email: one serving judgement under the app lock (ruled, P2 of round 2)
Ruled by Paul, 2026-11-14 ("Sure"): finish option 1, one invariant
enforced in one place. Fable's P2: instance create read the switch about
300 lines before its locks, so a switch-on in between let it write an
instance on an undeclared build; rebind had the same shape.
- judgeServing is the one judgement ("is this build declared, does this
environment hold the From"), replacing the gate family. It refuses
(logged) a caller that does not hold the app lock. Every serve, create
and rebind door calls it under the app lock immediately before its
write: the create at its record write (createRecordMarkedLocked,
createRecordWithLifetimeLocked, the claim create), with an early
lock-held check only before a private store's paid work; the rebind
inside its record lock.
- Guards: the static test now requires judgeServing (and counts the
record's environment as a serve writer, which lists the rebind door);
TestServingJudgedUnderTheLockBeforeEveryWrite drives every listed door
and fails a record, pointer or manifest write made without the
judgement under the lock.
- A re-declare while switched is serialised with the switch, refused
unless the mailer sends the new From, and delivered to every bundle
(PMS-C46).
- The simulation races create, pin, channel move, rebind and promote
into a switch-on, and runs a switch-on inside a create paused after its
channel read (Fable's probe; a new create stage seam). Store faults are
drawn from a door's whole range of operations, reads too, counted in a
dry pass against an overlay. It models environment release, enable and
re-declare, the hourly reap and a box that has not adopted. Kills
Fable's survivors: the default From first, the rebind gate, the team
config door's 502 (also its own test).
- The plan records the ruling, the SMTP credentials a failed switch-off
leaves at rest, and the restart gap on the way off.
Census: the record-write layer is restacked on main's g6 pool layer and
re-pins the doors that now judge; copySince pins the judgement's reads.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
25 files changed,
+1,041
−293
approved_platform_mail_submission_copy_test.go+1 −1docs/superpowers/plans/2026-11-13-platform-mail-submission.md+8 −0docs/superpowers/plans/platform-mail-submission-copy.json+6 −0internal/console/apicli.go+1 −1internal/console/apiinstances.go+42 −13internal/console/apimail.go+33 −1internal/console/apisubmission.go+26 −0internal/console/apisubmission_test.go+35 −4internal/console/apiupdates.go+1 −1internal/console/applocks.go+18 −0internal/console/channelmove.go+2 −2internal/console/copiespublication.go+4 −0internal/console/copysince_paths_test.go+4 −1internal/console/hostsused.go+6 −0internal/console/lifetimes_create.go+5 −0internal/console/pendinghandlers.go+1 −1internal/console/record_write_lock_test.go+0 −15internal/console/server.go+5 −2internal/console/submission_sim_test.go+553 −138internal/console/submissioncopy.go+5 −3internal/console/submissiongate.go+151 −96internal/console/submissiongate_test.go+114 −10internal/console/updatescore.go+2 −2internal/provision/platform_mail_submission_census_test.go+17 −1internal/provision/testdata/plan14-root-reads-platform-mail-submission.tsv+1 −1
CI passed — run details
diff --git a/approved_platform_mail_submission_copy_test.go b/approved_platform_mail_submission_copy_test.go| index be454e7e9..91b4b4571 100644 |
| --- a/approved_platform_mail_submission_copy_test.go |
| +++ b/approved_platform_mail_submission_copy_test.go |
| @@ -10,7 +10,7 @@ import ( |
| // submission switch (Task 6 step 0): the door's refusals and answers, the |
| // serve doors' build refusal, and the CLI's lines. |
| var platformMailSubmissionCopyIDs = []string{ |
| - "PMS-C1", "PMS-C2", "PMS-C3", "PMS-C4", "PMS-C5", "PMS-C6", "PMS-C7", "PMS-C8", "PMS-C9", "PMS-C10", "PMS-C11", "PMS-C12", "PMS-C13", "PMS-C14", "PMS-C15", "PMS-C16", "PMS-C17", "PMS-C18", "PMS-C19", "PMS-C20", "PMS-C21", "PMS-C22", "PMS-C23", "PMS-C24", "PMS-C25", "PMS-C26", "PMS-C27", "PMS-C28", "PMS-C29", "PMS-C30", "PMS-C31", "PMS-C32", "PMS-C33", "PMS-C34", "PMS-C35", "PMS-C36", "PMS-C37", "PMS-C38", "PMS-C39", "PMS-C40", "PMS-C41", "PMS-C42", "PMS-C43", "PMS-C44", "PMS-C45", |
| + "PMS-C1", "PMS-C2", "PMS-C3", "PMS-C4", "PMS-C5", "PMS-C6", "PMS-C7", "PMS-C8", "PMS-C9", "PMS-C10", "PMS-C11", "PMS-C12", "PMS-C13", "PMS-C14", "PMS-C15", "PMS-C16", "PMS-C17", "PMS-C18", "PMS-C19", "PMS-C20", "PMS-C21", "PMS-C22", "PMS-C23", "PMS-C24", "PMS-C25", "PMS-C26", "PMS-C27", "PMS-C28", "PMS-C29", "PMS-C30", "PMS-C31", "PMS-C32", "PMS-C33", "PMS-C34", "PMS-C35", "PMS-C36", "PMS-C37", "PMS-C38", "PMS-C39", "PMS-C40", "PMS-C41", "PMS-C42", "PMS-C43", "PMS-C44", "PMS-C45", "PMS-C46", |
| } |
| // Every string of the switch's copy record is in the file it names, byte |
diff --git a/docs/superpowers/plans/2026-11-13-platform-mail-submission.md b/docs/superpowers/plans/2026-11-13-platform-mail-submission.md| index 04c2137ac..f0500c3d0 100644 |
| --- a/docs/superpowers/plans/2026-11-13-platform-mail-submission.md |
| +++ b/docs/superpowers/plans/2026-11-13-platform-mail-submission.md |
| @@ -62,6 +62,14 @@ Plan choices that are not gaps, for the plan reviewer (each resolves an item on |
| - **P2-4:** for a switched app, a `DeliverMailFromIn` failure is returned to the door that created or adopted the environment, which answers it (no more log-and-swallow in `teamcreds.go`). The environment was written by then, so an instance create or rebind into an owned environment whose bundle lacks the From is refused too, with the remedy (switch on again, which delivers it). |
| - A randomised simulation test (`TestSubmissionChannelSimulation`) drives interleavings of switch on and off, promote, rollback, pin and channel moves, instance and environment creation, box arm and disarm, and injected AWS and store failures at each write, and asserts the invariant after every step. Mutation-checked: it catches each of P2-1 to P2-4 when its fix is removed. **Ruled by Paul, 2026-11-14.** |
| 3. **The platform binary's size ceiling: 65 MB, confirmed.** **Ruled by Paul, 2026-11-14.** |
| +4. **Finishing ruling 2 (Fable's review of 6b5f9f845, one P2: instance create raced the switch, reading it about 300 lines before its locks; the rebind door had the same shape).** **Ruled by Paul, 2026-11-14 ("Sure"): finish option 1, one invariant enforced in one place.** |
| + - **One judgement:** `judgeServing` (`internal/console/submissiongate.go`) is the only gate: "is this build declared, does this environment hold the From". Every serve, create and rebind door calls it under the app lock, immediately before its write, and it refuses (logged) a caller that does not hold the lock. The create door judges at the record write (`createRecordMarkedLocked`, `createRecordWithLifetimeLocked`, the claim create), with an early, lock-held check only before a private store's paid work; the rebind door judges inside its record lock. |
| + - **The guard:** `TestSubmissionGateCoversEveryServeDoor` (static: every route that reaches a serve writer, the record's environment now among them, reaches `judgeServing`) and `TestServingJudgedUnderTheLockBeforeEveryWrite` (dynamic: every listed door, driven, writes a record, a channel pointer or the instances manifest only after `judgeServing` ran under the app lock, and with the lock still held). |
| + - **A re-declare while switched** is serialised with the switch (the app lock), refused unless the box's mailer would send the new From, and delivered to every bundle at once. |
| + - **The simulation** races a create, a pin, a channel move, a rebind and a promote into a switch-on, and runs a whole switch-on inside a create paused after its channel read (Fable's probe). Its store faults are drawn from the whole range of a door's operations, reads and writes, counted in a dry pass of the door against an overlay. It models environment release, `email enable` and re-declare, the hourly reap, and a box that has not adopted yet. |
| + - **Stated, as Fable asked:** |
| + - After a switch-off that failed part-way, a switched app's bundles can hold the five `<P>_SMTP_*` (and an environment its own SMTP user) beside the From until the switch-off is run again; its instances use submission throughout (the agent sets `CARLOS_MAIL=submit`), so this is a credential at rest, not a second channel in use. |
| + - On the way off, a running instance started with `CARLOS_MAIL=submit` is refused by the mailer (`403 SUBMISSION_OFF`) from `On:false` until it restarts; the door asks every instance to restart at once. |
| The copy review (Task 6 P2-6) is still Paul's; the copy record stays a draft. |
diff --git a/docs/superpowers/plans/platform-mail-submission-copy.json b/docs/superpowers/plans/platform-mail-submission-copy.json| index d0ed031ba..8ed9fc5fc 100644 |
| --- a/docs/superpowers/plans/platform-mail-submission-copy.json |
| +++ b/docs/superpowers/plans/platform-mail-submission-copy.json |
| @@ -272,6 +272,12 @@ |
| "file": "internal/console/submissioncopy.go", |
| "text": "Environment %s was written, but email submission is on for %s and its From address couldn't be delivered, so no instance can use it yet. Run carlos email submission on --app %s again to deliver it.", |
| "note": "EnvironmentFromFailed" |
| + }, |
| + { |
| + "id": "PMS-C46", |
| + "file": "internal/console/submissioncopy.go", |
| + "text": "Declared, but email submission is on for %s and the new From couldn't reach every environment yet. Run carlos email submission on again to deliver it.", |
| + "note": "DeclaredFromUndelivered" |
| } |
| ] |
| } |
diff --git a/internal/console/apicli.go b/internal/console/apicli.go| index f9ef86c71..b0252a237 100644 |
| --- a/internal/console/apicli.go |
| +++ b/internal/console/apicli.go |
| @@ -1064,7 +1064,7 @@ func (s *Server) handleAPIPromote(w http.ResponseWriter, r *http.Request) { |
| jsonError(w, ref.Status, ref.Msg) |
| return |
| } |
| - if ref := s.submissionBuildRefusal(ctx, acct.Sqid, app, version); ref != nil { |
| + if ref := s.judgeServing(ctx, acct.Sqid, app, servingChange{version: version}); ref != nil { |
| jsonError(w, ref.Status, ref.Msg) |
| return |
| } |
diff --git a/internal/console/apiinstances.go b/internal/console/apiinstances.go| index d6149e4a1..73d07d04e 100644 |
| --- a/internal/console/apiinstances.go |
| +++ b/internal/console/apiinstances.go |
| @@ -72,6 +72,11 @@ const ( |
| // instanceCreateAfterRestoreProof: a restore's early restoreProof was |
| // eligible (instance restore #658); no lock is held. |
| instanceCreateAfterRestoreProof = "after-restore-proof" |
| + // instanceCreateAfterChannelCheck: the door has read the channel the |
| + // instance follows, where it used to judge the email submission switch |
| + // before any lock (ruled 2026-11-14: it now judges under the app lock at |
| + // the record write); no lock is held. |
| + instanceCreateAfterChannelCheck = "after-channel-check" |
| // instanceCreateAfterRecordWrite: the record write returned with the |
| // record written, still inside the app lock and the host exclusion |
| // (createRecordMarked, createRecordWithLifetime). |
| @@ -2155,18 +2160,24 @@ func (s *Server) handleAPIInstanceCreate(w http.ResponseWriter, r *http.Request) |
| jsonError(w, ref.Status, ref.Msg) |
| return |
| } |
| - if kind := strings.TrimSpace(req.Kind); kind == "" || kind == "instance" { |
| - if ref := s.submissionChannelRefusal(ctx, acct.Sqid, app, channel); ref != nil { |
| - jsonError(w, ref.Status, ref.Msg) |
| - return |
| - } |
| - // A switched app's owned environment must hold its From (P2-4, |
| - // ruled 2026-11-14). |
| - if ref := s.submissionEnvironmentRefusal(ctx, acct.Sqid, app, strings.TrimSpace(req.Environment)); ref != nil { |
| + if kind := strings.TrimSpace(req.Kind); m.PrivateStorage && (kind == "" || kind == "instance") { |
| + // Fail fast, before paid work (a private store is provisioned before |
| + // the record): the serving judgement under the app lock for its own |
| + // moment. The one that binds is made under the app lock immediately |
| + // before the record write, on every create |
| + // (createRecordMarkedLocked, createRecordWithLifetimeLocked, the |
| + // claim create), so a switch-on that lands in between is still |
| + // judged (ruled 2026-11-14). |
| + env := strings.TrimSpace(req.Environment) |
| + unlockApp := s.lockApp(acct.Sqid, app) |
| + ref := s.judgeServing(ctx, acct.Sqid, app, servingChange{channel: &channel, env: &env}) |
| + unlockApp() |
| + if ref != nil { |
| jsonError(w, ref.Status, ref.Msg) |
| return |
| } |
| } |
| + instanceCreateStage(instanceCreateAfterChannelCheck, host) |
| // Managed fleets 1b (rules 1, 7, 8): on a fleet the console labels, the |
| // record names the box that runs it. The fleet's lock is held from this |
| // read until the record is written, so concurrent creates count each |
| @@ -2587,6 +2598,13 @@ func (s *Server) handleAPIInstanceCreate(w http.ResponseWriter, r *http.Request) |
| jsonError(w, http.StatusServiceUnavailable, copiesUnread) |
| return |
| } |
| + // The claim create publishes the record under this hold |
| + // (finishClaimCreate), or re-takes it (finishCopiesClaimCreate): |
| + // the serving judgement, under it. |
| + if ref := s.judgeServing(createContext, acct.Sqid, app, servingChange{record: &rec}); ref != nil { |
| + writeDoorRefusal(w, ref) |
| + return |
| + } |
| var chooseErr error |
| if createContext, chooseErr = s.chooseCreateFirst(createContext, host, buildClaim); chooseErr != nil { |
| writeClaimResponseError(w, chooseErr) |
| @@ -3155,10 +3173,8 @@ func (s *Server) handleAPIInstanceUpdate(w http.ResponseWriter, r *http.Request) |
| } |
| // A switched app's owned environment must hold its From |
| // (P2-4, ruled 2026-11-14). |
| - if ref := s.submissionEnvironmentRefusal(ctx, acct.Sqid, app, rec.Environment); ref != nil { |
| - jsonError(w, ref.Status, ref.Msg) |
| - return |
| - } |
| + // The serving judgement of the new binding is made under the |
| + // record lock, immediately before the write, below. |
| } |
| } |
| } |
| @@ -3293,11 +3309,24 @@ func (s *Server) handleAPIInstanceUpdate(w http.ResponseWriter, r *http.Request) |
| if err := s.ownedBindingRecheck(lctx, *rec); err != nil { |
| return err |
| } |
| + // A rebind of a switched app's instance into an owned environment |
| + // without its From is refused (ruled 2026-11-14), under the app |
| + // lock, immediately before the write. |
| + if rec.Environment != stored.Environment { |
| + if ref := s.judgeServing(ctx, rec.Account, rec.App, servingChange{env: &rec.Environment}); ref != nil { |
| + return &statelessSelectionError{ref} |
| + } |
| + } |
| return provision.UpdateRecord(ctx, s.cfg.Releases, *rec, etag) |
| }); err != nil { |
| if writeOwnedBindingRefusal(w, err) { |
| return |
| } |
| + var selection *statelessSelectionError |
| + if errors.As(err, &selection) { |
| + writeDoorRefusal(w, selection.ref) |
| + return |
| + } |
| if errors.Is(err, release.ErrCASConflict) { |
| jsonError(w, http.StatusConflict, |
| "instance "+host+" changed while this request was in flight — read it again and re-apply") |
| @@ -3673,7 +3702,7 @@ func (s *Server) handleAPIInstanceEnable(w http.ResponseWriter, r *http.Request) |
| m.PrivateStorage = *req.PrivateStorage |
| } |
| if req.Channel != nil { |
| - if ref := s.submissionChannelRefusal(ctx, acct.Sqid, app, m.Channel); ref != nil { |
| + if ref := s.judgeServing(ctx, acct.Sqid, app, servingChange{channel: &m.Channel}); ref != nil { |
| jsonError(w, ref.Status, ref.Msg) |
| return |
| } |
diff --git a/internal/console/apimail.go b/internal/console/apimail.go| index 2fee472a1..bcde9bc41 100644 |
| --- a/internal/console/apimail.go |
| +++ b/internal/console/apimail.go |
| @@ -611,6 +611,23 @@ func (s *Server) handleAPIEmailDeclare(w http.ResponseWriter, r *http.Request) { |
| } |
| ctx, cancel := context.WithTimeout(r.Context(), mailTimeout) |
| defer cancel() |
| + // Under the app lock the switch door holds (ruled by Paul, 2026-11-14): |
| + // a switched app's declaration is its instances' From, so a re-declare |
| + // and a switch-on are never interleaved. |
| + defer s.lockApp(acct.Sqid, app)() |
| + switched, ref := s.submissionSwitched(ctx, acct.Sqid, app) |
| + if ref != nil { |
| + writeDoorRefusalJSON(w, r, ref) |
| + return |
| + } |
| + if switched { |
| + // While switched, the From goes to every instance's bundle at once, |
| + // so it must be one the box's mailer sends (one working channel). |
| + if ref := s.submissionFromRefusal(ctx, acct.Sqid, app, from); ref != nil { |
| + writeDoorRefusalJSON(w, r, ref) |
| + return |
| + } |
| + } |
| rec0, _, err := mail.Get(ctx, s.cfg.Releases, acct.Sqid, app) |
| if err != nil { |
| log.Printf("console: api email read %s/%s: %v", acct.Sqid, app, err) |
| @@ -639,7 +656,22 @@ func (s *Server) handleAPIEmailDeclare(w http.ResponseWriter, r *http.Request) { |
| if changed { |
| s.audit(acct, app, addr, "email-declare", "declared email with env prefix "+prefix+" from "+from+" (cli)") |
| } |
| - // No bumpSerial: a declaration touches nothing a box reads. |
| + if switched && changed { |
| + // A switched app's From is in every bundle: deliver the new one |
| + // there, as the switch did (its idempotent re-run), so every |
| + // instance sends as what is declared. |
| + envs, err := s.ownedEnvironmentNames(ctx, acct.Sqid, app) |
| + if err == nil { |
| + _, err = mail.SwitchOn(ctx, s.claimMailStore(), s.cfg.MailProvisioner, acct.Sqid, app, envs, addr, time.Now()) |
| + } |
| + if err != nil { |
| + log.Printf("console: api email declare %s/%s: deliver the From: %v", acct.Sqid, app, err) |
| + jsonError(w, http.StatusBadGateway, fmt.Sprintf(submissionCopy.DeclaredFromUndelivered, app)) |
| + return |
| + } |
| + s.bumpSerial(ctx) |
| + } |
| + // No bumpSerial otherwise: a declaration touches nothing a box reads. |
| out, err := s.emailReply(ctx, acct, app, rec) |
| if err != nil { |
| log.Printf("console: api email reply %s/%s: %v", acct.Sqid, app, err) |
diff --git a/internal/console/apisubmission.go b/internal/console/apisubmission.go| index d1b4c080e..f98192ef4 100644 |
| --- a/internal/console/apisubmission.go |
| +++ b/internal/console/apisubmission.go |
| @@ -560,6 +560,32 @@ func (s *Server) mailCallerCounts(ctx context.Context, acct, app, day string, re |
| return s.store.MailCallerSends(ctx, acct, app, day) |
| } |
| +// submissionFromRefusal is the box mailer's own rule for a From, as the |
| +// switch door applies it (mailwire.CheckFromDomain): nil when the mailer |
| +// would send as from for acct/app. |
| +func (s *Server) submissionFromRefusal(ctx context.Context, acct, app, from string) *doorRefusal { |
| + region := s.cfg.MailDeployment.Region |
| + domain := strings.ToLower(from[strings.LastIndexByte(from, '@')+1:]) |
| + sn, _, err := mail.GetSender(ctx, s.claimMailStore(), acct, app, mail.SenderAppID) |
| + if err != nil { |
| + log.Printf("console: email from %s/%s: read sender: %v", acct, app, err) |
| + return &doorRefusal{Status: http.StatusBadGateway, Msg: submissionCopy.SwitchFailed} |
| + } |
| + var granted []string |
| + if sn != nil && sn.Grant != nil { |
| + granted = sn.Grant.Domains |
| + } |
| + dv, err := s.submissionDomainView(ctx, acct, domain) |
| + if err != nil { |
| + log.Printf("console: email from %s/%s: domain %s: %v", acct, app, domain, err) |
| + return &doorRefusal{Status: http.StatusBadGateway, Msg: submissionCopy.SwitchFailed} |
| + } |
| + if mailwire.CheckFromDomain(granted, domain, app, region, dv) != mailwire.FromSendable { |
| + return &doorRefusal{Status: http.StatusConflict, Msg: fmt.Sprintf(submissionCopy.FromNotSendable, from, domain, region)} |
| + } |
| + return nil |
| +} |
| + |
| // submissionDomainView reads a domain record as the mailer does |
| // (mailwire.DomainView, by key): nil when absent. |
| func (s *Server) submissionDomainView(ctx context.Context, acct, domain string) (*mailwire.DomainView, error) { |
diff --git a/internal/console/apisubmission_test.go b/internal/console/apisubmission_test.go| index cfe243ed6..0dde0be8e 100644 |
| --- a/internal/console/apisubmission_test.go |
| +++ b/internal/console/apisubmission_test.go |
| @@ -464,11 +464,19 @@ func TestSubmissionDoorMoreRefusals(t *testing.T) { |
| } |
| // The serve gate's read of the switch fails closed: an unreadable |
| - // sender record is a 502, never "off". |
| - if ref := w.fx.srv.submissionBuildRefusal(ctx, "bab", "titogo", "v1"); ref == nil || ref.Status != http.StatusConflict { |
| + // sender record is a 502, never "off". The judgement is made under the |
| + // app lock, which it refuses without (ruled 2026-11-14). |
| + judge := func(version string) *doorRefusal { |
| + defer w.fx.srv.lockApp("bab", "titogo")() |
| + return w.fx.srv.judgeServing(ctx, "bab", "titogo", servingChange{version: version}) |
| + } |
| + if ref := w.fx.srv.judgeServing(ctx, "bab", "titogo", servingChange{version: "v2"}); ref == nil || ref.Status != http.StatusInternalServerError { |
| + t.Fatalf("judged without the app lock: %+v, want the 500 refusal", ref) |
| + } |
| + if ref := judge("v1"); ref == nil || ref.Status != http.StatusConflict { |
| t.Fatalf("switched, undeclared v1: %+v", ref) |
| } |
| - if ref := w.fx.srv.submissionBuildRefusal(ctx, "bab", "titogo", "v-missing"); ref == nil || ref.Status != http.StatusBadGateway { |
| + if ref := judge("v-missing"); ref == nil || ref.Status != http.StatusBadGateway { |
| t.Fatalf("switched, unreadable manifest: %+v, want 502", ref) |
| } |
| sk := mailwire.SenderKey("bab", "titogo", mailwire.SenderAppID) |
| @@ -476,7 +484,7 @@ func TestSubmissionDoorMoreRefusals(t *testing.T) { |
| if _, err := w.fx.rel.Put(ctx, sk, []byte("{not json"), setag); err != nil { |
| t.Fatal(err) |
| } |
| - if ref := w.fx.srv.submissionBuildRefusal(ctx, "bab", "titogo", "v2"); ref == nil || ref.Status != http.StatusBadGateway { |
| + if ref := judge("v2"); ref == nil || ref.Status != http.StatusBadGateway { |
| t.Fatalf("unreadable sender: %+v, want 502", ref) |
| } |
| } |
| @@ -571,3 +579,26 @@ func TestSubmissionDoorChecksEveryGrantedDomain(t *testing.T) { |
| t.Fatalf("every granted domain associated: %d %s", status, out) |
| } |
| } |
| + |
| +// P2-4 (ruled 2026-11-14), the team config door: a team credential's |
| +// config write that brings an owned environment into being while the app |
| +// is switched, whose From cannot be delivered, answers 502 with the |
| +// remedy, never 200; the environment it wrote has no From, and an instance |
| +// cannot be created into it. |
| +func TestTeamConfigDoorAnswersAFailedFrom(t *testing.T) { |
| + w := newSubmissionWorld(t, "code-submission-team-from") |
| + w.switchOn(t) |
| + faults := &simFaultStore{base: w.fx.srv.cfg.Releases, prefix: "apps/bab/titogo/"} |
| + w.fx.srv.cfg.Releases = faults |
| + // The new environment's first write makes it; the second is its From. |
| + faults.armMatching("environments/crew.json", 2) |
| + team := teamToken(t, w.fx.st, OpsAccountID, "alta-titogo", "titogo", "alta") |
| + body := `{"environment":"crew","set":{"TEAM_ONLY":{"kind":"env","value":"1"}}}` |
| + status, _, out := rawReq(t, http.MethodPut, w.fx.ts.URL+"/api/cli/apps/bab/titogo/config", team, body) |
| + if status != http.StatusBadGateway || !strings.Contains(out, "its From address couldn't be delivered") { |
| + t.Fatalf("team config create with the From's write failing: %d %s, want 502 naming the From", status, out) |
| + } |
| + if vars := w.vars(t, "crew"); vars["TITO_MAIL_FROM"].Value != "" { |
| + t.Fatalf("crew holds a From after its write failed: %v", vars) |
| + } |
| +} |
diff --git a/internal/console/apiupdates.go b/internal/console/apiupdates.go| index 43cc2f20e..827a1096c 100644 |
| --- a/internal/console/apiupdates.go |
| +++ b/internal/console/apiupdates.go |
| @@ -412,7 +412,7 @@ func (s *Server) handleAPIUpdatesPolicy(w http.ResponseWriter, r *http.Request) |
| jsonError(w, ref.Status, ref.Msg) |
| return |
| } |
| - if ref := s.submissionPolicyRefusal(ctx, acct.Sqid, app, before, next, m.Channel, nextChannel); ref != nil { |
| + if ref := s.judgeServing(ctx, acct.Sqid, app, servingChange{policy: &servingPolicy{before: before, next: next, channel: m.Channel, nextChannel: nextChannel}}); ref != nil { |
| jsonError(w, ref.Status, ref.Msg) |
| return |
| } |
diff --git a/internal/console/applocks.go b/internal/console/applocks.go| index 2820ec0a3..94c70ab09 100644 |
| --- a/internal/console/applocks.go |
| +++ b/internal/console/applocks.go |
| @@ -70,6 +70,24 @@ func (s *Server) lockApp(sqid, app string) func() { |
| } |
| } |
| +// held reports whether key's mutex is held now, by anyone. The serving |
| +// judgement (judgeServing) asserts with it that its caller holds the app |
| +// lock: it cannot say whose hold it sees, but a caller that forgot the |
| +// lock is caught whenever no other request holds it. |
| +func (l *keyedLocks) held(key string) bool { |
| + l.mu.Lock() |
| + defer l.mu.Unlock() |
| + e := l.m[key] |
| + if e == nil { |
| + return false |
| + } |
| + if e.mu.TryLock() { |
| + e.mu.Unlock() |
| + return false |
| + } |
| + return true |
| +} |
| + |
| // tryLock avoids reversing app-before-fleet order in a background pass. |
| // A busy app is retried on the existing fleet pass. |
| func (l *keyedLocks) tryLock(key string) (func(), bool) { |
diff --git a/internal/console/channelmove.go b/internal/console/channelmove.go| index 0f2db88a2..25bc3ef2a 100644 |
| --- a/internal/console/channelmove.go |
| +++ b/internal/console/channelmove.go |
| @@ -186,7 +186,7 @@ func (s *Server) handleAPIInstanceChannel(w http.ResponseWriter, r *http.Request |
| jsonError(w, ref.Status, ref.Msg) |
| return |
| } |
| - if ref := s.submissionRecordRefusal(ctx, *rec); ref != nil { |
| + if ref := s.judgeServing(ctx, rec.Account, rec.App, servingChange{record: rec}); ref != nil { |
| jsonError(w, ref.Status, ref.Msg) |
| return |
| } |
| @@ -241,7 +241,7 @@ func (s *Server) executePendingRouteChannel(ctx context.Context, acct *Account, |
| if ref := s.copiesRecordRefusal(ctx, acct, *rec, false); ref != nil { |
| return "", &statelessSelectionError{ref} |
| } |
| - if ref := s.submissionRecordRefusal(ctx, *rec); ref != nil { |
| + if ref := s.judgeServing(ctx, rec.Account, rec.App, servingChange{record: rec}); ref != nil { |
| return "", &statelessSelectionError{ref} |
| } |
| if err := provision.UpdateRecord(ctx, s.cfg.Releases, *rec, etag); err != nil { |
diff --git a/internal/console/copiespublication.go b/internal/console/copiespublication.go| index c91eb9162..7138caf16 100644 |
| --- a/internal/console/copiespublication.go |
| +++ b/internal/console/copiespublication.go |
| @@ -379,6 +379,10 @@ func (s *Server) finishCopiesClaimCreate(w http.ResponseWriter, q *claimCreateRe |
| jsonError(w, http.StatusServiceUnavailable, copiesUnread) |
| return false |
| } |
| + if ref := s.judgeServing(ctx, acct.Sqid, app, servingChange{record: &rec}); ref != nil { |
| + jsonError(w, ref.Status, ref.Msg) |
| + return false |
| + } |
| if ref := s.copiesRecordRefusal(ctx, acct, rec, true); ref != nil { |
| jsonError(w, ref.Status, ref.Msg) |
| return false |
diff --git a/internal/console/copysince_paths_test.go b/internal/console/copysince_paths_test.go| index 9ff13bdc9..35845217a 100644 |
| --- a/internal/console/copysince_paths_test.go |
| +++ b/internal/console/copysince_paths_test.go |
| @@ -455,7 +455,10 @@ var copyInventory = map[string]map[string]int{ |
| // none: the mailer_unarmed alert decodes a switched app's instance |
| // records for their hosts (platform mail submission Task 6); it |
| // writes nothing. |
| - "(*internal/console.engineReads).switchedRecordHosts": 1, |
| + "(*internal/console.engineReads).switchedRecordHosts": 1, |
| + // none: the serving judgement (ruled 2026-11-14) reads the two |
| + // records of an update-settings change it judges; it writes nothing. |
| + "(*internal/console.Server).judgeServing": 2, |
| "(*internal/console.Server).migrationFinishLocked": 1, |
| "(*internal/console.Server).movesRecovery": 1, |
| "(*internal/console.Server).restoreProof": 1, |
diff --git a/internal/console/hostsused.go b/internal/console/hostsused.go| index d3868a2f5..44fe52889 100644 |
| --- a/internal/console/hostsused.go |
| +++ b/internal/console/hostsused.go |
| @@ -703,6 +703,12 @@ func (s *Server) createRecordMarkedLocked(ctx context.Context, rec provision.Rec |
| if err := s.copiesCreateCheck(ctx, &rec); err != nil { |
| return nil, err |
| } |
| + // The serving judgement (ruled 2026-11-14), under the app lock, before |
| + // the write: a switched app's instance serves a declared build and |
| + // binds an environment holding its From. |
| + if ref := s.judgeServing(ctx, rec.Account, rec.App, servingChange{record: &rec}); ref != nil { |
| + return nil, &statelessSelectionError{ref} |
| + } |
| // The regional recheck (spec §6.3): a regional claim written since the |
| // door's first check refuses the create before anything is marked. |
| if err := s.regionalRecheck(ctx, rec); err != nil { |
diff --git a/internal/console/lifetimes_create.go b/internal/console/lifetimes_create.go| index ad0a5dbf8..812388642 100644 |
| --- a/internal/console/lifetimes_create.go |
| +++ b/internal/console/lifetimes_create.go |
| @@ -87,6 +87,11 @@ func (s *Server) createRecordWithLifetimeLocked(ctx context.Context, rec provisi |
| if err := s.copiesCreateCheck(ctx, &rec); err != nil { |
| return nil, err |
| } |
| + // The serving judgement (ruled 2026-11-14), under the app lock the |
| + // caller holds, before the write. |
| + if ref := s.judgeServing(ctx, rec.Account, rec.App, servingChange{record: &rec}); ref != nil { |
| + return nil, &statelessSelectionError{ref} |
| + } |
| // The regional recheck (#447, spec §6.3 rev 5): the door's claim check |
| // ran before any lock, so a regional claim written since is caught here, |
| // under the hostname exclusion and before BeginAllocation. A refusal |
diff --git a/internal/console/pendinghandlers.go b/internal/console/pendinghandlers.go| index d02eba865..da3dae398 100644 |
| --- a/internal/console/pendinghandlers.go |
| +++ b/internal/console/pendinghandlers.go |
| @@ -571,7 +571,7 @@ func (s *Server) executePendingPromote(ctx context.Context, acct *Account, app, |
| if ref := s.copiesPublicationRefusal(ctx, acct, app, nil, p.Version, false); ref != nil { |
| return "", &statelessSelectionError{ref} |
| } |
| - if ref := s.submissionBuildRefusal(ctx, acct.Sqid, app, p.Version); ref != nil { |
| + if ref := s.judgeServing(ctx, acct.Sqid, app, servingChange{version: p.Version}); ref != nil { |
| return "", &statelessSelectionError{ref} |
| } |
| // A replicated release retry (R1) is judged before the pointer is |
diff --git a/internal/console/record_write_lock_test.go b/internal/console/record_write_lock_test.go| index 098561f65..3572cc6cd 100644 |
| --- a/internal/console/record_write_lock_test.go |
| +++ b/internal/console/record_write_lock_test.go |
| @@ -187,21 +187,6 @@ func witnessLockHeld(ds *deletableStore, key string) bool { |
| return false |
| } |
| -// held reports whether key's mutex is held now, by anyone. |
| -func (l *keyedLocks) held(key string) bool { |
| - l.mu.Lock() |
| - defer l.mu.Unlock() |
| - e := l.m[key] |
| - if e == nil { |
| - return false |
| - } |
| - if e.mu.TryLock() { |
| - e.mu.Unlock() |
| - return false |
| - } |
| - return true |
| -} |
| - |
| // consoleCaller walks the write's stack, past the store doubles and any |
| // other package (release, provision), to the first frame in |
| // internal/console, and reports its function and whether it is console code. |
diff --git a/internal/console/server.go b/internal/console/server.go| index 413d6d344..4c20b9f3f 100644 |
| --- a/internal/console/server.go |
| +++ b/internal/console/server.go |
| @@ -1029,6 +1029,9 @@ type Server struct { |
| // submission door at its stages: "locked" once it holds the app lock, |
| // "checked" once switch-on's preconditions pass, before the switch. |
| submissionSwitchHook func(on bool, stage string) |
| + // servingJudged, when set (tests only), is called by judgeServing each |
| + // time it judges, once it has confirmed the app lock is held. |
| + servingJudged func(acct, app string) |
| sourceDownloads sourceDownloads |
| haPools map[string][]string |
| haScopeInvalid bool |
| @@ -5997,7 +6000,7 @@ func (s *Server) handlePromote(w http.ResponseWriter, r *http.Request) { |
| back("err", ref.Msg) |
| return |
| } |
| - if ref := s.submissionBuildRefusal(ctx, acct.Sqid, app, version); ref != nil { |
| + if ref := s.judgeServing(ctx, acct.Sqid, app, servingChange{version: version}); ref != nil { |
| back("err", ref.Msg) |
| return |
| } |
| @@ -6735,7 +6738,7 @@ func (s *Server) handleNewCanary(w http.ResponseWriter, r *http.Request) { |
| back("err", ref.Msg) |
| return |
| } |
| - if ref := s.submissionBuildRefusal(ctx, acct.Sqid, app, version); ref != nil { |
| + if ref := s.judgeServing(ctx, acct.Sqid, app, servingChange{version: version}); ref != nil { |
| back("err", ref.Msg) |
| return |
| } |
diff --git a/internal/console/submission_sim_test.go b/internal/console/submission_sim_test.go| index 1ae4a12c8..41ed42592 100644 |
| --- a/internal/console/submission_sim_test.go |
| +++ b/internal/console/submission_sim_test.go |
| @@ -2,10 +2,13 @@ package console |
| import ( |
| "context" |
| + "encoding/json" |
| "errors" |
| "fmt" |
| + "maps" |
| "math/rand" |
| "net/http" |
| + "os" |
| "slices" |
| "strings" |
| "sync" |
| @@ -14,6 +17,7 @@ import ( |
| "github.com/carlosframework/platform/internal/appconfig" |
| "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/status" |
| @@ -37,53 +41,211 @@ import ( |
| // answered 2xx for an environment of a switched app must have left its |
| // From there (P2-4). |
| -// simFaultStore fails the nth write (Put or Delete) to a key under prefix, |
| -// once, when armed; with match set, only keys holding match count. |
| +// simFaultStore fails, once, when armed, the nth store operation under |
| +// prefix: the nth write (Put or Delete), or with reads set the nth |
| +// operation of any kind (Get and List too); with match set, only keys |
| +// holding match count. During a dry pass it sends every operation to an |
| +// overlay instead and counts them (beginDry, endDry), so a fault is drawn |
| +// from the whole range of what the door does. |
| type simFaultStore struct { |
| - release.Store |
| - mu sync.Mutex |
| - prefix string |
| - match string |
| - failAt int // 0: off |
| - writes int |
| + base release.Store |
| + mu sync.Mutex |
| + prefix string |
| + match string |
| + reads bool |
| + failAt int // 0: off |
| + n int |
| + overlay *simOverlay |
| + dryOps int |
| } |
| var errSimFault = errors.New("simulated store failure") |
| func (f *simFaultStore) arm(n int) { f.armMatching("", n) } |
| +// armMatching fails the nth write to a key holding match. |
| func (f *simFaultStore) armMatching(match string, n int) { |
| f.mu.Lock() |
| defer f.mu.Unlock() |
| - f.match, f.failAt, f.writes = match, n, 0 |
| + f.match, f.reads, f.failAt, f.n = match, false, n, 0 |
| } |
| -func (f *simFaultStore) hit(key string) bool { |
| +// armOps fails the nth operation, read or write. |
| +func (f *simFaultStore) armOps(n int) { |
| f.mu.Lock() |
| defer f.mu.Unlock() |
| - if f.failAt == 0 || !strings.HasPrefix(key, f.prefix) || !strings.Contains(key, f.match) { |
| + f.match, f.reads, f.failAt, f.n = "", true, n, 0 |
| +} |
| + |
| +func (f *simFaultStore) beginDry() { |
| + f.mu.Lock() |
| + defer f.mu.Unlock() |
| + f.overlay, f.dryOps = &simOverlay{base: f.base, objs: map[string][]byte{}, gone: map[string]bool{}}, 0 |
| +} |
| + |
| +func (f *simFaultStore) endDry() int { |
| + f.mu.Lock() |
| + defer f.mu.Unlock() |
| + f.overlay = nil |
| + return f.dryOps |
| +} |
| + |
| +func (f *simFaultStore) store() release.Store { |
| + f.mu.Lock() |
| + defer f.mu.Unlock() |
| + if f.overlay != nil { |
| + return f.overlay |
| + } |
| + return f.base |
| +} |
| + |
| +func (f *simFaultStore) hit(key string, read bool) bool { |
| + f.mu.Lock() |
| + defer f.mu.Unlock() |
| + if !strings.HasPrefix(key, f.prefix) { |
| return false |
| } |
| - f.writes++ |
| - if f.writes == f.failAt { |
| + if f.overlay != nil { |
| + f.dryOps++ |
| + return false |
| + } |
| + if f.failAt == 0 || (read && !f.reads) || !strings.Contains(key, f.match) { |
| + return false |
| + } |
| + f.n++ |
| + if f.n == f.failAt { |
| f.failAt = 0 |
| return true |
| } |
| return false |
| } |
| +func (f *simFaultStore) Get(ctx context.Context, key string) ([]byte, string, error) { |
| + if f.hit(key, true) { |
| + return nil, "", errSimFault |
| + } |
| + return f.store().Get(ctx, key) |
| +} |
| + |
| +func (f *simFaultStore) List(ctx context.Context, prefix string) ([]string, error) { |
| + if f.hit(prefix, true) { |
| + return nil, errSimFault |
| + } |
| + return f.store().List(ctx, prefix) |
| +} |
| + |
| +func (f *simFaultStore) ListDirs(ctx context.Context, prefix string) ([]string, error) { |
| + if f.hit(prefix, true) { |
| + return nil, errSimFault |
| + } |
| + return f.store().ListDirs(ctx, prefix) |
| +} |
| + |
| func (f *simFaultStore) Put(ctx context.Context, key string, body []byte, ifMatch string) (string, error) { |
| - if f.hit(key) { |
| + if f.hit(key, false) { |
| return "", errSimFault |
| } |
| - return f.Store.Put(ctx, key, body, ifMatch) |
| + return f.store().Put(ctx, key, body, ifMatch) |
| } |
| func (f *simFaultStore) Delete(ctx context.Context, key string) error { |
| - if f.hit(key) { |
| + if f.hit(key, false) { |
| return errSimFault |
| } |
| - return f.Store.Delete(ctx, key) |
| + return f.store().Delete(ctx, key) |
| +} |
| + |
| +// simOverlay is a dry pass's store: reads see the base under the pass's |
| +// own writes, which never reach the base. Its etags and CAS rules are the |
| +// DirStore's (sha256 of the body; "" creates only). |
| +type simOverlay struct { |
| + base release.Store |
| + mu sync.Mutex |
| + objs map[string][]byte |
| + gone map[string]bool |
| +} |
| + |
| +func (o *simOverlay) Get(ctx context.Context, key string) ([]byte, string, error) { |
| + o.mu.Lock() |
| + b, ok := o.objs[key] |
| + gone := o.gone[key] |
| + o.mu.Unlock() |
| + switch { |
| + case gone: |
| + return nil, "", fmt.Errorf("overlay: %s: %w", key, os.ErrNotExist) |
| + case ok: |
| + return slices.Clone(b), simEtag(b), nil |
| + } |
| + return o.base.Get(ctx, key) |
| +} |
| + |
| +func (o *simOverlay) Put(ctx context.Context, key string, body []byte, ifMatch string) (string, error) { |
| + _, cur, err := o.Get(ctx, key) |
| + exists := err == nil |
| + if err != nil && !errors.Is(err, os.ErrNotExist) { |
| + return "", err |
| + } |
| + if (ifMatch == "" && exists) || (ifMatch != "" && (!exists || cur != ifMatch)) { |
| + return "", fmt.Errorf("overlay: %s: %w", key, release.ErrCASConflict) |
| + } |
| + o.mu.Lock() |
| + defer o.mu.Unlock() |
| + o.objs[key] = slices.Clone(body) |
| + delete(o.gone, key) |
| + return simEtag(body), nil |
| +} |
| + |
| +func (o *simOverlay) Delete(ctx context.Context, key string) error { |
| + o.mu.Lock() |
| + defer o.mu.Unlock() |
| + delete(o.objs, key) |
| + o.gone[key] = true |
| + return nil |
| +} |
| + |
| +func (o *simOverlay) List(ctx context.Context, prefix string) ([]string, error) { |
| + keys, err := o.base.List(ctx, prefix) |
| + if err != nil { |
| + return nil, err |
| + } |
| + o.mu.Lock() |
| + defer o.mu.Unlock() |
| + set := map[string]bool{} |
| + for _, k := range keys { |
| + if !o.gone[k] { |
| + set[k] = true |
| + } |
| + } |
| + for k := range o.objs { |
| + if strings.HasPrefix(k, prefix) { |
| + set[k] = true |
| + } |
| + } |
| + return slices.Sorted(maps.Keys(set)), nil |
| +} |
| + |
| +func (o *simOverlay) ListDirs(ctx context.Context, prefix string) ([]string, error) { |
| + dirs, err := o.base.ListDirs(ctx, prefix) |
| + if err != nil { |
| + return nil, err |
| + } |
| + if !strings.HasSuffix(prefix, "/") { |
| + prefix += "/" |
| + } |
| + o.mu.Lock() |
| + defer o.mu.Unlock() |
| + set := map[string]bool{} |
| + for _, d := range dirs { |
| + set[d] = true |
| + } |
| + for k := range o.objs { |
| + if rest, ok := strings.CutPrefix(k, prefix); ok { |
| + if i := strings.Index(rest, "/"); i >= 0 { |
| + set[prefix+rest[:i+1]] = true |
| + } |
| + } |
| + } |
| + return slices.Sorted(maps.Keys(set)), nil |
| } |
| // simProvisionerFaults are the AWS calls a switch or an environment walk |
| @@ -91,16 +253,18 @@ func (f *simFaultStore) Delete(ctx context.Context, key string) error { |
| var simProvisionerFaults = []string{"EnsureUser", "MintKey", "ReapKeys", "DeleteUser", "SetKeyActive", "DeleteKey"} |
| type channelSim struct { |
| - t *testing.T |
| - w *submissionWorld |
| - rng *rand.Rand |
| - faults *simFaultStore |
| - prov *mail.MemProvisioner |
| - hosts []string |
| - envs []string // owned environments: "team" and the forks |
| - armed bool |
| - nextID int |
| - steps []string |
| + t *testing.T |
| + w *submissionWorld |
| + rng *rand.Rand |
| + faults *simFaultStore |
| + prov *mail.MemProvisioner |
| + team string // a team credential of scope alta |
| + hosts []string |
| + envs []string // owned environments: "team" and the made ones |
| + reported map[string]string |
| + dry bool // a dry pass: no bookkeeping, no honesty checks |
| + nextID int |
| + steps []string |
| } |
| func newChannelSim(t *testing.T, seed int64) *channelSim { |
| @@ -111,7 +275,8 @@ func newChannelSim(t *testing.T, seed int64) *channelSim { |
| // every serve door is open to the owner's CLI token. |
| seedChannel(t, w.fx, "titogo", "edge", "v2") |
| seedChannel(t, w.fx, "titogo", "beta", "v2") |
| - // v1 promoted once, where no instance follows it, so it can be pinned. |
| + // v1 promoted once, onto canary, which no instance follows yet, so it |
| + // can be pinned, and created or moved onto (an undeclared head). |
| seedChannel(t, w.fx, "titogo", "canary", "v1") |
| w.fx.srv.cli.write = newRateLimiter(1<<20, time.Minute) |
| rec, etag, err := provision.GetRecordETag(ctx, w.fx.rel, "bab", "titogo", submissionHost) |
| @@ -123,10 +288,11 @@ func newChannelSim(t *testing.T, seed int64) *channelSim { |
| t.Fatal(err) |
| } |
| sim := &channelSim{t: t, w: w, rng: rand.New(rand.NewSource(seed)), prov: w.fx.srv.cfg.MailProvisioner.(*mail.MemProvisioner), |
| - hosts: []string{submissionHost}, envs: []string{"team"}, armed: true} |
| - sim.faults = &simFaultStore{Store: w.fx.srv.cfg.Releases, prefix: "apps/bab/titogo/"} |
| + team: teamToken(t, w.fx.st, OpsAccountID, fmt.Sprintf("alta-sim-%d", seed), "titogo", "alta"), |
| + hosts: []string{submissionHost}, envs: []string{"team"}, reported: map[string]string{}} |
| + sim.faults = &simFaultStore{base: w.fx.srv.cfg.Releases, prefix: "apps/bab/titogo/"} |
| w.fx.srv.cfg.Releases = sim.faults |
| - sim.boxTick(true) |
| + sim.boxTick(true, false) |
| return sim |
| } |
| @@ -163,46 +329,30 @@ func (sim *channelSim) records() []provision.Record { |
| return recs |
| } |
| -// boxTick writes box-1's report: armed or not, and serving what each |
| -// record resolves to, as a box that has adopted every change would. |
| -func (sim *channelSim) boxTick(armed bool) { |
| +// boxTick writes box-1's report, armed or not. A box that adopts serves |
| +// what each record resolves to; a lagging one keeps, for about half the |
| +// hosts it already serves, the build it was serving. |
| +func (sim *channelSim) boxTick(armed, lagging bool) { |
| sim.t.Helper() |
| - sim.armed = armed |
| versions := map[string]string{} |
| for _, rec := range sim.records() { |
| + if old, ok := sim.reported[rec.Host]; ok && lagging && sim.rng.Intn(2) == 0 { |
| + versions[rec.Host] = old |
| + continue |
| + } |
| if v := sim.resolved(rec); v != "" { |
| versions[rec.Host] = v |
| } |
| } |
| + sim.reported = versions |
| b := status.CollectBox(nil, status.Probes{MachineID: "box-1"}, time.Now()) |
| b.Label = "box-1" |
| - b.Metrics = &status.BoxMetrics{RouteVersions: versions, MailerArmed: armed, UpdateSettings: status.UpdateSettingsProtocol} |
| + b.Metrics = &status.BoxMetrics{RouteVersions: maps.Clone(versions), MailerArmed: armed, UpdateSettings: status.UpdateSettingsProtocol} |
| if err := status.WriteBox(context.Background(), sim.w.fx.rel, b); err != nil { |
| sim.t.Fatal(err) |
| } |
| } |
| -// armFault arms, sometimes, one failure for the next door: the nth store |
| -// write under the app, or one AWS call. |
| -func (sim *channelSim) armFault() string { |
| - switch sim.rng.Intn(10) { |
| - case 0, 1, 2: |
| - n := 1 + sim.rng.Intn(6) |
| - sim.faults.arm(n) |
| - return fmt.Sprintf(" [store write #%d fails]", n) |
| - case 3, 4: |
| - m := simProvisionerFaults[sim.rng.Intn(len(simProvisionerFaults))] |
| - sim.prov.FailNext = map[string]error{m: errors.New("simulated AWS failure")} |
| - return " [" + m + " fails]" |
| - } |
| - return "" |
| -} |
| - |
| -func (sim *channelSim) disarm() { |
| - sim.faults.arm(0) |
| - sim.prov.FailNext = nil |
| -} |
| - |
| func (sim *channelSim) pick(xs []string) string { return xs[sim.rng.Intn(len(xs))] } |
| // switched reads the app sender's switch. |
| @@ -222,6 +372,7 @@ func (sim *channelSim) bundleVars(env string) map[string]appconfig.Var { |
| sim.t.Helper() |
| ctx := context.Background() |
| out := map[string]appconfig.Var{} |
| + var overlay map[string]appconfig.Var |
| if env != "" { |
| m, _, found, err := appconfig.GetEnvironment(ctx, sim.w.fx.rel, "bab", "titogo", env) |
| if err != nil { |
| @@ -231,25 +382,52 @@ func (sim *channelSim) bundleVars(env string) map[string]appconfig.Var { |
| return m.Vars |
| } |
| if found { |
| - defer func() { |
| - for k, v := range m.Vars { |
| - out[k] = v |
| - } |
| - }() |
| + overlay = m.Vars |
| } |
| } |
| def, err := appconfig.Get(ctx, sim.w.fx.rel, "bab", "titogo") |
| if err != nil { |
| sim.t.Fatal(err) |
| } |
| - for k, v := range def.Vars { |
| - out[k] = v |
| - } |
| + maps.Copy(out, def.Vars) |
| + maps.Copy(out, overlay) |
| return out |
| } |
| +// sendable reports whether the box's mailer would send as from for the |
| +// app: the mailer's own rule (mailwire.CheckFromDomain). |
| +func (sim *channelSim) sendable(sn *mail.Sender, from string) bool { |
| + at := strings.LastIndexByte(from, '@') |
| + if at < 0 { |
| + return false |
| + } |
| + domain := strings.ToLower(from[at+1:]) |
| + var granted []string |
| + if sn.Grant != nil { |
| + granted = sn.Grant.Domains |
| + } |
| + body, _, err := sim.w.fx.rel.Get(context.Background(), mailwire.DomainKey("bab", domain)) |
| + var dv *mailwire.DomainView |
| + if err == nil { |
| + dv = &mailwire.DomainView{} |
| + if json.Unmarshal(body, dv) != nil { |
| + dv = nil |
| + } |
| + } |
| + return mailwire.CheckFromDomain(granted, domain, "titogo", sim.w.fx.srv.cfg.MailDeployment.Region, dv) == mailwire.FromSendable |
| +} |
| + |
| +// declared reports whether version's manifest declares --mail submit. |
| +func (sim *channelSim) declared(version string) bool { |
| + m, err := release.GetManifest(context.Background(), sim.w.fx.rel, "bab", "titogo", version) |
| + return err == nil && m.Mail == release.MailSubmit |
| +} |
| + |
| // check asserts the invariant after a step. wasSwitched is the switch |
| // before it: a step that turned it off must leave every instance on SMTP. |
| +// While switched, every instance resolves to a declared build (and a box |
| +// that has not adopted yet serves a declared one too), and its bundle |
| +// holds a From the box's mailer sends. |
| func (sim *channelSim) check(wasSwitched bool) { |
| sim.t.Helper() |
| ctx := context.Background() |
| @@ -268,13 +446,14 @@ func (sim *channelSim) check(wasSwitched bool) { |
| vars := sim.bundleVars(rec.Environment) |
| switch { |
| case switched: |
| - v := sim.resolved(rec) |
| - m, err := release.GetManifest(ctx, sim.w.fx.rel, "bab", "titogo", v) |
| - if v != "" && (err != nil || m.Mail != release.MailSubmit) { |
| + if v := sim.resolved(rec); v != "" && !sim.declared(v) { |
| bad = append(bad, fmt.Sprintf("%s serves %s, which does not declare --mail submit", rec.Host, v)) |
| } |
| - if got := vars[mf]; got.Kind != "env" || got.Value != sn.Declared.From { |
| - bad = append(bad, fmt.Sprintf("%s (environment %q) has no %s", rec.Host, rec.Environment, mf)) |
| + if v, ok := sim.reported[rec.Host]; ok && !sim.declared(v) { |
| + bad = append(bad, fmt.Sprintf("%s is still served at %s by a box that has not adopted, which does not declare --mail submit", rec.Host, v)) |
| + } |
| + if got := vars[mf]; got.Kind != "env" || !sim.sendable(sn, got.Value) { |
| + bad = append(bad, fmt.Sprintf("%s (environment %q) has no %s the mailer sends (%q)", rec.Host, rec.Environment, mf, got.Value)) |
| } |
| case wasSwitched: |
| for _, k := range []string{host, port, user, pass, from} { |
| @@ -289,13 +468,75 @@ func (sim *channelSim) check(wasSwitched bool) { |
| } |
| } |
| +// provisionerState is the in-memory AWS's state, for a dry pass to put |
| +// back. |
| +type provisionerState struct { |
| + Tenants map[string]bool |
| + ConfigSets map[string]string |
| + Identities map[string]*mail.MemIdentity |
| + Users map[string]*mail.MemUser |
| + TenantResources map[string]map[string]bool |
| +} |
| + |
| +func (sim *channelSim) saveProvisioner() []byte { |
| + sim.t.Helper() |
| + b, err := json.Marshal(provisionerState{sim.prov.Tenants, sim.prov.ConfigSets, sim.prov.Identities, sim.prov.Users, sim.prov.TenantResources}) |
| + if err != nil { |
| + sim.t.Fatal(err) |
| + } |
| + return b |
| +} |
| + |
| +func (sim *channelSim) restoreProvisioner(b []byte) { |
| + sim.t.Helper() |
| + var st provisionerState |
| + if err := json.Unmarshal(b, &st); err != nil { |
| + sim.t.Fatal(err) |
| + } |
| + sim.prov.Tenants, sim.prov.ConfigSets, sim.prov.Identities, sim.prov.Users, sim.prov.TenantResources = |
| + st.Tenants, st.ConfigSets, st.Identities, st.Users, st.TenantResources |
| +} |
| + |
| +// armFault arms, sometimes, one failure for the next door. A store fault |
| +// is drawn from the whole range of the door's store operations, reads and |
| +// writes, counted in a dry pass of the same door against an overlay (the |
| +// in-memory AWS is put back after it); otherwise one AWS call fails. |
| +func (sim *channelSim) armFault(door func() string) string { |
| + switch sim.rng.Intn(10) { |
| + case 0, 1, 2, 3: |
| + saved := sim.saveProvisioner() |
| + sim.faults.beginDry() |
| + sim.dry = true |
| + door() |
| + sim.dry = false |
| + ops := sim.faults.endDry() |
| + sim.restoreProvisioner(saved) |
| + if ops == 0 { |
| + return "" |
| + } |
| + n := 1 + sim.rng.Intn(ops) |
| + sim.faults.armOps(n) |
| + return fmt.Sprintf(" [store op #%d of %d fails]", n, ops) |
| + case 4, 5: |
| + m := simProvisionerFaults[sim.rng.Intn(len(simProvisionerFaults))] |
| + sim.prov.FailNext = map[string]error{m: errors.New("simulated AWS failure")} |
| + return " [" + m + " fails]" |
| + } |
| + return "" |
| +} |
| + |
| +func (sim *channelSim) disarm() { |
| + sim.faults.arm(0) |
| + sim.prov.FailNext = nil |
| +} |
| + |
| // do runs one door, maybe with a fault armed, and checks the invariant. |
| func (sim *channelSim) do(name string, fault bool, door func() string) { |
| sim.t.Helper() |
| was := sim.switched() |
| note := "" |
| if fault { |
| - note = sim.armFault() |
| + note = sim.armFault(door) |
| } |
| out := door() |
| sim.disarm() |
| @@ -342,7 +583,7 @@ func (sim *channelSim) create(channel, env string) string { |
| sim.nextID++ |
| host := fmt.Sprintf("sim%d.go.tito.io", sim.nextID) |
| st, out := sim.cli(http.MethodPost, "/instances", fmt.Sprintf(`{"host":%q,"region":"ie","channel":%q,"environment":%q,"scope":%q}`, host, channel, env, scopeOf(env))) |
| - if st/100 == 2 { |
| + if st/100 == 2 && !sim.dry { |
| sim.hosts = append(sim.hosts, host) |
| } |
| return short(st, out) |
| @@ -361,57 +602,112 @@ func scopeOf(env string) string { |
| return "alta" |
| } |
| -// fork creates an owned environment, and checks the door's word: a 2xx |
| -// for a switched app means its From is there. |
| +// madeEnvironment books env when a door made it owned, and checks the |
| +// door's word: a 2xx for a switched app means a From the mailer sends is |
| +// there (P2-4). |
| +func (sim *channelSim) madeEnvironment(door string, env string, st int) { |
| + if sim.dry { |
| + return |
| + } |
| + ctx := context.Background() |
| + m, _, found, err := appconfig.GetEnvironment(ctx, sim.w.fx.rel, "bab", "titogo", env) |
| + if err != nil || !found || !m.Owned() { |
| + return |
| + } |
| + sim.envs = append(sim.envs, env) |
| + if st/100 != 2 || !sim.switched() { |
| + return |
| + } |
| + sn, _, _ := mail.GetSender(ctx, sim.w.fx.rel, "bab", "titogo", mail.SenderAppID) |
| + mf, _ := mail.MailFromName(sn.Declared.EnvPrefix) |
| + if got := m.Vars[mf]; !sim.sendable(sn, got.Value) { |
| + sim.t.Fatalf("the %s door answered %d for %s, which has no %s the mailer sends\nsteps:\n %s", door, st, env, mf, strings.Join(sim.steps, "\n ")) |
| + } |
| +} |
| + |
| +// fork creates an owned environment from team. |
| func (sim *channelSim) fork() string { |
| sim.nextID++ |
| env := fmt.Sprintf("e%d", sim.nextID) |
| st, out := sim.cli(http.MethodPost, "/environments/fork", fmt.Sprintf(`{"from":"team","to":%q,"scope":"alta"}`, env)) |
| - ctx := context.Background() |
| - if m, _, found, err := appconfig.GetEnvironment(ctx, sim.w.fx.rel, "bab", "titogo", env); err == nil && found && m.Owned() { |
| - sim.envs = append(sim.envs, env) |
| - if st/100 == 2 && sim.switched() { |
| - sn, _, _ := mail.GetSender(ctx, sim.w.fx.rel, "bab", "titogo", mail.SenderAppID) |
| - mf, _ := mail.MailFromName(sn.Declared.EnvPrefix) |
| - if got := m.Vars[mf]; got.Value != sn.Declared.From { |
| - sim.t.Fatalf("the fork door answered %d for %s, which has no %s\nsteps:\n %s", st, env, mf, strings.Join(sim.steps, "\n ")) |
| - } |
| - } |
| - } |
| + sim.madeEnvironment("fork", env, st) |
| return short(st, out) |
| } |
| -// adopt makes a new unowned environment (straight into the store, as an |
| -// earlier config write would have) and adopts it into scope alta through |
| -// the door, which mints its credentials: for a switched app, its From. A |
| -// 2xx for a switched app means the From is there (P2-4). |
| +// adopt makes a new unowned environment (through the store the doors use, |
| +// as an earlier config write would have) and adopts it into scope alta |
| +// through the door, which mints its credentials: for a switched app, its |
| +// From. |
| func (sim *channelSim) adopt() string { |
| sim.nextID++ |
| env := fmt.Sprintf("u%d", sim.nextID) |
| - ctx := context.Background() |
| - if _, err := appconfig.ApplyEnvironment(ctx, sim.w.fx.rel, "bab", "titogo", env, |
| + if _, err := appconfig.ApplyEnvironment(context.Background(), sim.w.fx.srv.cfg.Releases, "bab", "titogo", env, |
| map[string]appconfig.Var{"PLAIN": {Kind: "env", Value: "1"}}, nil); err != nil { |
| - sim.t.Fatal(err) |
| + return "setup: " + err.Error() |
| } |
| st, out := sim.cli(http.MethodPost, "/environments/"+env+"/adopt", `{"scope":"alta"}`) |
| - if m, _, found, err := appconfig.GetEnvironment(ctx, sim.w.fx.rel, "bab", "titogo", env); err == nil && found && m.Owned() { |
| - sim.envs = append(sim.envs, env) |
| - if st/100 == 2 && sim.switched() { |
| - sn, _, _ := mail.GetSender(ctx, sim.w.fx.rel, "bab", "titogo", mail.SenderAppID) |
| - mf, _ := mail.MailFromName(sn.Declared.EnvPrefix) |
| - if got := m.Vars[mf]; got.Value != sn.Declared.From { |
| - sim.t.Fatalf("the adopt door answered %d for %s, which has no %s\nsteps:\n %s", st, env, mf, strings.Join(sim.steps, "\n ")) |
| + sim.madeEnvironment("adopt", env, st) |
| + return short(st, out) |
| +} |
| + |
| +// teamCreate is a team credential's config write that brings a new owned |
| +// environment into being (the team config door). |
| +func (sim *channelSim) teamCreate() string { |
| + sim.nextID++ |
| + env := fmt.Sprintf("c%d", sim.nextID) |
| + st, _, out := rawReq(sim.t, http.MethodPut, sim.w.fx.ts.URL+"/api/cli/apps/bab/titogo/config", sim.team, |
| + fmt.Sprintf(`{"environment":%q,"set":{"TEAM_ONLY":{"kind":"env","value":"1"}}}`, env)) |
| + sim.madeEnvironment("team config", env, st) |
| + return short(st, out) |
| +} |
| + |
| +// release gives an environment back (the release door), which reaps what |
| +// was minted for it. |
| +func (sim *channelSim) release(env string) string { |
| + st, out := sim.cli(http.MethodPost, "/environments/"+env+"/release", `{}`) |
| + if st/100 == 2 && !sim.dry { |
| + sim.envs = slices.DeleteFunc(sim.envs, func(e string) bool { return e == env }) |
| + } |
| + return short(st, out) |
| +} |
| + |
| +func (sim *channelSim) enable() string { |
| + return short(sim.cli(http.MethodPost, "/email/enable", `{}`)) |
| +} |
| + |
| +// redeclare re-declares the From, and checks the door's word: a 2xx for a |
| +// switched app means every bundle sends as the new From. |
| +func (sim *channelSim) redeclare(from string) string { |
| + st, out := sim.cli(http.MethodPost, "/email", fmt.Sprintf(`{"env_prefix":"TITO_SMTP","from":%q}`, from)) |
| + if st/100 == 2 && !sim.dry && sim.switched() { |
| + for _, env := range append([]string{""}, sim.envs...) { |
| + if got := sim.bundleVars(env)["TITO_MAIL_FROM"].Value; got != from { |
| + sim.t.Fatalf("the declare door answered %d for %s, and environment %q still sends as %q\nsteps:\n %s", st, from, env, got, strings.Join(sim.steps, "\n ")) |
| } |
| } |
| } |
| return short(st, out) |
| } |
| -// raceSwitchOn is the switch-on door with a promote of an undeclared |
| -// build started between its preconditions and its switch (P2-1). The |
| -// promote is given a moment to land; with the app lock held it cannot, |
| -// and it runs, and is judged, once the switch is in. |
| -func (sim *channelSim) raceSwitchOn(channel string) string { |
| +// reap is the hourly sweep's §7.4 reap, a week on, with a mailer send on |
| +// the record. |
| +func (sim *channelSim) reap() string { |
| + ctx := context.Background() |
| + now := time.Now().UTC() |
| + if !sim.dry { |
| + _ = sim.w.fx.st.RecordMailCallerSend(ctx, "bab", "titogo", now.Format("2006-01-02"), mail.CallerClassMailer) |
| + } |
| + if err := sim.w.fx.srv.reapSubmittedAppUsers(ctx, sim.w.fx.account(sim.t), now.AddDate(0, 0, 8)); err != nil { |
| + return "error: " + err.Error() |
| + } |
| + return "ok" |
| +} |
| + |
| +// raceSwitchOn is the switch-on door with another door started between |
| +// its preconditions and its switch (P2-1 and its kin). The other door is |
| +// given a moment to land; with the app lock held it cannot, and it runs, |
| +// and is judged, once the switch is in. |
| +func (sim *channelSim) raceSwitchOn(name string, other func() string) string { |
| var wg sync.WaitGroup |
| var raced string |
| sim.w.fx.srv.submissionSwitchHook = func(on bool, stage string) { |
| @@ -423,9 +719,7 @@ func (sim *channelSim) raceSwitchOn(channel string) string { |
| go func() { |
| defer wg.Done() |
| defer close(done) |
| - st, _, out := rawReq(sim.t, http.MethodPost, sim.w.fx.ts.URL+"/api/cli/apps/bab/titogo/promote", sim.w.owner, |
| - fmt.Sprintf(`{"channel":%q,"version":"v1","hotfix":true}`, channel)) |
| - raced = short(st, out) |
| + raced = other() |
| }() |
| select { |
| case <-done: |
| @@ -435,38 +729,131 @@ func (sim *channelSim) raceSwitchOn(channel string) string { |
| defer func() { sim.w.fx.srv.submissionSwitchHook = nil }() |
| st, out := sim.w.submit(sim.t, true) |
| wg.Wait() |
| - return short(st, out) + " | raced promote: " + raced |
| + return short(st, out) + " | raced " + name + ": " + raced |
| +} |
| + |
| +// createAroundSwitchOn is the other way round (Fable's probe of |
| +// 2026-11-14): a create on canary (v1) that has read its channel is held |
| +// there, before any lock, while a whole switch-on runs, then let go. The |
| +// record write judges under the app lock, now switched, and refuses; a door |
| +// that judged only where it read the channel would write an instance on an |
| +// undeclared build of a switched app. |
| +func (sim *channelSim) createAroundSwitchOn() string { |
| + sim.nextID++ |
| + host := fmt.Sprintf("sim%d.go.tito.io", sim.nextID) |
| + var switched string |
| + hook := func(stage, h string) { |
| + if stage != instanceCreateAfterChannelCheck || h != host { |
| + return |
| + } |
| + done := make(chan struct{}) |
| + go func() { |
| + defer close(done) |
| + st, out := sim.w.submit(sim.t, true) |
| + switched = short(st, out) |
| + }() |
| + select { |
| + case <-done: |
| + case <-time.After(1500 * time.Millisecond): |
| + switched = "still waiting" |
| + } |
| + } |
| + instanceCreateHook.Store(&hook) |
| + defer instanceCreateHook.Store(nil) |
| + st, out := sim.cli(http.MethodPost, "/instances", fmt.Sprintf(`{"host":%q,"region":"ie","channel":"canary"}`, host)) |
| + if st/100 == 2 && !sim.dry { |
| + sim.hosts = append(sim.hosts, host) |
| + } |
| + // A switch-on still waiting on the app lock finishes once the create |
| + // lets it go. |
| + for i := 0; i < 100 && switched == "still waiting"; i++ { |
| + time.Sleep(20 * time.Millisecond) |
| + } |
| + return short(st, out) + " | switch-on in between: " + switched |
| +} |
| + |
| +// races are the doors raced into a switch-on: each, landing between the |
| +// checks and the switch, would put an instance of the app where it has no |
| +// working channel. |
| +func (sim *channelSim) races() map[string]func() string { |
| + noFrom := "" |
| + for _, env := range sim.envs { |
| + if m, _, found, err := appconfig.GetEnvironment(context.Background(), sim.w.fx.rel, "bab", "titogo", env); err == nil && found && m.Owned() { |
| + if _, ok := m.Vars["TITO_MAIL_FROM"]; !ok { |
| + noFrom = env |
| + } |
| + } |
| + } |
| + return map[string]func() string{ |
| + "a promote of v1 to beta": func() string { return sim.promote("beta", "v1") }, |
| + "a create on canary (v1)": func() string { return sim.create("canary", "") }, |
| + "a pin to v1": func() string { return sim.pin(submissionHost, "v1") }, |
| + "a move to canary (v1)": func() string { return sim.move(submissionHost, "canary") }, |
| + "a rebind into " + noFrom: func() string { |
| + if noFrom == "" { |
| + return "no environment without a From" |
| + } |
| + return sim.rebind(submissionHost, noFrom) |
| + }, |
| + } |
| +} |
| + |
| +// ready puts the app off, with the instance on beta, unpinned and adopted |
| +// by an armed box: a switch-on's preconditions then pass. |
| +func (sim *channelSim) ready() { |
| + if sim.switched() { |
| + sim.do("switch off", false, sim.switchOff) |
| + } |
| + sim.do("unpin", false, func() string { return sim.pin(submissionHost, "") }) |
| + sim.do("move the instance to beta", false, func() string { return sim.move(submissionHost, "beta") }) |
| + sim.do("box tick", false, func() string { sim.boxTick(true, false); return "" }) |
| } |
| -// The scripted interleavings: each reaches one of P2-1 to P2-4. |
| +// The scripted interleavings: each reaches one of P2-1 to P2-4, or one of |
| +// the races the one judgement closes. |
| func (sim *channelSim) scripted() { |
| sim.t.Helper() |
| // P2-2: a pin to an undeclared build no box has adopted yet. |
| sim.do("pin v1 (no box adopts it)", false, func() string { return sim.pin(submissionHost, "v1") }) |
| sim.do("switch on", false, sim.switchOn) |
| sim.do("unpin", false, func() string { return sim.pin(submissionHost, "") }) |
| - sim.boxTick(true) |
| - // P2-1: a promote of an undeclared build between the checks and the |
| - // switch, onto the channel the instance follows (edge is entered by a |
| - // merge only, so beta). |
| - sim.do("move the instance to beta", false, func() string { return sim.move(submissionHost, "beta") }) |
| - sim.boxTick(true) |
| - sim.do("switch on, racing a promote of v1 to beta", false, func() string { return sim.raceSwitchOn("beta") }) |
| + sim.boxTick(true, false) |
| + // P2-4: an environment made while switched, its From's write failing; |
| + // then an instance created into it, and one rebound into it. |
| if !sim.switched() { |
| sim.do("switch on", false, sim.switchOn) |
| } |
| - // P2-4: an environment created while switched, its From's write |
| - // failing; then an instance created into it. |
| - // An adopted environment's second write is its From (the first marks |
| - // it owned); then a fork's first write. |
| - sim.faults.armMatching(fmt.Sprintf("environments/u%d.json", sim.nextID+1), 2) |
| + // The adopted environment's third write is its From: the first makes |
| + // it (the setup), the second marks it owned. |
| + sim.faults.armMatching(fmt.Sprintf("environments/u%d.json", sim.nextID+1), 3) |
| sim.do("adopt, its From's write failing", false, sim.adopt) |
| - sim.faults.arm(1) |
| - sim.do("fork, write #1 under the app failing", false, sim.fork) |
| + sim.faults.armMatching(fmt.Sprintf("environments/c%d.json", sim.nextID+1), 2) |
| + sim.do("team config creates an environment, its From's write failing", false, sim.teamCreate) |
| for _, env := range sim.envs { |
| sim.do("create an instance on edge in "+env, false, func() string { return sim.create("edge", env) }) |
| + sim.do("rebind the instance into "+env, false, func() string { return sim.rebind(submissionHost, env) }) |
| + } |
| + sim.do("rebind the instance to the default bundle", false, func() string { return sim.rebind(submissionHost, "") }) |
| + sim.boxTick(true, false) |
| + // P2-1 and its kin: each door raced into a switch-on, and a switch-on |
| + // run inside a create. |
| + for _, name := range slices.Sorted(maps.Keys(sim.races())) { |
| + sim.ready() |
| + race := sim.races()[name] |
| + sim.do("switch on, racing "+name, false, func() string { return sim.raceSwitchOn(name, race) }) |
| + } |
| + sim.ready() |
| + sim.do("a create on canary (v1) with a switch-on after its channel read", false, sim.createAroundSwitchOn) |
| + if !sim.switched() { |
| + sim.ready() |
| + sim.do("switch on", false, sim.switchOn) |
| } |
| - sim.boxTick(true) |
| + // Re-declare and enable while switched: a From the mailer sends, then |
| + // one it does not. |
| + sim.do("re-declare hello@", false, func() string { return sim.redeclare("hello@titogo.bab.oncarlos.com") }) |
| + sim.do("re-declare elsewhere", false, func() string { return sim.redeclare("x@elsewhere.example") }) |
| + sim.do("enable", false, sim.enable) |
| + sim.do("reap the app user", false, sim.reap) |
| // P2-3: a switch-off whose SMTP delivery fails part-way. |
| for _, m := range []string{"MintKey", "EnsureUser"} { |
| sim.prov.FailNext = map[string]error{m: errors.New("simulated AWS failure")} |
| @@ -480,24 +867,32 @@ func (sim *channelSim) scripted() { |
| sim.do(fmt.Sprintf("switch off, store write #%d failing", n), false, sim.switchOff) |
| } |
| sim.do("switch off", false, sim.switchOff) |
| - // Switch-on's own order: with an instance in team, the From's write to |
| - // team failing, then the write after the reap (which a reap that took |
| - // the From too would need). |
| + // Switch-on's own order: with an instance in team, team's first write |
| + // (its From), second (the reap of its user) and third failing. Each |
| + // starts from a clean switch-off, which takes every From out again. |
| sim.do("create an instance on edge in team", false, func() string { return sim.create("edge", "team") }) |
| - sim.boxTick(true) |
| - sim.faults.armMatching("environments/team.json", 1) |
| - sim.do("switch on, team's first write failing", false, sim.switchOn) |
| - sim.faults.armMatching("environments/team.json", 3) |
| - sim.do("switch on, team's third write failing", false, sim.switchOn) |
| + sim.do("create an instance on edge in the default bundle", false, func() string { return sim.create("edge", "") }) |
| + for n := 1; n <= 3; n++ { |
| + sim.do("switch off", false, sim.switchOff) |
| + sim.ready() |
| + sim.faults.armMatching("environments/team.json", n) |
| + sim.do(fmt.Sprintf("switch on, team's write #%d failing", n), false, sim.switchOn) |
| + } |
| sim.do("switch on", false, sim.switchOn) |
| + for _, env := range slices.Clone(sim.envs) { |
| + if env != "team" { |
| + sim.do("release "+env, false, func() string { return sim.release(env) }) |
| + } |
| + } |
| } |
| // random runs n random steps. |
| func (sim *channelSim) random(n int) { |
| sim.t.Helper() |
| - versions, channels := []string{"v1", "v2"}, []string{"edge", "beta"} |
| + versions, channels := []string{"v1", "v2"}, []string{"edge", "beta", "canary"} |
| + froms := []string{"noreply@titogo.bab.oncarlos.com", "hello@titogo.bab.oncarlos.com", "x@elsewhere.example"} |
| for i := 0; i < n; i++ { |
| - switch sim.rng.Intn(14) { |
| + switch sim.rng.Intn(20) { |
| case 0, 1: |
| sim.do("switch on", true, sim.switchOn) |
| case 2: |
| @@ -524,13 +919,33 @@ func (sim *channelSim) random(n int) { |
| sim.do("rebind "+h+" to "+env, true, func() string { return sim.rebind(h, env) }) |
| case 10: |
| armed := sim.rng.Intn(3) > 0 |
| - sim.do(fmt.Sprintf("box tick, armed %v", armed), false, func() string { sim.boxTick(armed); return "" }) |
| + sim.do(fmt.Sprintf("box tick, armed %v", armed), false, func() string { sim.boxTick(armed, false); return "" }) |
| case 11: |
| - sim.do("switch on, racing a promote of v1 to beta", false, func() string { return sim.raceSwitchOn("beta") }) |
| + races := sim.races() |
| + name := sim.pick(slices.Sorted(maps.Keys(races))) |
| + sim.do("switch on, racing "+name, false, func() string { return sim.raceSwitchOn(name, races[name]) }) |
| case 12: |
| - sim.do("box tick, armed", false, func() string { sim.boxTick(true); return "" }) |
| + sim.do("box tick, lagging", false, func() string { sim.boxTick(true, true); return "" }) |
| case 13: |
| sim.do("adopt", true, sim.adopt) |
| + case 14: |
| + sim.do("team config creates an environment", true, sim.teamCreate) |
| + case 15: |
| + env := sim.pick(sim.envs) |
| + sim.do("release "+env, true, func() string { return sim.release(env) }) |
| + case 16: |
| + sim.do("enable", true, sim.enable) |
| + case 17: |
| + f := sim.pick(froms) |
| + sim.do("re-declare "+f, true, func() string { return sim.redeclare(f) }) |
| + case 18: |
| + sim.do("the hourly reap", true, sim.reap) |
| + case 19: |
| + if sim.rng.Intn(2) == 0 { |
| + sim.do("box tick, armed", false, func() string { sim.boxTick(true, false); return "" }) |
| + } else { |
| + sim.do("a create on canary (v1) with a switch-on after its channel read", false, sim.createAroundSwitchOn) |
| + } |
| } |
| } |
| } |
| @@ -542,7 +957,7 @@ func TestSubmissionChannelSimulation(t *testing.T) { |
| if seed == 1 { |
| sim.scripted() |
| } |
| - sim.random(60) |
| + sim.random(70) |
| t.Logf("%d steps; switched at the end: %v", len(sim.steps), sim.switched()) |
| if testing.Verbose() { |
| t.Logf("steps:\n %s", strings.Join(sim.steps, "\n ")) |
diff --git a/internal/console/submissioncopy.go b/internal/console/submissioncopy.go| index 62c21d53d..dc669f904 100644 |
| --- a/internal/console/submissioncopy.go |
| +++ b/internal/console/submissioncopy.go |
| @@ -11,6 +11,7 @@ var submissionCopy = struct { |
| FromNotSendable, ConfigSetUnbuildable string |
| RouteUnreported, RouteUndeclared, RoutesUnreadable string |
| RoutePinUndeclared, EnvironmentNoFrom, EnvironmentFromFailed string |
| + DeclaredFromUndelivered string |
| ChannelUndeclared, ChannelUnreadable string |
| TenantUnassociated, TenantUnconfirmed string |
| BoxUnarmed, BoxesUnreadable string |
| @@ -30,9 +31,10 @@ var submissionCopy = struct { |
| RouteUndeclared: "Instance %s runs build %s, which doesn't declare --mail submit. Ship with --mail submit and promote it first.", |
| RoutesUnreadable: "Can't read this app's instances, so submission stays off. Try again.", |
| - RoutePinUndeclared: "Instance %s is pinned to build %s, which doesn't declare --mail submit. Pin a build that does, or unpin it, first.", |
| - EnvironmentNoFrom: "Email submission is on for %s, and environment %s has no From address for it yet, so an instance there couldn't send. Run carlos email submission on --app %s again to deliver it.", |
| - EnvironmentFromFailed: "Environment %s was written, but email submission is on for %s and its From address couldn't be delivered, so no instance can use it yet. Run carlos email submission on --app %s again to deliver it.", |
| + RoutePinUndeclared: "Instance %s is pinned to build %s, which doesn't declare --mail submit. Pin a build that does, or unpin it, first.", |
| + EnvironmentNoFrom: "Email submission is on for %s, and environment %s has no From address for it yet, so an instance there couldn't send. Run carlos email submission on --app %s again to deliver it.", |
| + DeclaredFromUndelivered: "Declared, but email submission is on for %s and the new From couldn't reach every environment yet. Run carlos email submission on again to deliver it.", |
| + EnvironmentFromFailed: "Environment %s was written, but email submission is on for %s and its From address couldn't be delivered, so no instance can use it yet. Run carlos email submission on --app %s again to deliver it.", |
| ChannelUndeclared: "Channel %s points at build %s, which doesn't declare --mail submit. Ship with --mail submit and promote it first.", |
| ChannelUnreadable: "Can't confirm channel %s: its pointer or build couldn't be read. Try again.", |
diff --git a/internal/console/submissiongate.go b/internal/console/submissiongate.go| index 53bcef606..01ad6f420 100644 |
| --- a/internal/console/submissiongate.go |
| +++ b/internal/console/submissiongate.go |
| @@ -30,8 +30,9 @@ import ( |
| // submissionServeDoors is every console route that changes which build a |
| // route serves: it writes a channel pointer, an instance's channel, or an |
| // update pin, mode, major hold, install request or app update policy, or |
| -// creates an instance on a channel. Each calls one of the gates below before |
| -// it writes, with the version the route would serve afterwards. |
| +// creates or rebinds an instance. Each calls judgeServing (the one |
| +// judgement, ruled by Paul, 2026-11-14) under the app lock, immediately |
| +// before it writes, with what the route would serve afterwards. |
| // TestSubmissionGateCoversEveryServeDoor drives each one, and fails when a |
| // route that reaches a serve writer is in neither this list nor |
| // submissionUngatedServeDoors. |
| @@ -72,8 +73,11 @@ var submissionServeDoors = []string{ |
| // its head. |
| "PUT /api/cli/apps/{account}/{app}/instances-manifest", |
| // A new instance (and a seed or import, which create through it): its |
| - // channel's head. |
| + // channel's head, and the environment it binds. |
| "POST /api/cli/apps/{account}/{app}/instances", |
| + // A rebind: the environment an instance is moved into (ruled by Paul, |
| + // 2026-11-14). |
| + "PATCH /api/cli/apps/{account}/{app}/instances/{host}", |
| } |
| // submissionUngatedServeDoors are routes that reach a serve writer and are |
| @@ -137,25 +141,116 @@ func (s *Server) submissionSwitched(ctx context.Context, acct, app string) (bool |
| return v.Submission != nil && v.Submission.On, nil |
| } |
| -// submissionBuildRefusal is nil when acct/app's email submission is off, or |
| -// when version's manifest declares --mail submit (or version is "": nothing |
| -// would be served). Otherwise it is the 409 that names the remedy. A read |
| -// error of the sender or the manifest refuses with a 502 rather than let an |
| -// unconfirmed build through. |
| -func (s *Server) submissionBuildRefusal(ctx context.Context, acct, app, version string) *doorRefusal { |
| - if version == "" { |
| - return nil |
| +// servingChange is what a serve, create or rebind door is about to write, |
| +// as judgeServing reads it: any of the fields, each judged as below. |
| +type servingChange struct { |
| + // version is a build a channel pointer is about to name (a promote, a |
| + // canary, a rollback's or fast-track's selected version). |
| + version string |
| + // channel is a channel a route is about to follow, or adopt the head |
| + // of (an instance install, the instances manifest's channel). |
| + channel *string |
| + // record is a record as it is about to be written (a create, a channel |
| + // move): the build it serves, its pin else its channel's head, and the |
| + // environment it binds. Only an instance (Kind instance) runs a process. |
| + record *provision.Record |
| + // updates is an update-settings change from updates[0] to updates[1], |
| + // judged only when it can make the route adopt a build (a new or |
| + // cleared pin, a release from manual, a different major). |
| + updates *[2]provision.Record |
| + // policy is an app update policy change and the instances manifest's |
| + // channel change. |
| + policy *servingPolicy |
| + // env is an environment an existing instance is about to be bound to (a |
| + // rebind). |
| + env *string |
| +} |
| + |
| +// servingPolicy is an app-wide policy change: the update policy from before |
| +// to next, and the instances manifest's channel from channel to nextChannel. |
| +type servingPolicy struct { |
| + before, next provision.UpdatePolicy |
| + channel, nextChannel string |
| +} |
| + |
| +// judgeServing is the one judgement every serve, create and rebind door |
| +// makes (ruled by Paul, 2026-11-14, the one-working-channel family: one |
| +// invariant, enforced in one place), under the app lock, immediately before |
| +// its write. While acct/app's email submission is on, every instance must |
| +// keep a working mail channel: the build it would serve declares |
| +// --mail submit, and an owned environment it binds holds the app's From. |
| +// The app lock is the one the switch door holds (beginCopiesMutation), so |
| +// no switch-on can land between this judgement and the write; a caller that |
| +// does not hold it is refused (a programming error, logged), never judged. |
| +// |
| +// It answers nil when the switch is off, or when every part of c passes; |
| +// otherwise the 409 that names the remedy, or a 502 when a read it needs |
| +// fails: an unconfirmed build is never let through. |
| +func (s *Server) judgeServing(ctx context.Context, acct, app string, c servingChange) *doorRefusal { |
| + if !s.appLocks.held(acct + "/" + app) { |
| + log.Printf("console: submission gate %s/%s: judged without the app lock", acct, app) |
| + return &doorRefusal{Status: http.StatusInternalServerError, Msg: "This change isn't serialised with the email submission switch, so nothing changed. Try again."} |
| + } |
| + if s.servingJudged != nil { |
| + s.servingJudged(acct, app) |
| } |
| switched, ref := s.submissionSwitched(ctx, acct, app) |
| if ref != nil || !switched { |
| return ref |
| } |
| - return s.submissionDeclaredRefusal(ctx, acct, app, version) |
| + if c.version != "" { |
| + if ref := s.submissionDeclaredRefusal(ctx, acct, app, c.version); ref != nil { |
| + return ref |
| + } |
| + } |
| + if c.channel != nil { |
| + if ref := s.submissionHeadRefusal(ctx, acct, app, *c.channel); ref != nil { |
| + return ref |
| + } |
| + } |
| + if c.record != nil { |
| + if ref := s.servingRecord(ctx, acct, app, *c.record); ref != nil { |
| + return ref |
| + } |
| + } |
| + if u := c.updates; u != nil { |
| + rec, next := u[0], u[1] |
| + releases := next.Pin != rec.Pin || |
| + (rec.Updates == release.UpdatesManual && next.Updates != release.UpdatesManual) || |
| + !sameMajor(rec.Major, next.Major) |
| + if releases { |
| + if ref := s.servingRecord(ctx, acct, app, next); ref != nil { |
| + return ref |
| + } |
| + } |
| + } |
| + if p := c.policy; p != nil { |
| + if p.nextChannel != p.channel { |
| + if ref := s.submissionHeadRefusal(ctx, acct, app, p.nextChannel); ref != nil { |
| + return ref |
| + } |
| + } |
| + if (p.before.DefaultUpdates == release.UpdatesManual && p.next.DefaultUpdates != release.UpdatesManual) || |
| + !sameMajor(p.before.DefaultMajor, p.next.DefaultMajor) { |
| + if ref := s.servingRoutes(ctx, acct, app); ref != nil { |
| + return ref |
| + } |
| + } |
| + } |
| + if c.env != nil { |
| + if ref := s.servingEnvironment(ctx, acct, app, *c.env); ref != nil { |
| + return ref |
| + } |
| + } |
| + return nil |
| } |
| -// submissionDeclaredRefusal is the manifest half of submissionBuildRefusal, |
| -// for a caller that already knows the app is switched. |
| +// submissionDeclaredRefusal is judgeServing's manifest read: version's |
| +// manifest must declare --mail submit ("" serves nothing). |
| func (s *Server) submissionDeclaredRefusal(ctx context.Context, acct, app, version string) *doorRefusal { |
| + if version == "" { |
| + return nil |
| + } |
| m, err := release.GetManifest(ctx, s.cfg.Releases, acct, app, version) |
| if err != nil { |
| log.Printf("console: submission gate %s/%s: read manifest %s: %v", acct, app, version, err) |
| @@ -167,31 +262,24 @@ func (s *Server) submissionDeclaredRefusal(ctx context.Context, acct, app, versi |
| return &doorRefusal{Status: http.StatusConflict, Msg: fmt.Sprintf(submissionCopy.BuildUndeclared, app, app)} |
| } |
| -// submissionSelectionGuard is submissionBuildRefusal as a checkTarget for a |
| -// pointer write that selects its target under its own CAS (a rollback's |
| -// History[0], a fast-track's head): it judges the very version the write |
| -// will sign. Its refusal is a *statelessSelectionError, which those doors |
| -// already answer with the refusal's status and words. |
| +// submissionSelectionGuard is judgeServing as a checkTarget for a pointer |
| +// write that selects its target under its own CAS (a rollback's History[0], |
| +// a fast-track's head): it judges the very version the write will sign, |
| +// under the app lock the door holds. Its refusal is a |
| +// *statelessSelectionError, which those doors already answer with the |
| +// refusal's status and words. |
| func (s *Server) submissionSelectionGuard(ctx context.Context, acct, app string) func(string) error { |
| return func(version string) error { |
| - if ref := s.submissionBuildRefusal(ctx, acct, app, version); ref != nil { |
| + if ref := s.judgeServing(ctx, acct, app, servingChange{version: version}); ref != nil { |
| return &statelessSelectionError{ref} |
| } |
| return nil |
| } |
| } |
| -// submissionChannelRefusal gates a door that puts a route on channel, or |
| -// makes it adopt channel's head: the version it would serve is the head. A |
| -// channel with no pointer serves nothing, so there is nothing to refuse. |
| -func (s *Server) submissionChannelRefusal(ctx context.Context, acct, app, channel string) *doorRefusal { |
| - switched, ref := s.submissionSwitched(ctx, acct, app) |
| - if ref != nil || !switched { |
| - return ref |
| - } |
| - return s.submissionHeadRefusal(ctx, acct, app, channel) |
| -} |
| - |
| +// submissionHeadRefusal judges channel's head: the version a route on it |
| +// serves. A channel with no pointer serves nothing, so there is nothing to |
| +// refuse. |
| func (s *Server) submissionHeadRefusal(ctx context.Context, acct, app, channel string) *doorRefusal { |
| if channel == "" { |
| return nil // a channel-less record is skipped by reconcile, never served |
| @@ -207,40 +295,31 @@ func (s *Server) submissionHeadRefusal(ctx context.Context, acct, app, channel s |
| return s.submissionDeclaredRefusal(ctx, acct, app, head.Version) |
| } |
| -// submissionRecordRefusal judges the build rec would serve once a box |
| -// applies it: its pin, else its channel's head. Under a major hold the root |
| -// picks the newest build inside the major, which the console cannot name |
| -// (it never chooses a build); the head is the build that hold releases to, |
| -// and the box's loud log covers an older one. |
| -func (s *Server) submissionRecordRefusal(ctx context.Context, rec provision.Record) *doorRefusal { |
| - if rec.Pin != "" { |
| - return s.submissionBuildRefusal(ctx, rec.Account, rec.App, rec.Pin) |
| - } |
| - return s.submissionChannelRefusal(ctx, rec.Account, rec.App, rec.Channel) |
| -} |
| - |
| -// submissionUpdatesRefusal gates an instance's update settings change from |
| -// rec to next. Only a change that can make the route adopt a build is |
| -// judged: a new or cleared pin, a release from manual, or a different major. |
| -// Freezing (manual on, or nothing changed) is never refused. |
| -func (s *Server) submissionUpdatesRefusal(ctx context.Context, rec, next provision.Record) *doorRefusal { |
| - releases := next.Pin != rec.Pin || |
| - (rec.Updates == release.UpdatesManual && next.Updates != release.UpdatesManual) || |
| - !sameMajor(rec.Major, next.Major) |
| - if !releases { |
| +// servingRecord judges a record as it is about to be written, for a |
| +// switched app: the build it would serve once a box applies it (its pin, |
| +// else its channel's head; under a major hold the root picks the newest |
| +// build inside the major, which the console cannot name, so the head, the |
| +// build that hold releases to, is judged and the box's loud log covers an |
| +// older one), and the environment it binds. A record that runs no process |
| +// (a static or service route) sends no mail and passes. |
| +func (s *Server) servingRecord(ctx context.Context, acct, app string, rec provision.Record) *doorRefusal { |
| + if rec.KindOrDefault() != "instance" { |
| return nil |
| } |
| - return s.submissionRecordRefusal(ctx, next) |
| -} |
| - |
| -// submissionRoutesRefusal judges the head of every channel the app's |
| -// unpinned instances follow: the builds an app-wide policy change that |
| -// releases a hold lets them adopt. Unreadable records refuse. |
| -func (s *Server) submissionRoutesRefusal(ctx context.Context, acct, app string) *doorRefusal { |
| - switched, ref := s.submissionSwitched(ctx, acct, app) |
| - if ref != nil || !switched { |
| + if rec.Pin != "" { |
| + if ref := s.submissionDeclaredRefusal(ctx, acct, app, rec.Pin); ref != nil { |
| + return ref |
| + } |
| + } else if ref := s.submissionHeadRefusal(ctx, acct, app, rec.Channel); ref != nil { |
| return ref |
| } |
| + return s.servingEnvironment(ctx, acct, app, rec.Environment) |
| +} |
| + |
| +// servingRoutes judges the head of every channel the app's unpinned |
| +// instances follow: the builds an app-wide policy change that releases a |
| +// hold lets them adopt. Unreadable records refuse. |
| +func (s *Server) servingRoutes(ctx context.Context, acct, app string) *doorRefusal { |
| recs, unreadable, err := s.listRecordsStrict(ctx, acct, app, submissionRecordMax) |
| if err != nil || len(unreadable) > 0 { |
| if err != nil { |
| @@ -261,42 +340,18 @@ func (s *Server) submissionRoutesRefusal(ctx context.Context, acct, app string) |
| return nil |
| } |
| -// submissionPolicyRefusal gates an app update policy change from before to |
| -// next, and of the instances manifest's channel from channel to nextChannel. |
| -// A new default channel judges its head (it is the channel minted routes |
| -// follow); a default that releases a hold (manual cleared, or a different |
| -// major) judges the heads the app's unpinned instances would adopt. An |
| -// instance with its own setting is judged too, which can only over-refuse. |
| -func (s *Server) submissionPolicyRefusal(ctx context.Context, acct, app string, before, next provision.UpdatePolicy, channel, nextChannel string) *doorRefusal { |
| - if nextChannel != channel { |
| - if ref := s.submissionChannelRefusal(ctx, acct, app, nextChannel); ref != nil { |
| - return ref |
| - } |
| - } |
| - if (before.DefaultUpdates == release.UpdatesManual && next.DefaultUpdates != release.UpdatesManual) || |
| - !sameMajor(before.DefaultMajor, next.DefaultMajor) { |
| - return s.submissionRoutesRefusal(ctx, acct, app) |
| - } |
| - return nil |
| -} |
| - |
| -// submissionEnvironmentRefusal gates a door that puts an instance into |
| -// environment env: creating it there, or rebinding it (ruled by Paul, |
| -// 2026-11-14, P2-4). While acct/app's email submission is on, an owned |
| -// environment's bundle stands alone (it inherits nothing from the default |
| -// bundle), so it must hold the app's From for an instance there to send; |
| -// one created while the From could not be delivered does not, and the |
| -// door refuses with the remedy. The default bundle (env "") and an |
| -// unowned environment, which inherits the default's, get their From from |
| -// the switch itself. A read that fails refuses. |
| -func (s *Server) submissionEnvironmentRefusal(ctx context.Context, acct, app, env string) *doorRefusal { |
| +// servingEnvironment judges an environment an instance of a switched app |
| +// is about to bind (P2-4, ruled 2026-11-14): an owned environment's bundle |
| +// stands alone (it inherits nothing from the default bundle), so it must |
| +// hold the app's From for an instance there to send; one created while the |
| +// From could not be delivered does not, and the door refuses with the |
| +// remedy. The default bundle (env "") and an unowned environment, which |
| +// inherits the default's, get their From from the switch itself. A read |
| +// that fails refuses. |
| +func (s *Server) servingEnvironment(ctx context.Context, acct, app, env string) *doorRefusal { |
| if env == "" { |
| return nil |
| } |
| - switched, ref := s.submissionSwitched(ctx, acct, app) |
| - if ref != nil || !switched { |
| - return ref |
| - } |
| m, _, found, err := appconfig.GetEnvironment(ctx, s.cfg.Releases, acct, app, env) |
| if err != nil { |
| log.Printf("console: submission gate %s/%s: read environment %s: %v", acct, app, env, err) |
| @@ -320,8 +375,8 @@ func (s *Server) submissionEnvironmentRefusal(ctx context.Context, acct, app, en |
| return &doorRefusal{Status: http.StatusConflict, Msg: fmt.Sprintf(submissionCopy.EnvironmentNoFrom, app, env, app)} |
| } |
| -// submissionEnvironmentUnreadable is submissionEnvironmentRefusal's answer |
| -// when it could not read what it judges. |
| +// submissionEnvironmentUnreadable is servingEnvironment's answer when it |
| +// could not read what it judges. |
| func submissionEnvironmentUnreadable() *doorRefusal { |
| return &doorRefusal{Status: http.StatusBadGateway, Msg: "Couldn't confirm this environment can send email while submission is on, so nothing changed. Try again."} |
| } |
diff --git a/internal/console/submissiongate_test.go b/internal/console/submissiongate_test.go| index ac95197b5..ea9c39f82 100644 |
| --- a/internal/console/submissiongate_test.go |
| +++ b/internal/console/submissiongate_test.go |
| @@ -19,10 +19,12 @@ import ( |
| "golang.org/x/tools/go/packages" |
| + "github.com/carlosframework/platform/internal/appconfig" |
| "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/status" |
| ) |
| // submissionServeWriters is every write that changes which build a route |
| @@ -51,6 +53,9 @@ var submissionServeWriters = []string{ |
| "provision.Record.Updates=", |
| "provision.Record.Major=", |
| "provision.Record.InstallRequest=", |
| + // The environment an instance binds, whose bundle must hold a switched |
| + // app's From (ruled 2026-11-14). |
| + "provision.Record.Environment=", |
| // The app's update policy and the channel its instances are created on. |
| "provision.Manifest.Channel=", |
| "provision.Manifest.Updates=", |
| @@ -291,16 +296,13 @@ func funcName(fn *types.Func) string { |
| return fn.Pkg().Name() + "." + fn.Name() |
| } |
| -// submissionGates are the gate functions a serve door calls; the guard |
| +// submissionGates is the gate function a serve door calls; the guard |
| // reports them beside the writers so a listed door that reaches no gate at |
| // all fails statically too, not only when driven. |
| var submissionGates = []string{ |
| - "console.Server.submissionBuildRefusal", |
| - "console.Server.submissionSelectionGuard", |
| - "console.Server.submissionChannelRefusal", |
| - "console.Server.submissionRecordRefusal", |
| - "console.Server.submissionUpdatesRefusal", |
| - "console.Server.submissionPolicyRefusal", |
| + // The one judgement (ruled by Paul, 2026-11-14): every serve, create |
| + // and rebind door reaches it. |
| + "console.Server.judgeServing", |
| } |
| // TestSubmissionGateCoversEveryServeDoor is test 8.12's door half (spec |
| @@ -373,8 +375,12 @@ func TestSubmissionGateCoversEveryServeDoor(t *testing.T) { |
| } |
| before := w.snapshot(t) |
| out := door.drive(t, w) |
| - if !strings.Contains(out, "Switch submission off first") { |
| - t.Fatalf("%s against an undeclared build: %s, want the build refusal (switch submission off first)", door.pattern, out) |
| + want := door.want |
| + if want == "" { |
| + want = "Switch submission off first" |
| + } |
| + if !strings.Contains(out, want) { |
| + t.Fatalf("%s against an undeclared build: %s, want the refusal %q", door.pattern, out, want) |
| } |
| if after := w.snapshot(t); after != before { |
| t.Fatalf("%s refused but changed what is served:\nbefore %s\nafter %s", door.pattern, before, after) |
| @@ -551,7 +557,10 @@ func (w *submissionGateWorld) snapshot(t *testing.T) string { |
| type submissionGateDoor struct { |
| pattern string |
| - setup func(t *testing.T, w *submissionGateWorld) |
| + // want is the refusal the drive must see, "Switch submission off first" |
| + // (the build refusal) when empty. |
| + want string |
| + setup func(t *testing.T, w *submissionGateWorld) |
| // drive calls the door with an undeclared target and answers what it |
| // said: the CLI's status and body, or the browser's landing page. |
| drive func(t *testing.T, w *submissionGateWorld) string |
| @@ -659,4 +668,99 @@ var submissionGateDoors = []submissionGateDoor{ |
| drive: cliDrive(http.MethodPut, "/instances-manifest", `{"channel":"canary/bad"}`)}, |
| {pattern: "POST /api/cli/apps/{account}/{app}/instances", |
| drive: cliDrive(http.MethodPost, "/instances", `{"host":"new.example.com","channel":"canary/bad"}`)}, |
| + // A rebind into an owned environment without the switched app's From |
| + // (ruled 2026-11-14). |
| + {pattern: "PATCH /api/cli/apps/{account}/{app}/instances/{host}", |
| + want: "has no From address", |
| + setup: func(t *testing.T, w *submissionGateWorld) { |
| + if _, err := appconfig.ApplyEnvironmentOwned(context.Background(), w.rel, release.OpsAccount, "km", "teamx", "alta", |
| + map[string]appconfig.Var{"X": {Kind: "env", Value: "1"}}, nil); err != nil { |
| + t.Fatal(err) |
| + } |
| + // The team floor: every box on a release that binds owned |
| + // environments. |
| + seedSettingsBox(t, w.consoleFixture, "ie-1", time.Now(), |
| + &status.BoxMetrics{UpdateSettings: status.UpdateSettingsProtocol, Release: "v0.40.0"}) |
| + }, |
| + drive: cliDrive(http.MethodPatch, "/instances/a.example.com", `{"environment":"teamx","scope":"alta"}`)}, |
| +} |
| + |
| +// servingGuardStore records each write a serve, create or rebind door makes |
| +// to what a route serves (a record, a channel pointer, the instances |
| +// manifest) and whether, at that moment, the serving judgement had been |
| +// made under the app lock and the lock was still held. |
| +type servingGuardStore struct { |
| + release.Store |
| + srv *Server |
| + acct string |
| + app string |
| + mu sync.Mutex |
| + judged bool |
| + writes int |
| + unjudged []string |
| +} |
| + |
| +func (g *servingGuardStore) guarded(key string) bool { |
| + return strings.HasPrefix(key, provision.RecordsPrefix(g.acct, g.app)) || |
| + strings.HasPrefix(key, release.ChannelsPrefix(g.acct, g.app)) || |
| + key == provision.ManifestKey(g.acct, g.app) |
| +} |
| + |
| +func (g *servingGuardStore) note(key string) { |
| + if !g.guarded(key) { |
| + return |
| + } |
| + held := g.srv.appLocks.held(g.acct + "/" + g.app) |
| + g.mu.Lock() |
| + defer g.mu.Unlock() |
| + g.writes++ |
| + if !g.judged || !held { |
| + g.unjudged = append(g.unjudged, fmt.Sprintf("%s (judged %v, app lock held %v)", key, g.judged, held)) |
| + } |
| +} |
| + |
| +func (g *servingGuardStore) Put(ctx context.Context, key string, body []byte, ifMatch string) (string, error) { |
| + g.note(key) |
| + return g.Store.Put(ctx, key, body, ifMatch) |
| +} |
| + |
| +func (g *servingGuardStore) Delete(ctx context.Context, key string) error { |
| + g.note(key) |
| + return g.Store.Delete(ctx, key) |
| +} |
| + |
| +// TestServingJudgedUnderTheLockBeforeEveryWrite is the guard of the one |
| +// judgement (ruled by Paul, 2026-11-14): every listed serve, create and |
| +// rebind door, driven with the switch off (so it writes), writes a record, |
| +// a channel pointer or the instances manifest only after judgeServing ran |
| +// under the app lock, and while that lock is held. judgeServing refuses a |
| +// caller without the lock, so a door that judged outside it fails here too. |
| +func TestServingJudgedUnderTheLockBeforeEveryWrite(t *testing.T) { |
| + for _, door := range submissionGateDoors { |
| + t.Run(door.pattern, func(t *testing.T) { |
| + w := newSubmissionGateWorld(t) |
| + if door.setup != nil { |
| + door.setup(t, w) |
| + } |
| + w.setSwitch(t, false) |
| + g := &servingGuardStore{Store: w.srv.cfg.Releases, srv: w.srv, acct: release.OpsAccount, app: "km"} |
| + w.srv.cfg.Releases = g |
| + w.srv.servingJudged = func(acct, app string) { |
| + if acct == g.acct && app == g.app { |
| + g.mu.Lock() |
| + g.judged = true |
| + g.mu.Unlock() |
| + } |
| + } |
| + out := door.drive(t, w) |
| + g.mu.Lock() |
| + defer g.mu.Unlock() |
| + if g.writes == 0 { |
| + t.Fatalf("%s wrote nothing with the switch off, so the guard saw nothing: %s", door.pattern, out) |
| + } |
| + if len(g.unjudged) > 0 { |
| + t.Fatalf("%s wrote what a route serves without the serving judgement under the app lock:\n %s", door.pattern, strings.Join(g.unjudged, "\n ")) |
| + } |
| + }) |
| + } |
| } |
diff --git a/internal/console/updatescore.go b/internal/console/updatescore.go| index e24ca4557..7508379a2 100644 |
| --- a/internal/console/updatescore.go |
| +++ b/internal/console/updatescore.go |
| @@ -177,7 +177,7 @@ func (s *Server) applyUpdates(ctx context.Context, acct *Account, app, principal |
| if ref := s.copiesRecordRefusal(ctx, acct, next, false); ref != nil { |
| return updatesView{}, ref.Status, ref.Msg |
| } |
| - if ref := s.submissionUpdatesRefusal(ctx, *rec, next); ref != nil { |
| + if ref := s.judgeServing(ctx, rec.Account, rec.App, servingChange{updates: &[2]provision.Record{*rec, next}}); ref != nil { |
| return updatesView{}, ref.Status, ref.Msg |
| } |
| @@ -241,7 +241,7 @@ func (s *Server) requestInstall(ctx context.Context, acct *Account, app, princip |
| if ref := s.copiesRecordRefusal(ctx, acct, next, false); ref != nil { |
| return 0, ref.Status, ref.Msg |
| } |
| - if ref := s.submissionRecordRefusal(ctx, next); ref != nil { |
| + if ref := s.judgeServing(ctx, next.Account, next.App, servingChange{record: &next}); ref != nil { |
| return 0, ref.Status, ref.Msg |
| } |
| err := provision.UpdateRecord(ctx, s.cfg.Releases, next, etag) |
diff --git a/internal/provision/platform_mail_submission_census_test.go b/internal/provision/platform_mail_submission_census_test.go| index 05f5b766c..f3a33578d 100644 |
| --- a/internal/provision/platform_mail_submission_census_test.go |
| +++ b/internal/provision/platform_mail_submission_census_test.go |
| @@ -83,6 +83,22 @@ func platformMailSubmissionWriteCensusInventory() []censusEntry { |
| {"internal/mail/walk_environment.go", "claimUnserializedEnableEnvironment", "reference", "id:Put", "aa676ba9623ffa989da7ed3c7943225d23eae78fe564a9674bd272987f92ed5e"}, |
| {"internal/mail/walk_environment.go", "claimUnserializedReapEnvironment", "reference", "id:Put", "b2d670d8ef9c26a0847fa966559aa51530760f9a0170df3f9d95523994b2f552"}, |
| {"internal/console/apiinstances.go", "Server.handleAPIInstanceUpdate", "record-writer", "key:UpdateRecord", "90385e624ddc76606423fbb6723d000c7675a5f9ec61223bd14df653c61d4803"}, |
| + // Ruled by Paul, 2026-11-14 (finishing the one-working-channel |
| + // ruling): re-digested, classification and kinds unchanged, the same |
| + // writes. Each door now judges through judgeServing, the one |
| + // judgement, under the app lock immediately before its write: the |
| + // create's record writers (createRecordMarkedLocked, |
| + // createRecordWithLifetimeLocked) judge the record they create, the |
| + // instance update door judges a rebind inside its record lock, and |
| + // the channel move and update doors call judgeServing in place of |
| + // the old gates. submissionServeDoors lists the rebind door. |
| + {"internal/console/apiinstances.go", "Server.handleAPIInstanceUpdate", "record-writer", "key:UpdateRecord", "cbb341035c7b17c743c5943743605ff57712af2de0a58301fded1be907600546"}, |
| + {"internal/console/channelmove.go", "Server.executePendingRouteChannel", "record-writer", "key:UpdateRecord", "d0ae0c5a359bb15ee33914be869d2b7d4a3042276b8e6e1c5e5272dff734a3da"}, |
| + {"internal/console/channelmove.go", "Server.handleAPIInstanceChannel", "record-writer", "key:UpdateRecord", "78373a66bdf7912e8e1a13174763aa04a3de3b780d91b85a11ada5769a03b272"}, |
| + {"internal/console/hostsused.go", "Server.createRecordMarkedLocked", "record-writer", "key:CreateRecord,key:RecordKey", "5f52e93c41991d78d3f685ae7ea1eccf89a47f96dc4b32226d90d5a08669769e"}, |
| + {"internal/console/lifetimes_create.go", "Server.createRecordWithLifetimeLocked", "key-site", "key:RecordKey", "7693b5ffa2908ee6f8856634dca0827af231679c29f83125a463901071348e99"}, |
| + {"internal/console/updatescore.go", "Server.applyUpdates", "record-writer", "key:UpdateRecord", "be499044ac2f810182d82a7220246b12031914ebba9e4c495d114b6a4204280a"}, |
| + {"internal/console/updatescore.go", "Server.requestInstall", "record-writer", "key:UpdateRecord", "016c60ecc2c8054c396c909d6f7c227b8bbdd1ee6868ac807919cecdf8986de4"}, |
| } |
| for _, r := range repins { |
| found := false |
| @@ -121,7 +137,7 @@ func platformMailSubmissionWriteCensusInventory() []censusEntry { |
| censusEntry{"internal/mail/submission.go", "claimUnserializedSwitchOff", "reference", "id:Put", "fb3b0cf11f4846eb60aefd09130b0cf0f7e243d79178f1b80446b13d312ae0c8"}, |
| censusEntry{"internal/mail/sweep.go", "claimUnserializedReapAppUserAfterSubmission", "reference", "id:Put", "1e0ec1ef110c5237e3755004103f4c2698ec68bf726f1345bde2ca64fa466acf"}, |
| censusEntry{"internal/console/alertsignals.go", "engineReads.switchedRecordHosts", "key-site", "key:RecordsPrefix", "9d474c76f8e5326bb99c79b03fd4677adbec77564172a66d1b4a625d2e33e294"}, |
| - censusEntry{"internal/console/submissiongate.go", "var submissionServeDoors", "key-site", "lit:instances", "ffdd74f701289aca38df6d6c47afa10532ba39acee8260b406c66320c1fc2dad"}, |
| + censusEntry{"internal/console/submissiongate.go", "var submissionServeDoors", "key-site", "lit:instances", "072f05e9822cafc73b07ad5863617b9a5db348362b2e747a3ef71b6e665d134b"}, |
| ) |
| return entries |
| } |
diff --git a/internal/provision/testdata/plan14-root-reads-platform-mail-submission.tsv b/internal/provision/testdata/plan14-root-reads-platform-mail-submission.tsv| index 9d26d9b9b..da16b86eb 100644 |
| --- a/internal/provision/testdata/plan14-root-reads-platform-mail-submission.tsv |
| +++ b/internal/provision/testdata/plan14-root-reads-platform-mail-submission.tsv |
| @@ -95,7 +95,7 @@ internal/host/agent.go runAgent authority B,C,D,F rev3=census-ruling-self-serve- |
| @coverage internal/host/units 63a333f0bb4a354fdde9802089f4ec6794cdfbf774c20fbd48cffab805cd022c |
| @coverage internal/hostenv 6c96c4abe8548fe3cf12d3a220de3e2917c3edfa5320b1662ea76bdf364d24b5 |
| @coverage internal/instancectl 811493ad636a21f5f8e7f2336e8e58055fd2a83f53dd71ef689cd90232e7d3df |
| -@coverage internal/mailer 8480d8ca048f2f7e966e317d74b3aac864e28d270216459f1386ef929c354bae |
| +@coverage internal/mailer 6837ba5a107c9035fbf946cd7fb490940e69a1a42f77d1f34425d284ded5c2ec |
| @coverage internal/mailsubmit 519123e15891e0802427595306d8caca1fd7f4f861ae1a2ec70e1c10f012e263 |
| @coverage internal/mailwire 0242392c670a0f61b875056b0d79576ccb69c2e29f56735cbb191e7d038222a0 |
| @coverage internal/moves 9390702695d308a327f5572f4ff5967718141c5d385dff7671ff1e2c825ef407 |