email: Task 6 review fixes (Fable P2-5 and P3s)
P2-1..P2-4 (the one-working-channel family) are left for Paul's choice, and P2-6 (copy) is his review. - P2-5: switch-on keeps AppUserReapedAt only while Provisioned is nil, so an on, reap, off, on cycle reaps again after the next week. - The declare prefix lock also holds while switched, and Enable delivers a re-declared From to the default bundle while switched. - The door judges the From domain by the mailer's own rule (mailwire.CheckFromDomain, now shared with the mailer's policy): granted, listed for the app, verified and with a configuration set. A configuration set whose ARN cannot be built is refused, not dropped. - mailer_unarmed reads the boxes the door reads: the account's fleets' boxes too, and RouteServing as well as RouteVersions. A fleet box fires only for its own account's apps; an unlistable registry keeps open incidents. - A caller-class send the console could not record holds the reap: it is kept as a gap, written as an "unrecorded" row once the store accepts, and the reap reads that day as unclean. - Tests for the 409 NotEnabled, the configuration-set and From-domain refusals and the serve gate's fail-closed sender read. - Census: runAgent's claim names Task 6's ManifestOf read; the root-read overlay is re-proposed and the record-write layer re-pinned. The plan's G7 text says what was built: the spawn-time log, no adopt-pass log. - Copy: PMS-C41 FromNotSendable, PMS-C42 ConfigSetUnbuildable (draft).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
24 files changed,
+714
−118
approved_platform_mail_submission_copy_test.go+1 −1docs/superpowers/notes/census-claims-platform-mail-submission.tsv+1 −1docs/superpowers/notes/census-plan-platform-mail-submission.md+1 −1docs/superpowers/notes/census-proposal-platform-mail-submission.md+1 −1docs/superpowers/plans/2026-11-13-platform-mail-submission.md+3 −3docs/superpowers/plans/platform-mail-submission-copy.json+12 −0internal/console/alertengine_pass_test.go+1 −1internal/console/alertmailer_test.go+106 −7internal/console/alertsignals.go+123 −44internal/console/apisubmission.go+110 −26internal/console/apisubmission_test.go+146 −0internal/console/mailcounts.go+1 −1internal/console/server.go+2 −0internal/console/sesevents.go+4 −0internal/console/submissioncopy.go+4 −0internal/mail/sender.go+5 −0internal/mail/submission.go+6 −1internal/mail/submission_test.go+88 −0internal/mail/sweep.go+3 −1internal/mail/walk.go+13 −1internal/mailer/policy.go+24 −23internal/mailwire/mailwire.go+40 −0internal/provision/platform_mail_submission_census_test.go+16 −3internal/provision/testdata/plan14-root-reads-platform-mail-submission.tsv+3 −3
diff --git a/approved_platform_mail_submission_copy_test.go b/approved_platform_mail_submission_copy_test.go| index 147190304..05c38f7bb 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-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", |
| } |
| // Every string of the switch's copy record is in the file it names, byte |
diff --git a/docs/superpowers/notes/census-claims-platform-mail-submission.tsv b/docs/superpowers/notes/census-claims-platform-mail-submission.tsv| index 2493bfba4..1179c52ad 100644 |
| --- a/docs/superpowers/notes/census-claims-platform-mail-submission.tsv |
| +++ b/docs/superpowers/notes/census-claims-platform-mail-submission.tsv |
| @@ -38,7 +38,7 @@ internal/activator/backend_exec.go:ExecBackend.agentOwnedVars Task 4: also decid |
| internal/activator/backend_exec.go:ExecBackend.mailSubmits Task 4, new: the CARLOS_MAIL rule. Reads rt.App, rt.Host, rt.Provisioned and RouteAccount(rt) from the agent's own registry row, and asks b.MailSwitch (the agent's cache of the console-written app sender record, internal/host/mailswitch.go: one bounded Get of apps/<acct>/<app>/email/senders/app.json through the agent's deploy store). Logs once per host at error level for an unprovisioned route of a switched app. Agent, not root; no file read. |
| internal/mailsubmit/verb.go:Mount Task 4, new: POST /v1/mail on an instance's control socket. The bearer by the existing verbs' rule (empty or unreadable token refuses everything; SHA-256 constant-time compare); MaxBytesReader(14 MiB), the JSON envelope, base64 raw of at most 10 MiB, 1 to 50 non-empty recipients, a non-empty from, else 400 BAD_REQUEST; at most 2 messages per socket in the agent at once, the next 429 RATE (review round 1, Task 4 P3). Stamps account, app and host from the route the socket was bound for, never from the body, and forwards; a transport error or an answer outside 200/400/403/429/503 is 503 MAILER_UNAVAILABLE. Runs in the agent, as carlos; the body is a tenant's and is only decoded and forwarded, never used to name a path, route or account. |
| internal/mailsubmit/forward.go:SocketForwarder.Send Task 4, new: the agent's client to the mailer: one HTTP POST of /v1/send over a fresh dial of the constant /run/carlos-mailer/mailer.sock, 60 s timeout, answer read to at most 64 KiB and decoded. Runs in the agent, as carlos. The socket's directory is root's; the mailer at the other end is a separate uid. |
| -internal/host/agent.go:runAgent Task 4: sets eb.Mail = mailsubmit.SocketForwarder{} on every box, and eb.MailSwitch to a mailSwitchCache's On that opens the deploy store itself through openDeployStore, retried at most once a minute with an error line until it opens (review round 1, Task 4 P3), armed for the serial-move refresh (armedMailSwitch). Agent, not root. |
| +internal/host/agent.go:runAgent Task 4: sets eb.Mail = mailsubmit.SocketForwarder{} on every box, and eb.MailSwitch to a mailSwitchCache's On that opens the deploy store itself through openDeployStore, retried at most once a minute with an error line until it opens (review round 1, Task 4 P3), armed for the serial-move refresh (armedMailSwitch). Task 6: also sets the ExecBackend's ManifestOf, the same staged-manifest read as TierOf (rt.App and RouteAccount(rt), hence +registry:App and +whole:Route), for the spawn-time check of decision 10, which logs and emits an event and never refuses. Agent, not root. |
| internal/host/agent.go:fastTick Task 4: on a serial move, after the schedule leg, starts the armed mail switch cache's Refresh on its own goroutine (each read bounded at 2 s, overlapping refreshes skipped). It re-reads the app sender records already cached, through the agent's deploy store. Agent, not root; the tick waits on nothing new. |
| # |
| # Task 5 (the mailer's send: policy, hygiene, rate, per-box cap, SES). |
diff --git a/docs/superpowers/notes/census-plan-platform-mail-submission.md b/docs/superpowers/notes/census-plan-platform-mail-submission.md| index 1bc744ae9..fa58f135b 100644 |
| --- a/docs/superpowers/notes/census-plan-platform-mail-submission.md |
| +++ b/docs/superpowers/notes/census-plan-platform-mail-submission.md |
| @@ -86,7 +86,7 @@ Envelopes re-pinned: `internal/host/units`, `internal/host`, `internal/instancec |
| | `internal/mailsubmit/*` (every unit) | new | (0) | New package. `Mount` (`POST /v1/mail`: bearer by the existing verbs' rule, where an empty or unreadable token refuses everything and the compare is constant-time over SHA-256; size and shape checks; stamps account, app and host from the route, never the body) and `SocketForwarder` (HTTP over `/run/carlos-mailer/mailer.sock`). Agent process | |
| | `internal/mailwire/*` (every unit) | new | (0) | New package, first in the root binary here. Pure wire types and helpers: `Pause`, `Submission`, `SenderView`, key functions, tag names, `IsMailerCaller`, the tier default cap. No I/O | |
| | `internal/host/mailswitch.go` (every unit) | new | +1 bucket read | The agent's switch cache. A bounded `Get` of `apps/<acct>/<app>/email/senders/app.json` (console-written), decoded as `mailwire.SenderView`. Agent, not root | |
| -| `internal/host/agent.go` `runAgent` | body | unchanged | Wires `eb.Mail`, `eb.MailSwitch` and the cache's refresh on the serial bump. Agent, not root | |
| +| `internal/host/agent.go` `runAgent` | sites | +registry:App, +whole:Route | Wires `eb.Mail`, `eb.MailSwitch` and the cache's refresh on the serial bump. Task 6 adds `ManifestOf`, the same staged-manifest read as `TierOf`, for the spawn-time log of decision 10: the new sites are its `rt.App` and `RouteAccount(rt)`. Agent, not root | |
| Envelopes re-pinned: `internal/activator`, `internal/moves`, `internal/host`. New envelopes: `internal/mailsubmit`, `internal/mailwire`. |
diff --git a/docs/superpowers/notes/census-proposal-platform-mail-submission.md b/docs/superpowers/notes/census-proposal-platform-mail-submission.md| index 834f7ac04..c19b8ebda 100644 |
| --- a/docs/superpowers/notes/census-proposal-platform-mail-submission.md |
| +++ b/docs/superpowers/notes/census-proposal-platform-mail-submission.md |
| @@ -30,7 +30,7 @@ Ruling `census-ruling-platform-mail-submission`. The independent reviewer approv |
| | `internal/activator/backend_exec.go` `ExecBackend.spawnUnitFrom` | sites | +whole:Route ×2 | Task 6: calls warnUndeclaredMailBuild with the route and the version being spawned. Logs and emits an instance event once per (host, version) when the app is switched and the staged manifest does not declare --mail submit; never refuses. Agent, not root. | |
| | `internal/activator/prepare.go` `ExecBackend.listenControl` | sites | -registry:Host ×3, +whole:Route | Task 4: the same replacement as spawnChildFrom, with gen as the write fence's generation, so the nested and rootfs listener mounts exactly what the flat one does. Agent, not root. | |
| | `internal/activator/rootfs.go` `ExecBackend.spawnRootfs` | sites | +whole:Route | Task 6: the same warnUndeclaredMailBuild call for a rootfs spawn. Agent, not root. | |
| -| `internal/host/agent.go` `runAgent` | sites | +registry:App, +whole:Route | Task 4: sets eb.Mail = mailsubmit.SocketForwarder{} on every box, and eb.MailSwitch to a mailSwitchCache's On that opens the deploy store itself through openDeployStore, retried at most once a minute with an error line until it opens (review round 1, Task 4 P3), armed for the serial-move refresh (armedMailSwitch). Agent, not root. | |
| +| `internal/host/agent.go` `runAgent` | sites | +registry:App, +whole:Route | Task 4: sets eb.Mail = mailsubmit.SocketForwarder{} on every box, and eb.MailSwitch to a mailSwitchCache's On that opens the deploy store itself through openDeployStore, retried at most once a minute with an error line until it opens (review round 1, Task 4 P3), armed for the serial-move refresh (armedMailSwitch). Task 6: also sets the ExecBackend's ManifestOf, the same staged-manifest read as TierOf (rt.App and RouteAccount(rt), hence +registry:App and +whole:Route), for the spawn-time check of decision 10, which logs and emits an event and never refuses. Agent, not root. | |
| Envelopes re-pinned: `.`, `infra/modules/region-host`, `infra/modules/region-host/tests`, `internal/activator`, `internal/host`, `internal/host/demo_units`, `internal/host/units`, `internal/hostenv`, `internal/instancectl`, `internal/mailer`, `internal/mailsubmit`, `internal/mailwire`, `internal/moves`, `internal/provision`, `internal/release`, `internal/status`. |
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 25e949360..6f4d1abf9 100644 |
| --- a/docs/superpowers/plans/2026-11-13-platform-mail-submission.md |
| +++ b/docs/superpowers/plans/2026-11-13-platform-mail-submission.md |
| @@ -36,7 +36,7 @@ Each gap names the task it blocks, the spec text, what the code shows, and a rec |
| | G4 | Task 6 | Decision 10: "**Before §7.4's reap, `carlos email test --submit`** sends through the submit path per route, as proof" | Only the agent can reach an instance's control socket (round 3's own P3). The console has no path to make a route send | Gate the §7.4 reap on **event evidence** instead. The evidence is a per-app, per-day count of Send events **by caller class**, which Task 2 records (`mail_caller_sends`, round 1 P2-1): `mail_events` has no caller column, and every class resolves to sender `app`. The reap needs all three of these:<br>• at least 7 days since the switch;<br>• at least one `mailer` Send for the app;<br>• no `app_user` Send (`carlos-mail-<acct>-<app>`) in the last 7 days.<br>**What this proves:** the app-level SMTP key stopped being used. It does **not** prove that submit works on every route. A route that never sends proves nothing either way, and a route that cannot submit shows up as its app's own failures and the mailer's refusals, not here. `--submit` is left out of this plan **Ruled by Paul, 2026-11-13: as recommended** (no `app_user` send for 7 days, from `mail_caller_sends`). | |
| | G5 | Task 8 | §5: the IAM policy is "conditioned on `ses:FromAddress` matching the platform's verified identities, or on `ses:TenantName`" | One fleet-wide user cannot carry a static `ses:FromAddress` list: identities are created at runtime by the console, per account. Terraform cannot enumerate them | `ses:SendRawEmail` on `arn:aws:ses:<mail_region>:<acct>:identity/*` and `configuration-set/carlos-*` only, with no From condition. The mailer's From check is the gate (as §5 already says); IAM bounds the account, region and resource types. Add the `ses:TenantName` `StringLike carlos-*` condition only once §9 item 3's backfill has landed (it would refuse every untenanted send). Round 3's P3 list already names this | |
| | G6 | Task 8, Task 9 | §5: key "armed by the operator by hand", and never through `user_data`, SSM or the bucket | Group-mode boxes are launched unattended by their Auto Scaling group (`group-init.sh.tftpl:312-338`). A new or replaced group box has **no key**, so its mailer never starts and every switched instance on it answers `503 MAILER_UNAVAILABLE` until someone arms it. Every automatic delivery path the spec rules out is one uid `carlos` can read | Ask Paul. Options: (a) switched apps run on fixed boxes only, refused by the door; (b) the box reports "mailer armed" in its status record, the door and an alert read it, and the operator arms each new box (a runbook step per scale event); (c) a separate design for unattended key delivery. This plan builds (b)'s report and alert (Task 3 step 6, Task 6 precondition) because it helps under every option **Ruled by Paul, 2026-11-13: (b).** Group boxes answer `503` until armed by hand; the `mailer_unarmed` alert flags them. | |
| -| G7 | Task 6 | Decision 10: "**Adopting**, rolling back to, or pinning a build whose manifest lacks the declaration is refused" | Every person-facing change of what a route serves goes through a console door. A box's `carlos adopt` (root) also adopts channel heads that a direct-bucket promote (pinfra scripts) moved, without the console | Refuse at every console door that changes what a route serves (one shared check, and a guard test over the route table). At the box, log loudly and raise an event on adopt and on wake, as decision 10 already does for wake. A box-side adopt **refusal** would be new root authority, and the plan does not add it unless Paul asks | |
| +| G7 | Task 6 | Decision 10: "**Adopting**, rolling back to, or pinning a build whose manifest lacks the declaration is refused" | Every person-facing change of what a route serves goes through a console door. A box's `carlos adopt` (root) also adopts channel heads that a direct-bucket promote (pinfra scripts) moved, without the console | Refuse at every console door that changes what a route serves (one shared check, and a guard test over the route table). At the box, log loudly and raise an event when a switched app's route starts an undeclared build, as decision 10 already does for wake. **As built (Task 6):** the log is at spawn only, in the agent, on every launch path (flat, unit, rootfs), once per (host, version). An adopted head is caught there, at its first start. The adopt pass itself (`carlos adopt`, root) does not log: it would have to read the app's switch, a new root read of a console-written object, and the plan does not add one. A box-side adopt **refusal** would be new root authority, and the plan does not add it unless Paul asks | |
| | G8 | Task 6 | §5 Tenants: "The switch refuses an app whose sender would send with an unassociated tenant" | Nothing records whether an identity or configuration set is associated with its tenant (`DomainRecord`, `internal/mail/domain.go:59-66`). Senders spec §4.2.1's backfill is §9 item 3, still open | The door asks SES live (`ListTenantResources`) through the console's provisioner, only when the app sender has a `TenantARN`. The control-plane role may need `ses:ListTenantResources`. That policy is not in this repo (senders spec §4.2 item 2). A sender with no `TenantARN` sends without `TenantName` and needs no association | |
| | G10 | Task 4, Task 9, operator step 8 | Decision 11: rastrillo "fails loudly at boot when a switched app has neither channel" | With `CARLOS_MAIL` set only for `rt.Provisioned` (round 1 P2-2), a **hand-made route** (a registry row with no instance record) of a switched app has neither channel. Its bundle lost the SMTP variables, so rastrillo refuses at boot: **a mail gap becomes a site outage for that route**. Nothing in the door can see such a route, because the box report keys `RouteVersions` by host, not by app (round 2 P2-B; family "one working channel", second round) | **Paul's choice.** The plan as written takes (a), and the copy and the operator check say so.<br>(a) Accept it, with an operator check before switch-on that every route of the app has an instance record (operator step 8), and the outage named in the `email submission on` copy.<br>(b) Add the app to the box report (a host-to-app map) so the door can refuse.<br>(c) Let rastrillo fall back to logged mail rather than refuse at boot, which reverses decision 11's loud failure **Ruled by Paul, 2026-11-13: (a).** The hand-made-route outage is accepted, with the operator check before each switch-on. | |
| | G9 | Task 5 | §5 Rate: "a per-sender token bucket" | No rate or burst is given | 2 messages a second, a burst of 20, per sender per box, as package constants. Paul to confirm against the deployment's SES send rate **Ruled by Paul, 2026-11-13: confirmed,** 2/s with a burst of 20. | |
| @@ -406,7 +406,7 @@ Tasks 1 and 2 can start at once and run in parallel. Task 7 can start once Task |
| - Modify: `internal/mail/walk.go` (`claimUnserializedEnable` `:761`, `claimUnserializedRotate` `:1031`, `claimUnserializedSetSenderPaused` relaxed for switched senders), `internal/mail/walk_environment.go` (`claimUnserializedEnableEnvironment`), `internal/mail/sweep.go` (the §7.4 reap) |
| - Create: `internal/mail/submission.go`, `internal/mail/submission_test.go` |
| - Modify: the console doors that change what a route serves. Step 1 enumerates them; at least `handleAPIPromote` (`apicli.go:909`), `handleAPIRollback` (`:1312`), `handleAPIInstanceChannel`, `handleAPIUpdatesPut`, `handleAPIUpdatesInstall` and `handleAPIUpdatesPolicy`. |
| -- Modify: `internal/activator` (the spawn paths' loud log), `internal/host` (the adopt pass's loud log and event) |
| +- Modify: `internal/activator` (the spawn paths' loud log), `internal/host` (`runAgent` wires the spawn check's staged-manifest read; the adopt pass is unchanged, see G7) |
| - Modify: `mail_cli.go` (`carlos email submission on|off`, the status line), the command registry, `parity/parity.tsv`, `docs/site/cli.md` |
| - Create: `docs/superpowers/plans/platform-mail-submission-copy.json`, `approved_platform_mail_submission_copy_test.go` |
| - Test: `internal/console/teamcreds_test.go` (guard tests 17 and 19), `internal/release/release_test.go` |
| @@ -441,7 +441,7 @@ Tasks 1 and 2 can start at once and run in parallel. Task 7 can start once Task |
| - `alertRuleKind("mailer_unarmed")` is the box kind and `alertRuleLevel` is warning. The copy row is drafted in step 0. |
| - `alertengine_pass.go` calls it beside `heartbeatBoxSignals` and passes `sig.cover("mailer_unarmed", unread)`, so a box whose snapshot was unreadable is unknown, not clear. |
| A flat route is **not** a refusal (decision 7, test 8.8). It then calls `mail.SwitchOn`, bumps the serial, and requests an app-wide restart through the existing restart-gen path (`handleAPIRestart`, `apicli.go:1582`). Running instances then respawn with `CARLOS_MAIL`. Until they do, they send over SMTP on the kept app-level key. `on: false` calls `mail.SwitchOff`, bumps the serial and requests the restart. |
| -- **The precondition holds while on** (decision 10, test 8.12): `func (s *Server) submissionBuildRefusal(ctx, acct, app, version string) *doorRefusal` returns `409` "this build does not declare `--mail submit`, and email submission is on for <app>: switch submission off first (carlos email submission off --app <app>), or ship with --mail submit". Every door from step 1's enumeration calls it before it writes. Waking is never refused. Instead, at spawn, when `MailSwitch` is on and the staged manifest's `Mail != "submit"`, the agent logs at error level and emits an instance event, once per (host, version). The adopt pass does the same when it adopts such a head (G7). |
| +- **The precondition holds while on** (decision 10, test 8.12): `func (s *Server) submissionBuildRefusal(ctx, acct, app, version string) *doorRefusal` returns `409` "this build does not declare `--mail submit`, and email submission is on for <app>: switch submission off first (carlos email submission off --app <app>), or ship with --mail submit". Every door from step 1's enumeration calls it before it writes. Waking is never refused. Instead, at spawn, when `MailSwitch` is on and the staged manifest's `Mail != "submit"`, the agent logs at error level and emits an instance event, once per (host, version). The adopt pass does not log (G7, as built): an adopted head is logged at its first spawn, and a log in the root adopt pass would need a new root read of the switch. |
| - The status reply and `carlos email status` gain a Submission block: on or off, since when, whether the app-level user is kept or reaped, and the boxes not armed. |
| - [ ] **Step 0: UX pass, then copy review** (AGENTS.md). Mock the CLI output of `email submission on|off` and the status block, the five precondition refusals, the build refusal, and the `mailer_unarmed` alert's title and body, at 80 columns. **The `email submission on` confirmation names the G10 outage** (round 2 P2-B). A route with no instance record cannot send mail once this is on, and its app will refuse to start, so check `carlos instances --app <a>` first. Lead with the state. Draft IDs `PMS-C1`.. in `platform-mail-submission-copy.json`. Run the copy-review skill, and apply Paul's edits verbatim. `TestApprovedPlatformMailSubmissionCopy` via `checkApprovedCopy` (`approved_copy_test.go:71`). **Paul's step.** |
diff --git a/docs/superpowers/plans/platform-mail-submission-copy.json b/docs/superpowers/plans/platform-mail-submission-copy.json| index 49b2ef49d..96260e987 100644 |
| --- a/docs/superpowers/plans/platform-mail-submission-copy.json |
| +++ b/docs/superpowers/plans/platform-mail-submission-copy.json |
| @@ -242,6 +242,18 @@ |
| "file": "internal/activator/mailbuild.go", |
| "text": "build %s does not declare --mail submit, and email submission is on for this app, so it cannot send mail: ship with --mail submit, or switch submission off", |
| "note": "spawn event" |
| + }, |
| + { |
| + "id": "PMS-C41", |
| + "file": "internal/console/submissioncopy.go", |
| + "text": "This app sends as %s, and the box's mailer would refuse it: %s must be granted to the app, list the app and be verified in %s. Run carlos email enable for the app again.", |
| + "note": "FromNotSendable" |
| + }, |
| + { |
| + "id": "PMS-C42", |
| + "file": "internal/console/submissioncopy.go", |
| + "text": "Can't name the configuration set of %s from its identity, so its tenant can't be checked. Run carlos email domains add for it again.", |
| + "note": "ConfigSetUnbuildable" |
| } |
| ] |
| } |
diff --git a/internal/console/alertengine_pass_test.go b/internal/console/alertengine_pass_test.go| index 592d4744b..443dd40b8 100644 |
| --- a/internal/console/alertengine_pass_test.go |
| +++ b/internal/console/alertengine_pass_test.go |
| @@ -232,7 +232,7 @@ func TestEngineReadsUnsupportedFallsBackToPlain(t *testing.T) { |
| if err != nil || !changed || string(body) != `{}` { |
| t.Fatalf("get = %q, %v, %v; want the object read plainly", body, changed, err) |
| } |
| - keys, err := engineBoxKeyList(ctx, store, alertT0) |
| + keys, err := engineBoxKeyList(ctx, store, alertStatusBoxesPrefix, alertT0) |
| if err != nil || len(keys) != 1 { |
| t.Fatalf("listing = %v, %v; want the object listed plainly", keys, err) |
| } |
diff --git a/internal/console/alertmailer_test.go b/internal/console/alertmailer_test.go| index 4d252f3d8..e41863044 100644 |
| --- a/internal/console/alertmailer_test.go |
| +++ b/internal/console/alertmailer_test.go |
| @@ -3,6 +3,7 @@ package console |
| import ( |
| "context" |
| "encoding/json" |
| + "os" |
| "strings" |
| "testing" |
| "time" |
| @@ -10,6 +11,7 @@ import ( |
| "github.com/carlosframework/platform/internal/alerting" |
| "github.com/carlosframework/platform/internal/mailwire" |
| "github.com/carlosframework/platform/internal/provision" |
| + "github.com/carlosframework/platform/internal/registry" |
| "github.com/carlosframework/platform/internal/status" |
| ) |
| @@ -39,7 +41,7 @@ func mailerBox(label string, at time.Time, armed bool, hosts ...string) status.B |
| func TestMailerUnarmedSignal(t *testing.T) { |
| now := alertT0 |
| fresh, stale := now.Add(-time.Minute), now.Add(-2*time.Hour) |
| - switched := map[string]bool{"shop.example.com": true} |
| + switched := map[string]string{"shop.example.com": "bab"} |
| expect := func(t *testing.T, sig *alertSignals, box string, firing bool) { |
| t.Helper() |
| @@ -59,25 +61,25 @@ func TestMailerUnarmedSignal(t *testing.T) { |
| t.Run("unarmed box hosting a switched route fires", func(t *testing.T) { |
| sig := newAlertSignals() |
| mailerUnarmedSignals([]status.Box{mailerBox("box-1", fresh, false, "blog.example.com", "shop.example.com")}, |
| - switched, false, nil, now, sig) |
| + nil, switched, false, nil, now, sig) |
| expect(t, sig, "box-1", true) |
| }) |
| t.Run("the same box armed is clear", func(t *testing.T) { |
| sig := newAlertSignals() |
| mailerUnarmedSignals([]status.Box{mailerBox("box-1", fresh, true, "blog.example.com", "shop.example.com")}, |
| - switched, false, nil, now, sig) |
| + nil, switched, false, nil, now, sig) |
| expect(t, sig, "box-1", false) |
| }) |
| t.Run("unarmed box hosting only unswitched routes is clear", func(t *testing.T) { |
| sig := newAlertSignals() |
| mailerUnarmedSignals([]status.Box{mailerBox("box-2", fresh, false, "blog.example.com"), |
| - {Label: "box-5", GeneratedAt: fresh}}, switched, false, nil, now, sig) |
| + {Label: "box-5", GeneratedAt: fresh}}, nil, switched, false, nil, now, sig) |
| expect(t, sig, "box-2", false) |
| expect(t, sig, "box-5", false) // no metrics at all |
| }) |
| t.Run("a stale box adds nothing", func(t *testing.T) { |
| sig := newAlertSignals() |
| - mailerUnarmedSignals([]status.Box{mailerBox("box-3", stale, false, "shop.example.com")}, switched, false, nil, now, sig) |
| + mailerUnarmedSignals([]status.Box{mailerBox("box-3", stale, false, "shop.example.com")}, nil, switched, false, nil, now, sig) |
| if sg, ok := mailerSignal(sig, "box-3"); ok { |
| t.Fatalf("stale box-3 added %+v", sg) |
| } |
| @@ -85,7 +87,7 @@ func TestMailerUnarmedSignal(t *testing.T) { |
| t.Run("an unreadable box is unknown, not clear", func(t *testing.T) { |
| sig := newAlertSignals() |
| unread := map[string]bool{"box-4": true} |
| - mailerUnarmedSignals([]status.Box{mailerBox("box-2", fresh, false, "blog.example.com")}, switched, false, unread, now, sig) |
| + mailerUnarmedSignals([]status.Box{mailerBox("box-2", fresh, false, "blog.example.com")}, nil, switched, false, unread, now, sig) |
| if !sig.covered["mailer_unarmed"]["box-4"] { |
| t.Fatalf("covered = %v, want box-4 unknown", sig.covered["mailer_unarmed"]) |
| } |
| @@ -100,13 +102,33 @@ func TestMailerUnarmedSignal(t *testing.T) { |
| t.Fatalf("the caller's unread map was changed: %v", unread) |
| } |
| }) |
| + // Task 6 review P3: the alert reads the boxes the door reads. A route |
| + // only serving (not installed) counts, and a fleet's box fires only for |
| + // its own account's apps. |
| + t.Run("a route only serving counts", func(t *testing.T) { |
| + sig := newAlertSignals() |
| + b := mailerBox("box-7", fresh, false) |
| + b.Metrics.RouteServing = map[string]string{"shop.example.com": "v2"} |
| + mailerUnarmedSignals([]status.Box{b}, nil, switched, false, nil, now, sig) |
| + expect(t, sig, "box-7", true) |
| + }) |
| + t.Run("a fleet box fires for its own account only", func(t *testing.T) { |
| + sig := newAlertSignals() |
| + owner := map[string]string{"fleets/f1/box-1": "bab", "fleets/f2/box-1": "zzz"} |
| + mailerUnarmedSignals([]status.Box{ |
| + mailerBox("fleets/f1/box-1", fresh, false, "shop.example.com"), |
| + mailerBox("fleets/f2/box-1", fresh, false, "shop.example.com"), |
| + }, owner, switched, false, nil, now, sig) |
| + expect(t, sig, "fleets/f1/box-1", true) |
| + expect(t, sig, "fleets/f2/box-1", false) |
| + }) |
| t.Run("a partial switched set clears no unarmed box it cannot fire for", func(t *testing.T) { |
| sig := newAlertSignals() |
| mailerUnarmedSignals([]status.Box{ |
| mailerBox("box-1", fresh, false, "shop.example.com"), |
| mailerBox("box-2", fresh, false, "blog.example.com"), |
| mailerBox("box-6", fresh, true, "blog.example.com"), |
| - }, switched, true, nil, now, sig) |
| + }, nil, switched, true, nil, now, sig) |
| expect(t, sig, "box-1", true) |
| expect(t, sig, "box-6", false) |
| if sg, ok := mailerSignal(sig, "box-2"); ok || !sig.covered["mailer_unarmed"]["box-2"] { |
| @@ -181,3 +203,80 @@ func TestEnginePassMailerUnarmed(t *testing.T) { |
| t.Fatalf("%d mailer_unarmed incidents open after box-1 was armed, want 0", n) |
| } |
| } |
| + |
| +// TestEnginePassMailerUnarmedFleetBox (Task 6 review P3): the pass reads |
| +// the fleet boxes of an account with a switched app, as the switch's door |
| +// does, and fires for the unarmed one hosting the app's route; a fleet of |
| +// an account with no switched app is not read. A registry that cannot be |
| +// listed keeps the open fleet box incident. |
| +func TestEnginePassMailerUnarmedFleetBox(t *testing.T) { |
| + ef := newEngineFixture(t, nil) |
| + ef.operator(t, opA) |
| + ctx := context.Background() |
| + if _, err := ef.st.CreateApp("shop", "test", alertT0); err != nil { |
| + t.Fatal(err) |
| + } |
| + b, err := json.Marshal(mailwire.SenderView{ID: mailwire.SenderAppID, Submission: &mailwire.Submission{On: true, At: alertT0}}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + putAlertBody(t, ef.rel, mailwire.SenderKey(opsSqid, "shop", mailwire.SenderAppID), b) |
| + if err := provision.CreateRecord(ctx, ef.rel, provision.Record{Schema: 1, Host: "shop.example.com", Slug: "shop", |
| + App: "shop", Account: opsSqid, Channel: "stable", CreatedAt: alertT0}); err != nil { |
| + t.Fatal(err) |
| + } |
| + reg := openTestReg(t, ef.consoleFixture) |
| + for name, acct := range map[string]string{"own": opsSqid, "other": "zzz"} { |
| + if _, err := reg.CreateFleet(registry.Fleet{Name: name, Account: acct, Bucket: name + "-bucket"}); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + ef.fleetServices(t, map[string]bool{"keymail": true}) |
| + beat := func(at time.Time) { |
| + ef.heartbeat(t, "box-1", at, &status.BoxMetrics{MailerArmed: true, RouteVersions: map[string]string{"shop.example.com": "v1"}}) |
| + for _, f := range []string{"own", "other"} { |
| + body, err := json.Marshal(status.Box{GeneratedAt: at, Label: "fbox", Metrics: &status.BoxMetrics{ |
| + RouteServing: map[string]string{"shop.example.com": "v1"}}}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + putAlertBody(t, ef.rel, "fleets/"+f+"/status/boxes/fbox.json", body) |
| + } |
| + } |
| + beat(alertT0) |
| + ef.passAt(t, 0) |
| + beat(alertT0.Add(4 * time.Minute)) |
| + rec := recordS3(ef.lat, nil) |
| + ef.passesTo(t, time.Minute, 5*time.Minute) |
| + read := map[string]bool{} |
| + for _, q := range rec.all() { |
| + read[q.Prefix+q.Key] = true |
| + } |
| + if !read["fleets/own/status/boxes/"] || !read["fleets/own/status/boxes/fbox.json"] { |
| + t.Fatalf("the switched account's fleet was not read: %v", read) |
| + } |
| + fire := ef.mailsTo(opA) |
| + if len(fire) != 1 || !strings.Contains(fire[0], "fleets/own/fbox") || strings.Contains(fire[0], "fleets/other/") || |
| + strings.Contains(fire[0], "box-1 ") { |
| + t.Fatalf("A got %v, want one mailer_unarmed fire for fleets/own/fbox only", fire) |
| + } |
| + if n := ef.count(t, `SELECT COUNT(*) FROM alert_incidents WHERE closed_at IS NULL AND rule = 'mailer_unarmed'`); n != 1 { |
| + t.Fatalf("%d mailer_unarmed incidents open, want 1", n) |
| + } |
| + for k := range read { |
| + if strings.HasPrefix(k, "fleets/other/") { |
| + t.Fatalf("the fleet of an account with no switched app was read: %s", k) |
| + } |
| + } |
| + |
| + // The registry gone: the fleets cannot be listed, so the open fleet |
| + // box incident keeps its state rather than clear. |
| + if err := os.Rename(ef.regPath, ef.regPath+".gone"); err != nil { |
| + t.Fatal(err) |
| + } |
| + beat(alertT0.Add(9 * time.Minute)) |
| + ef.passesTo(t, 6*time.Minute, 10*time.Minute) |
| + if n := ef.count(t, `SELECT COUNT(*) FROM alert_incidents WHERE closed_at IS NULL AND rule = 'mailer_unarmed'`); n != 1 { |
| + t.Fatalf("%d mailer_unarmed incidents open with the registry unreadable, want 1", n) |
| + } |
| +} |
diff --git a/internal/console/alertsignals.go b/internal/console/alertsignals.go| index 6738bd7b4..326146986 100644 |
| --- a/internal/console/alertsignals.go |
| +++ b/internal/console/alertsignals.go |
| @@ -35,6 +35,7 @@ import ( |
| "github.com/carlosframework/platform/internal/mailwire" |
| "github.com/carlosframework/platform/internal/metrics" |
| "github.com/carlosframework/platform/internal/provision" |
| + "github.com/carlosframework/platform/internal/registry" |
| "github.com/carlosframework/platform/internal/release" |
| "github.com/carlosframework/platform/internal/status" |
| ) |
| @@ -142,63 +143,75 @@ func (r *engineReads) forget(prefix string, keys []string) { |
| // signals on. listedBoxes and unreadBoxes record what the listing held and |
| // what of it could not be read. |
| func (r *engineReads) boxes(ctx context.Context, store release.Store, now time.Time) ([]status.Box, error) { |
| - keys, err := engineBoxKeyList(ctx, store, now) |
| + boxes, _, listed, unread, err := r.boxesUnder(ctx, store, alertStatusBoxesPrefix, now) |
| if err != nil { |
| return nil, err |
| } |
| - r.forget(alertStatusBoxesPrefix, keys) |
| - r.listedBoxes, r.unreadBoxes = map[string]bool{}, map[string]bool{} |
| - var boxes []status.Box |
| + r.listedBoxes, r.unreadBoxes = listed, unread |
| + return boxes, nil |
| +} |
| + |
| +// boxesUnder is boxes for the box reports under prefix (status/boxes/, or |
| +// a fleet's fleets/<name>/status/boxes/): the boxes read, every key |
| +// listed, and the labels listed and left unread. It forgets the cached |
| +// objects under prefix the listing no longer holds. |
| +func (r *engineReads) boxesUnder(ctx context.Context, store release.Store, prefix string, now time.Time) (boxes []status.Box, keys []string, listed, unread map[string]bool, err error) { |
| + keys, err = engineBoxKeyList(ctx, store, prefix, now) |
| + if err != nil { |
| + return nil, nil, nil, nil, err |
| + } |
| + r.forget(prefix, keys) |
| + listed, unread = map[string]bool{}, map[string]bool{} |
| for i, key := range keys { |
| - label := strings.TrimSuffix(strings.TrimPrefix(key, alertStatusBoxesPrefix), ".json") |
| + label := strings.TrimSuffix(strings.TrimPrefix(key, prefix), ".json") |
| if label == "" || !strings.HasSuffix(key, ".json") { |
| continue |
| } |
| - r.listedBoxes[label] = true |
| + listed[label] = true |
| if i >= engineBoxKeys { |
| - r.unreadBoxes[label] = true |
| + unread[label] = true |
| continue |
| } |
| body, _, err := r.get(ctx, store, key) |
| if err != nil { |
| alertReadFailed(ctx, fmt.Errorf("read %s: %w", key, err)) |
| - r.unreadBoxes[label] = true |
| + unread[label] = true |
| continue |
| } |
| var b status.Box |
| if len(body) > engineBoxBodyBytes { |
| alertReadFailed(ctx, fmt.Errorf("%s: body %d bytes exceeds %d", key, len(body), engineBoxBodyBytes)) |
| - r.unreadBoxes[label] = true |
| + unread[label] = true |
| continue |
| } |
| if err := json.Unmarshal(body, &b); err != nil { |
| alertReadFailed(ctx, fmt.Errorf("corrupt %s: %w", key, err)) |
| - r.unreadBoxes[label] = true |
| + unread[label] = true |
| continue |
| } |
| b.Label = label |
| boxes = append(boxes, b) |
| } |
| if len(keys) > engineBoxKeys { |
| - log.Printf("console: alert engine: %d keys under %s, reading the first %d", len(keys), alertStatusBoxesPrefix, engineBoxKeys) |
| + log.Printf("console: alert engine: %d keys under %s, reading the first %d", len(keys), prefix, engineBoxKeys) |
| } |
| - return boxes, nil |
| + return boxes, keys, listed, unread, nil |
| } |
| -// engineBoxKeyList is one listing of status/boxes/ without the objects not |
| +// engineBoxKeyList is one listing of prefix (a status/boxes/) without the objects not |
| // written within the horizon of now (the pass's clock), as status.LoadBoxes |
| // lists it. A store that cannot say when an object was written is listed |
| // whole, as is one whose listing with times answers errors.ErrUnsupported. |
| // A listing with times that fails returns its error and is not listed |
| // again plainly (ruling R-41). |
| -func engineBoxKeyList(ctx context.Context, store release.Store, now time.Time) ([]string, error) { |
| +func engineBoxKeyList(ctx context.Context, store release.Store, prefix string, now time.Time) ([]string, error) { |
| ml, ok := store.(release.ModLister) |
| if !ok { |
| - return store.List(ctx, alertStatusBoxesPrefix) |
| + return store.List(ctx, prefix) |
| } |
| - mods, err := ml.ListMod(ctx, alertStatusBoxesPrefix) |
| + mods, err := ml.ListMod(ctx, prefix) |
| if errors.Is(err, errors.ErrUnsupported) { |
| - return store.List(ctx, alertStatusBoxesPrefix) |
| + return store.List(ctx, prefix) |
| } |
| if err != nil { |
| return nil, err |
| @@ -378,15 +391,7 @@ func (s *Server) heartbeatSignals(ctx context.Context, settings map[string]alert |
| } else { |
| rows := s.activeStatusRows(ctx, boxes) |
| heartbeatBoxSignals(rows, r.unreadBoxes, settings, now, sig) |
| - // The switched apps are read only when some fresh box could fire: |
| - // with every box armed or hosting nothing, none can, and every box |
| - // is clear without a read. |
| - var switched map[string]bool |
| - partial := false |
| - if slices.ContainsFunc(rows, func(b status.Box) bool { return mailerCouldFire(b, now) }) { |
| - switched, partial = s.mailerSwitchedHosts(ctx, now) |
| - } |
| - mailerUnarmedSignals(rows, switched, partial, r.unreadBoxes, now, sig) |
| + s.mailerUnarmedPass(ctx, rows, now, sig) |
| } |
| if f, err := r.fleet(ctx, s.cfg.Releases); err != nil { |
| alertReadFailed(ctx, fmt.Errorf("read %s: %w", alertFleetKey, err)) |
| @@ -446,16 +451,86 @@ func heartbeatBoxSignals(boxes []status.Box, unread map[string]bool, settings ma |
| }) |
| } |
| +// mailerUnarmedPass reads the boxes the switch's door reads |
| +// (submissionBoxes: the platform's, and each account's own fleets') and |
| +// adds mailer_unarmed for them. The platform's are rows, read already. The |
| +// switched apps are read only when some box could fire: with no fleet, |
| +// and every platform box armed or hosting nothing, none can, and every box |
| +// is clear without a read. A fleet's boxes are read only while its account |
| +// has a switched app, or the switched set is partial; they are labelled |
| +// fleets/<name>/<label>. A registry that cannot be listed is logged, fails |
| +// the run, and keeps every open fleet box's incident as it is. |
| +func (s *Server) mailerUnarmedPass(ctx context.Context, rows []status.Box, now time.Time, sig *alertSignals) { |
| + r := &s.alertEngine.reads |
| + unread := maps.Clone(r.unreadBoxes) |
| + if unread == nil { |
| + unread = map[string]bool{} |
| + } |
| + var fleets []registry.Fleet |
| + fleetsRead := true |
| + if s.cfg.Registry != "" { |
| + reg, err := s.openPassRegistry() |
| + if err == nil { |
| + fleets, err = reg.ListFleets() |
| + } |
| + if err != nil { |
| + alertReadFailed(ctx, fmt.Errorf("list fleets for mailer_unarmed: %w", err)) |
| + fleetsRead = false |
| + } |
| + } |
| + var switched map[string]string |
| + partial := false |
| + if len(fleets) > 0 || slices.ContainsFunc(rows, func(b status.Box) bool { return mailerCouldFire(b, now) }) { |
| + switched, partial = s.mailerSwitchedHosts(ctx, now) |
| + } |
| + accts := map[string]bool{} |
| + for _, acct := range switched { |
| + accts[acct] = true |
| + } |
| + boxes, owner := slices.Clone(rows), map[string]string{} |
| + var fleetKeys []string |
| + for _, f := range fleets { |
| + if !partial && !accts[f.Account] { |
| + continue |
| + } |
| + prefix := "fleets/" + f.Name + "/" + alertStatusBoxesPrefix |
| + fb, keys, _, funread, err := r.boxesUnder(ctx, s.cfg.Releases, prefix, now) |
| + fleetKeys = append(fleetKeys, keys...) |
| + if err != nil { |
| + alertReadFailed(ctx, fmt.Errorf("list %s: %w", prefix, err)) |
| + fleetsRead = false |
| + continue |
| + } |
| + for _, b := range fb { |
| + b.Label = "fleets/" + f.Name + "/" + b.Label |
| + owner[b.Label] = f.Account |
| + boxes = append(boxes, b) |
| + } |
| + for label := range funread { |
| + unread["fleets/"+f.Name+"/"+label] = true |
| + } |
| + } |
| + if fleetsRead { |
| + r.forget("fleets/", fleetKeys) |
| + } |
| + mailerUnarmedSignals(boxes, owner, switched, partial, unread, now, sig) |
| + if !fleetsRead { |
| + sig.keepMissing["mailer_unarmed"] = true |
| + } |
| +} |
| + |
| // mailerUnarmedSignals adds mailer_unarmed for every fresh box (platform |
| // mail submission plan, gap G6 (b)): firing, value 1, while it reports a |
| -// route whose host is in switched (an app switched to mail submission) and |
| -// its mailer is not armed; clear, value 0, otherwise, so an open incident |
| -// clears on its own. A stale box adds nothing: box_silent covers it. A box |
| -// whose snapshot could not be read (unread) is unknown, not clear. With |
| -// partial set, switched is missing what could not be read: a box it does |
| -// not fire for is unknown too, unless its mailer is armed, which clears it |
| -// whatever the set holds. |
| -func mailerUnarmedSignals(boxes []status.Box, switched map[string]bool, partial bool, unread map[string]bool, now time.Time, sig *alertSignals) { |
| +// route, installed or serving, whose host is in switched (an app switched |
| +// to mail submission, by its account) and its mailer is not armed; clear, |
| +// value 0, otherwise, so an open incident clears on its own. A fleet's box |
| +// (in owner, with its fleet's account) fires only for its own account's |
| +// apps, as the door reads it. A stale box adds nothing: box_silent covers |
| +// it. A box whose snapshot could not be read (unread) is unknown, not |
| +// clear. With partial set, switched is missing what could not be read: a |
| +// box it does not fire for is unknown too, unless its mailer is armed, |
| +// which clears it whatever the set holds. |
| +func mailerUnarmedSignals(boxes []status.Box, owner, switched map[string]string, partial bool, unread map[string]bool, now time.Time, sig *alertSignals) { |
| unknown := maps.Clone(unread) |
| if unknown == nil { |
| unknown = map[string]bool{} |
| @@ -466,12 +541,16 @@ func mailerUnarmedSignals(boxes []status.Box, switched map[string]bool, partial |
| } |
| firing := false |
| if mailerCouldFire(b, now) { |
| - for host := range b.Metrics.RouteVersions { |
| - if switched[host] { |
| - firing = true |
| - break |
| + own, fleet := owner[b.Label] |
| + reports := func(routes map[string]string) bool { |
| + for host := range routes { |
| + if acct, ok := switched[host]; ok && (!fleet || own == acct) { |
| + return true |
| + } |
| } |
| + return false |
| } |
| + firing = reports(b.Metrics.RouteVersions) || reports(b.Metrics.RouteServing) |
| if !firing && partial { |
| unknown[b.Label] = true |
| continue |
| @@ -492,7 +571,7 @@ func mailerUnarmedSignals(boxes []status.Box, switched map[string]bool, partial |
| // routes is a switched app's. |
| func mailerCouldFire(b status.Box, now time.Time) bool { |
| return !status.BoxStale(b, now, status.SnapshotPeriod) && b.Metrics != nil && !b.Metrics.MailerArmed && |
| - len(b.Metrics.RouteVersions) > 0 |
| + (len(b.Metrics.RouteVersions) > 0 || len(b.Metrics.RouteServing) > 0) |
| } |
| // engineAbsentRecheck is how long an app with no sender object goes |
| @@ -509,7 +588,7 @@ const engineAbsentRecheck = time.Hour |
| const engineSwitchedRecordKeys = 1000 |
| // mailerSwitchedHosts is every host an instance record of an app switched |
| -// to mail submission names: an app whose sender |
| +// to mail submission names, with the app's account sqid: an app whose sender |
| // apps/<acct>/<app>/email/senders/app.json has submission.on. The apps are |
| // the console's own rows, trashed ones included (their routes may still |
| // run); an app with no sender object is not switched, and its sender is |
| @@ -518,7 +597,7 @@ const engineSwitchedRecordKeys = 1000 |
| // object costs a 304; the records are listed, one LIST a switched app. A |
| // read that fails is logged, fails the run, and leaves the set partial, so |
| // no box goes clear on it. |
| -func (s *Server) mailerSwitchedHosts(ctx context.Context, now time.Time) (hosts map[string]bool, partial bool) { |
| +func (s *Server) mailerSwitchedHosts(ctx context.Context, now time.Time) (hosts map[string]string, partial bool) { |
| r := &s.alertEngine.reads |
| apps, err := s.store.alertMailApps(ctx) |
| if err != nil { |
| @@ -527,7 +606,7 @@ func (s *Server) mailerSwitchedHosts(ctx context.Context, now time.Time) (hosts |
| } |
| absent := r.senderAbsent |
| r.senderAbsent = map[string]time.Time{} |
| - hosts = map[string]bool{} |
| + hosts = map[string]string{} |
| var read []string |
| for _, a := range apps { |
| key := mailwire.SenderKey(a.Sqid, a.App, mailwire.SenderAppID) |
| @@ -569,7 +648,7 @@ func (s *Server) mailerSwitchedHosts(ctx context.Context, now time.Time) (hosts |
| // acct/app, reading each through the cache. keys is every record key read; |
| // whole is false when the listing, a record or the cap left some out. A |
| // record gone since the listing is a route gone, not a failure. |
| -func (r *engineReads) switchedRecordHosts(ctx context.Context, store release.Store, acct, app string, hosts map[string]bool) (keys []string, whole bool) { |
| +func (r *engineReads) switchedRecordHosts(ctx context.Context, store release.Store, acct, app string, hosts map[string]string) (keys []string, whole bool) { |
| prefix := provision.RecordsPrefix(acct, app) |
| listed, err := store.List(ctx, prefix) |
| if err != nil { |
| @@ -602,7 +681,7 @@ func (r *engineReads) switchedRecordHosts(ctx context.Context, store release.Sto |
| whole = false |
| continue |
| } |
| - hosts[rec.Host] = true |
| + hosts[rec.Host] = acct |
| } |
| return keys, whole |
| } |
diff --git a/internal/console/apisubmission.go b/internal/console/apisubmission.go| index c92776ac7..9501a2ee7 100644 |
| --- a/internal/console/apisubmission.go |
| +++ b/internal/console/apisubmission.go |
| @@ -15,15 +15,20 @@ package console |
| import ( |
| "context" |
| + "encoding/json" |
| "errors" |
| "fmt" |
| "log" |
| "net/http" |
| + "os" |
| "slices" |
| "sort" |
| + "strings" |
| + "sync" |
| "time" |
| "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" |
| @@ -169,37 +174,40 @@ func (s *Server) submissionPreconditions(ctx context.Context, acct, app string, |
| return conflict(fmt.Sprintf(submissionCopy.PrefixNotSMTP, sn.Declared.EnvPrefix)) |
| } |
| - // 1b. The deployment can count and cap what the mailer sends: an SES |
| - // event destination, and a configuration set on every granted domain |
| - // in the mail region (the mailer refuses a domain with none). |
| + // 1b. The deployment can count and cap what the mailer sends (an SES |
| + // event destination), and the mailer would send from the app's declared |
| + // From: the mailer's own rule, mailwire.CheckFromDomain (review P3), on |
| + // the domain record as the mailer reads it. |
| region := s.cfg.MailDeployment.Region |
| if s.cfg.MailDeployment.SNSTopicARN == "" { |
| return conflict(submissionCopy.NoEventIngest) |
| } |
| - var identities, configSets []string |
| + from := sn.Declared.From |
| + domain := strings.ToLower(from[strings.LastIndexByte(from, '@')+1:]) |
| + var granted []string |
| if sn.Grant != nil { |
| - for _, d := range sn.Grant.Domains { |
| - dom, _, err := mail.GetDomain(ctx, s.cfg.Releases, acct, d) |
| - if err != nil { |
| - log.Printf("console: email submission %s/%s: domain %s: %v", acct, app, d, err) |
| - return &doorRefusal{Status: http.StatusBadGateway, Msg: submissionCopy.SwitchFailed} |
| - } |
| - if dom == nil { |
| - continue |
| - } |
| - st := dom.Regions[region] |
| - if st == nil || st.Status != mail.StatusVerified { |
| - continue |
| - } |
| - if st.ConfigSet == "" { |
| - return conflict(fmt.Sprintf(submissionCopy.DomainNoConfigSet, d, region)) |
| - } |
| - identities = append(identities, st.IdentityARN) |
| - if arn, ok := mail.ConfigSetARN(st.IdentityARN, st.ConfigSet); ok { |
| - configSets = append(configSets, arn) |
| - } |
| - } |
| + granted = sn.Grant.Domains |
| + } |
| + dv, err := s.submissionDomainView(ctx, acct, domain) |
| + if err != nil { |
| + log.Printf("console: email submission %s/%s: domain %s: %v", acct, app, domain, err) |
| + return &doorRefusal{Status: http.StatusBadGateway, Msg: submissionCopy.SwitchFailed} |
| } |
| + switch mailwire.CheckFromDomain(granted, domain, app, region, dv) { |
| + case mailwire.FromSendable: |
| + case mailwire.FromNoConfigSet: |
| + return conflict(fmt.Sprintf(submissionCopy.DomainNoConfigSet, domain, region)) |
| + default: |
| + return conflict(fmt.Sprintf(submissionCopy.FromNotSendable, from, domain, region)) |
| + } |
| + st := dv.Regions[region] |
| + csARN, ok := mail.ConfigSetARN(st.IdentityARN, st.ConfigSet) |
| + if !ok { |
| + // A set the door cannot name is a set the tenant check cannot |
| + // confirm (review P3): refuse rather than drop it. |
| + return conflict(fmt.Sprintf(submissionCopy.ConfigSetUnbuildable, domain)) |
| + } |
| + identities, configSets := []string{st.IdentityARN}, []string{csARN} |
| // 2. Every route runs a build that declares the transport, read from |
| // the boxes' fresh reports; a route no fresh box reports is refused, |
| @@ -406,7 +414,10 @@ func (s *Server) reapSubmittedAppUsers(ctx context.Context, acct *Account, now t |
| if !mail.Switched(sn) || sn.Provisioned == nil { |
| continue |
| } |
| - reaped, err := mail.ReapAppUserAfterSubmission(ctx, s.claimMailStore(), s.cfg.MailProvisioner, acct.Sqid, app, func(a, b, day string) (map[string]int64, error) { return s.store.MailCallerSends(ctx, a, b, day) }, now) |
| + counts := func(a, b, day string) (map[string]int64, error) { |
| + return s.mailCallerCounts(ctx, a, b, day, s.store.RecordMailCallerSend) |
| + } |
| + reaped, err := mail.ReapAppUserAfterSubmission(ctx, s.claimMailStore(), s.cfg.MailProvisioner, acct.Sqid, app, counts, now) |
| if err != nil { |
| errs = append(errs, fmt.Errorf("%s: %w", app, err)) |
| continue |
| @@ -427,3 +438,76 @@ func (s *Server) reapSubmittedAppUsers(ctx context.Context, acct *Account, now t |
| type tenantResourceLister interface { |
| ListTenantResources(ctx context.Context, tenant string) ([]string, error) |
| } |
| + |
| +// mailCallerGapSet is the caller-class sends the console failed to record |
| +// (review P3): a day of an app whose Send could not be counted. The reap |
| +// reads such a day as unclean. A gap is kept here until a write succeeds, |
| +// then written as an "unrecorded" row of mail_caller_sends, so it outlives |
| +// a restart from then on; until it is written, the reap's counts refuse. |
| +// A gap only in memory is lost if the console restarts before the store |
| +// recovers: the window in which the reap could miss it is that outage. |
| +type mailCallerGapSet struct { |
| + mu sync.Mutex |
| + gaps map[[3]string]bool // account, app, day |
| +} |
| + |
| +func (g *mailCallerGapSet) note(acct, app, day string) { |
| + g.mu.Lock() |
| + defer g.mu.Unlock() |
| + if g.gaps == nil { |
| + g.gaps = map[[3]string]bool{} |
| + } |
| + g.gaps[[3]string{acct, app, day}] = true |
| +} |
| + |
| +// flush writes every pending gap as an unrecorded row, keeping those whose |
| +// write fails. |
| +func (g *mailCallerGapSet) flush(ctx context.Context, record func(ctx context.Context, acct, app, day, class string) error) { |
| + g.mu.Lock() |
| + defer g.mu.Unlock() |
| + for k := range g.gaps { |
| + if err := record(ctx, k[0], k[1], k[2], mail.CallerClassUnrecorded); err == nil { |
| + delete(g.gaps, k) |
| + } |
| + } |
| +} |
| + |
| +// pending reports a gap of acct/app on or after sinceDay not yet written. |
| +func (g *mailCallerGapSet) pending(acct, app, sinceDay string) bool { |
| + g.mu.Lock() |
| + defer g.mu.Unlock() |
| + for k := range g.gaps { |
| + if k[0] == acct && k[1] == app && k[2] >= sinceDay { |
| + return true |
| + } |
| + } |
| + return false |
| +} |
| + |
| +// mailCallerCounts is the reap's read of acct/app's caller-class sends |
| +// since day: the gaps are written first, through record, and a gap still |
| +// unwritten refuses the read, so the reap waits. |
| +func (s *Server) mailCallerCounts(ctx context.Context, acct, app, day string, record func(ctx context.Context, acct, app, day, class string) error) (map[string]int64, error) { |
| + s.mailCallerGaps.flush(ctx, record) |
| + if s.mailCallerGaps.pending(acct, app, day) { |
| + return nil, fmt.Errorf("a send for %s/%s since %s could not be recorded yet", acct, app, day) |
| + } |
| + return s.store.MailCallerSends(ctx, acct, app, day) |
| +} |
| + |
| +// 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) { |
| + body, _, err := s.cfg.Releases.Get(ctx, mailwire.DomainKey(acct, domain)) |
| + if errors.Is(err, os.ErrNotExist) { |
| + return nil, nil |
| + } |
| + if err != nil { |
| + return nil, err |
| + } |
| + var dv mailwire.DomainView |
| + if err := json.Unmarshal(body, &dv); err != nil { |
| + return nil, err |
| + } |
| + return &dv, nil |
| +} |
diff --git a/internal/console/apisubmission_test.go b/internal/console/apisubmission_test.go| index b6dded7c3..2841e3c9f 100644 |
| --- a/internal/console/apisubmission_test.go |
| +++ b/internal/console/apisubmission_test.go |
| @@ -363,3 +363,149 @@ func readSerialForTest(t *testing.T, fx *consoleFixture) int64 { |
| } |
| return doc.Serial |
| } |
| + |
| +// Review P3: a caller-class send the console failed to record holds the |
| +// reap. The gap is pending in memory (the reap's counts refuse), and once |
| +// a write succeeds it is written as an "unrecorded" row the reap reads. |
| +func TestMailCallerGapHoldsTheReap(t *testing.T) { |
| + fx := newConsoleFixture(t) |
| + st := fx.st |
| + ctx := context.Background() |
| + if _, err := st.CreateAppIn(OpsAccountID, "titogo", "bill@tito.io", time.Now().AddDate(0, 0, -30)); err != nil { |
| + t.Fatal(err) |
| + } |
| + var g mailCallerGapSet |
| + g.note(release.OpsAccount, "titogo", "2026-11-10") |
| + if !g.pending(release.OpsAccount, "titogo", "2026-11-06") || g.pending(release.OpsAccount, "titogo", "2026-11-11") || g.pending(release.OpsAccount, "other", "2026-11-01") { |
| + t.Fatal("pending does not follow the gap's app and day") |
| + } |
| + fail := func(context.Context, string, string, string, string) error { return fmt.Errorf("db down") } |
| + g.flush(ctx, fail) |
| + if !g.pending(release.OpsAccount, "titogo", "2026-11-06") { |
| + t.Fatal("a failed flush dropped the gap") |
| + } |
| + g.flush(ctx, st.RecordMailCallerSend) |
| + if g.pending(release.OpsAccount, "titogo", "2026-11-06") { |
| + t.Fatal("a successful flush kept the gap") |
| + } |
| + got, err := st.MailCallerSends(ctx, release.OpsAccount, "titogo", "2026-11-06") |
| + if err != nil || got[mail.CallerClassUnrecorded] != 1 { |
| + t.Fatalf("the gap was not written as an unrecorded row: %v %v", got, err) |
| + } |
| + |
| + // The reap's read: a gap the store still refuses holds it; once |
| + // written, the read answers, unrecorded row and all. |
| + fx.srv.mailCallerGaps.note(release.OpsAccount, "titogo", "2026-11-12") |
| + if _, err := fx.srv.mailCallerCounts(ctx, release.OpsAccount, "titogo", "2026-11-06", fail); err == nil { |
| + t.Fatal("the reap read counts past a gap not yet written") |
| + } |
| + got, err = fx.srv.mailCallerCounts(ctx, release.OpsAccount, "titogo", "2026-11-06", st.RecordMailCallerSend) |
| + if err != nil || got[mail.CallerClassUnrecorded] != 2 { |
| + t.Fatalf("after the write: %v %v, want two unrecorded days", got, err) |
| + } |
| +} |
| + |
| +// Review P3, three gates with no test before: the door's 409 for an app |
| +// declared but not enabled, the From domain by the mailer's own rule (no |
| +// configuration set; a record that does not list the app), and the serve |
| +// gate's read of the switch, which fails closed. |
| +func TestSubmissionDoorMoreRefusals(t *testing.T) { |
| + w := newSubmissionWorld(t, "code-submission-more") |
| + w.promote(t, "v2") |
| + w.box(t, "box-1", "v2", true) |
| + refused := func(name, want string) { |
| + t.Helper() |
| + status, out := w.submit(t, true) |
| + if status != http.StatusConflict || !strings.Contains(out, want) { |
| + t.Fatalf("%s: %d %s, want 409 containing %q", name, status, out, want) |
| + } |
| + } |
| + // Not enabled: declared, no provisioned block, not switched. |
| + var saved any |
| + setSenderField(t, w, func(raw map[string]any) { saved = raw["provisioned"]; delete(raw, "provisioned") }) |
| + refused("declared but not enabled", "Email is not enabled for this app") |
| + setSenderField(t, w, func(raw map[string]any) { raw["provisioned"] = saved }) |
| + |
| + // The From domain as the mailer reads it. |
| + ctx := context.Background() |
| + key := mailwire.DomainKey("bab", "titogo.bab.oncarlos.com") |
| + body, etag, err := w.fx.rel.Get(ctx, key) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + edit := func(f func(map[string]any)) { |
| + t.Helper() |
| + var raw map[string]any |
| + _ = json.Unmarshal(body, &raw) |
| + f(raw) |
| + out, _ := json.Marshal(raw) |
| + if etag, err = w.fx.rel.Put(ctx, key, out, etag); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + edit(func(raw map[string]any) { |
| + raw["regions"].(map[string]any)["eu-west-1"].(map[string]any)["config_set"] = "" |
| + }) |
| + refused("no configuration set", "has no configuration set in eu-west-1") |
| + edit(func(raw map[string]any) { |
| + r := raw["regions"].(map[string]any)["eu-west-1"].(map[string]any) |
| + r["config_set"], r["identity_arn"] = "carlos-titogo", "not-an-arn" |
| + }) |
| + refused("an identity ARN no set can be named from", "Can't name the configuration set") |
| + edit(func(raw map[string]any) { raw["apps"] = []string{"sheets"} }) |
| + refused("a domain record that does not list the app", "the box's mailer would refuse it") |
| + edit(func(map[string]any) {}) |
| + if status, out := w.submit(t, true); status != http.StatusOK { |
| + t.Fatalf("restored: %d %s", status, out) |
| + } |
| + |
| + // 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 { |
| + t.Fatalf("switched, undeclared v1: %+v", ref) |
| + } |
| + if ref := w.fx.srv.submissionBuildRefusal(ctx, "bab", "titogo", "v-missing"); ref == nil || ref.Status != http.StatusBadGateway { |
| + t.Fatalf("switched, unreadable manifest: %+v, want 502", ref) |
| + } |
| + sk := mailwire.SenderKey("bab", "titogo", mailwire.SenderAppID) |
| + _, setag, _ := w.fx.rel.Get(ctx, sk) |
| + 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 { |
| + t.Fatalf("unreadable sender: %+v, want 502", ref) |
| + } |
| +} |
| + |
| +// TestReapWaitsOnAnUnrecordedSend (Task 6 review P3): the console's reap |
| +// reads the caller-class counts through the gap set, so a send the console |
| +// could not count holds it, as an unrecorded day, until that day leaves |
| +// the window; with no gap, the same app is reaped. |
| +func TestReapWaitsOnAnUnrecordedSend(t *testing.T) { |
| + for _, gap := range []bool{true, false} { |
| + w := newSubmissionWorld(t, fmt.Sprintf("code-submission-reap-%v", gap)) |
| + w.promote(t, "v2") |
| + w.box(t, "box-1", "v2", true) |
| + if status, out := w.submit(t, true); status != http.StatusOK { |
| + t.Fatalf("switch on: %d %s", status, out) |
| + } |
| + ctx := context.Background() |
| + now := time.Now().UTC().AddDate(0, 0, 8) |
| + if err := w.fx.st.RecordMailCallerSend(ctx, "bab", "titogo", now.AddDate(0, 0, -1).Format("2006-01-02"), mail.CallerClassMailer); err != nil { |
| + t.Fatal(err) |
| + } |
| + if gap { |
| + w.fx.srv.mailCallerGaps.note("bab", "titogo", now.AddDate(0, 0, -2).Format("2006-01-02")) |
| + } |
| + if err := w.fx.srv.reapSubmittedAppUsers(ctx, w.fx.account(t), now); err != nil { |
| + t.Fatalf("gap %v: reap: %v", gap, err) |
| + } |
| + sn, _, err := mail.GetSender(ctx, w.fx.rel, "bab", "titogo", mail.SenderAppID) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if reaped := sn.Provisioned == nil; reaped == gap { |
| + t.Fatalf("gap %v: reaped %v", gap, reaped) |
| + } |
| + } |
| +} |
diff --git a/internal/console/mailcounts.go b/internal/console/mailcounts.go| index 109e422ef..a5a1dd59d 100644 |
| --- a/internal/console/mailcounts.go |
| +++ b/internal/console/mailcounts.go |
| @@ -134,7 +134,7 @@ ON CONFLICT(account, app, sender, day) DO UPDATE SET %s = %s + 1`, col, col, col |
| // takes it as given and validates only that it is one of the three. |
| func (s *Store) RecordMailCallerSend(ctx context.Context, acct, app, day, class string) error { |
| switch class { |
| - case mail.CallerClassMailer, mail.CallerClassAppUser, mail.CallerClassOther: |
| + case mail.CallerClassMailer, mail.CallerClassAppUser, mail.CallerClassOther, mail.CallerClassUnrecorded: |
| default: |
| return fmt.Errorf("console: unknown mail caller class %q", class) |
| } |
diff --git a/internal/console/server.go b/internal/console/server.go| index 8b0006d7f..0a22b379a 100644 |
| --- a/internal/console/server.go |
| +++ b/internal/console/server.go |
| @@ -1015,6 +1015,8 @@ type Config struct { |
| // Server is the console's http.Handler. |
| type Server struct { |
| + // mailCallerGaps holds caller-class sends not yet recorded (apisubmission.go). |
| + mailCallerGaps mailCallerGapSet |
| sourceDownloads sourceDownloads |
| haPools map[string][]string |
| haScopeInvalid bool |
diff --git a/internal/console/sesevents.go b/internal/console/sesevents.go| index b808a9359..9b0edd1cf 100644 |
| --- a/internal/console/sesevents.go |
| +++ b/internal/console/sesevents.go |
| @@ -548,6 +548,10 @@ func (s *Server) recordAndEnforceMail(ctx context.Context, ev mail.Event, notice |
| class := mail.CallerClass(callerAcct, callerApp, ev.Caller) |
| if err := s.store.RecordMailCallerSend(ctx, callerAcct, callerApp, day, class); err != nil { |
| log.Printf("console: ses events: recording a %s send for %s/%s -> %v", class, callerAcct, callerApp, err) |
| + // The reap must not read this day as clean (review P3). |
| + s.mailCallerGaps.note(callerAcct, callerApp, day) |
| + } else { |
| + s.mailCallerGaps.flush(ctx, s.store.RecordMailCallerSend) |
| } |
| } |
| if err := s.store.RecordMailEvent(ctx, callerAcct, callerApp, callerSender, day, ev.Type); err != nil { |
diff --git a/internal/console/submissioncopy.go b/internal/console/submissioncopy.go| index 8795fa337..75e239e03 100644 |
| --- a/internal/console/submissioncopy.go |
| +++ b/internal/console/submissioncopy.go |
| @@ -8,6 +8,7 @@ package console |
| // TestApprovedPlatformMailSubmissionCopy pins each one here. |
| var submissionCopy = struct { |
| NotDeclared, NotEnabled, PrefixNotSMTP, NoEventIngest, DomainNoConfigSet string |
| + FromNotSendable, ConfigSetUnbuildable string |
| RouteUnreported, RouteUndeclared, RoutesUnreadable string |
| ChannelUndeclared, ChannelUnreadable string |
| TenantUnassociated, TenantUnconfirmed string |
| @@ -21,6 +22,9 @@ var submissionCopy = struct { |
| NoEventIngest: "This deployment has no SES event destination, so mail sent through the box couldn't be counted or capped. Submission needs event ingest.", |
| DomainNoConfigSet: "Sending domain %s has no configuration set in %s, so its mail couldn't be counted or capped. Submission needs one.", |
| + FromNotSendable: "This app sends as %s, and the box's mailer would refuse it: %s must be granted to the app, list the app and be verified in %s. Run carlos email enable for the app again.", |
| + ConfigSetUnbuildable: "Can't name the configuration set of %s from its identity, so its tenant can't be checked. Run carlos email domains add for it again.", |
| + |
| RouteUnreported: "Can't confirm instance %s: no box has reported it recently. Wait for it to report, or check it is running.", |
| 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.", |
diff --git a/internal/mail/sender.go b/internal/mail/sender.go| index a145062a3..2cda3f708 100644 |
| --- a/internal/mail/sender.go |
| +++ b/internal/mail/sender.go |
| @@ -575,6 +575,11 @@ const ( |
| CallerClassMailer = "mailer" |
| CallerClassAppUser = "app_user" |
| CallerClassOther = "other" |
| + // CallerClassUnrecorded marks a day on which a Send's class could not |
| + // be recorded (the console's write failed and was retried as this |
| + // mark). It is not a caller: the switch's reap waits while one falls in |
| + // its window, since the lost send may have been the app-level key's. |
| + CallerClassUnrecorded = "unrecorded" |
| ) |
| // CallerClass classifies the IAM identity that sent a message, for the app |
diff --git a/internal/mail/submission.go b/internal/mail/submission.go| index 1e9051343..1f4c19c39 100644 |
| --- a/internal/mail/submission.go |
| +++ b/internal/mail/submission.go |
| @@ -252,8 +252,13 @@ func claimUnserializedSwitchOn(ctx context.Context, s release.Store, p Provision |
| return nil, err |
| } |
| if !rec.switched() { |
| + // The reap mark is history only while the user it records is still |
| + // gone. A switch-off re-mints the app-level user, so a new switch-on |
| + // that finds one starts a new overlap week, and that user must be |
| + // reaped in its turn (review P2-5): carrying the old mark would |
| + // make the reap skip it for ever. |
| var reapedAt *time.Time |
| - if sub := rec.submission(); sub != nil { |
| + if sub := rec.submission(); sub != nil && rec.Provisioned == nil { |
| reapedAt = sub.AppUserReapedAt |
| } |
| rec.setSubmission(&mailwire.Submission{On: true, At: now, By: actor, AppUserReapedAt: reapedAt}) |
diff --git a/internal/mail/submission_test.go b/internal/mail/submission_test.go| index 63de59da1..abc6ccc59 100644 |
| --- a/internal/mail/submission_test.go |
| +++ b/internal/mail/submission_test.go |
| @@ -11,6 +11,7 @@ import ( |
| "context" |
| "errors" |
| "sort" |
| + "strconv" |
| "strings" |
| "testing" |
| "time" |
| @@ -492,6 +493,10 @@ func TestReapAppUserAfterSubmission(t *testing.T) { |
| days: func(t0 time.Time) map[string]map[string]int64 { |
| return map[string]map[string]int64{day(t0, 0): {CallerClassMailer: 5}} |
| }}, |
| + {name: "a day whose sends were not all recorded", after: 8 * 24 * time.Hour, |
| + days: func(t0 time.Time) map[string]map[string]int64 { |
| + return map[string]map[string]int64{day(t0, 0): {CallerClassMailer: 5}, day(t0, 4): {CallerClassUnrecorded: 1}} |
| + }}, |
| {name: "renamed user", after: 8 * 24 * time.Hour, rename: true, |
| days: func(t0 time.Time) map[string]map[string]int64 { |
| return map[string]map[string]int64{day(t0, 0): {CallerClassMailer: 5}} |
| @@ -565,3 +570,86 @@ func TestReapAppUserAfterSubmission(t *testing.T) { |
| t.Fatalf("reap of an unswitched app = %v, %v", got, err) |
| } |
| } |
| + |
| +// Review P2-5: on, reap, off, on again, then a month later. The second |
| +// switch-on found a re-minted app-level user, so it starts a new overlap |
| +// week with no reap mark, and that user is reaped in its turn. |
| +func TestReapAgainAfterSwitchOffAndOn(t *testing.T) { |
| + ctx, s, mem, seal, t0 := switchFixture(t) |
| + mailer := func(t0 time.Time) map[string]map[string]int64 { |
| + return map[string]map[string]int64{utcDay(t0): {CallerClassMailer: 3}} |
| + } |
| + if _, err := SwitchOn(ctx, s, mem, subAcct, subApp, []string{"team"}, "o", t0); err != nil { |
| + t.Fatal(err) |
| + } |
| + reap1 := t0.Add(8 * 24 * time.Hour) |
| + if ok, err := ReapAppUserAfterSubmission(ctx, s, mem, subAcct, subApp, fakeCounts(mailer(t0), nil), reap1); !ok || err != nil { |
| + t.Fatalf("first reap = %v, %v", ok, err) |
| + } |
| + off := reap1.Add(time.Hour) |
| + if _, err := SwitchOff(ctx, s, mem, seal, testDeployment(), subAcct, subApp, []string{"team"}, "o", off); err != nil { |
| + t.Fatal(err) |
| + } |
| + on2 := off.Add(time.Hour) |
| + if _, err := SwitchOn(ctx, s, mem, subAcct, subApp, []string{"team"}, "o", on2); err != nil { |
| + t.Fatal(err) |
| + } |
| + sn, _, _ := GetSender(ctx, s, subAcct, subApp, SenderAppID) |
| + if sn.Submission.AppUserReapedAt != nil { |
| + t.Fatalf("the second switch carried the first reap mark: %v", sn.Submission.AppUserReapedAt) |
| + } |
| + if _, ok := mem.Users[UserName(subAcct, subApp)]; !ok { |
| + t.Fatal("switch-off did not re-mint the app-level user") |
| + } |
| + later := on2.Add(30 * 24 * time.Hour) |
| + if ok, err := ReapAppUserAfterSubmission(ctx, s, mem, subAcct, subApp, fakeCounts(mailer(on2), nil), later); !ok || err != nil { |
| + t.Fatalf("the re-minted user was not reaped after the second switch: %v, %v", ok, err) |
| + } |
| + if _, ok := mem.Users[UserName(subAcct, subApp)]; ok { |
| + t.Fatal("the re-minted app-level user survived") |
| + } |
| +} |
| + |
| +// Review P3s: while switched the env prefix stays locked even once the |
| +// app-level user is reaped, and Enable delivers a re-declared From to the |
| +// default bundle (before and after the reap). |
| +func TestSwitchedDeclareAndEnable(t *testing.T) { |
| + ctx, s, mem, seal, t0 := switchFixture(t) |
| + if _, err := SwitchOn(ctx, s, mem, subAcct, subApp, []string{"team"}, "o", t0); err != nil { |
| + t.Fatal(err) |
| + } |
| + rec, _, _ := Get(ctx, s, subAcct, subApp) |
| + prefix := rec.Declared.EnvPrefix |
| + mf, _ := MailFromName(prefix) |
| + at := rec.Declared.From[strings.LastIndex(rec.Declared.From, "@"):] |
| + check := func(want string) { |
| + t.Helper() |
| + m, err := appconfig.Get(ctx, s, subAcct, subApp) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if got := m.Vars[mf].Value; got != want { |
| + t.Fatalf("default bundle %s = %q, want %q", mf, got, want) |
| + } |
| + } |
| + for i, phase := range []string{"overlap week", "after the reap"} { |
| + if i == 1 { |
| + ok, err := ReapAppUserAfterSubmission(ctx, s, mem, subAcct, subApp, |
| + fakeCounts(map[string]map[string]int64{utcDay(t0): {CallerClassMailer: 1}}, nil), t0.Add(8*24*time.Hour)) |
| + if !ok || err != nil { |
| + t.Fatalf("reap = %v, %v", ok, err) |
| + } |
| + } |
| + from := "new" + strconv.Itoa(i) + at |
| + if _, err := Declare(ctx, s, subAcct, subApp, prefix, from, "o", t0); err != nil { |
| + t.Fatalf("%s: re-declare: %v", phase, err) |
| + } |
| + if _, err := Enable(ctx, s, mem, seal, testDeployment(), subAcct, subApp, t0); err != nil { |
| + t.Fatalf("%s: enable: %v", phase, err) |
| + } |
| + check(from) |
| + if _, err := Declare(ctx, s, subAcct, subApp, "OTHER_SMTP", from, "o", t0); err == nil { |
| + t.Fatalf("%s: the prefix moved while switched", phase) |
| + } |
| + } |
| +} |
diff --git a/internal/mail/sweep.go b/internal/mail/sweep.go| index 274de8fc4..322cd476b 100644 |
| --- a/internal/mail/sweep.go |
| +++ b/internal/mail/sweep.go |
| @@ -148,7 +148,9 @@ func claimUnserializedReapAppUserAfterSubmission(ctx context.Context, s release. |
| if err != nil { |
| return false, fmt.Errorf("mail: %s/%s: read caller-class sends: %w", acct, app, err) |
| } |
| - if recent[CallerClassAppUser] != 0 { |
| + // A day whose send classes were not all recorded (review P3) might |
| + // hide an app-level send: wait until it leaves the window. |
| + if recent[CallerClassAppUser] != 0 || recent[CallerClassUnrecorded] != 0 { |
| return false, nil |
| } |
| if err := p.ReapKeys(ctx, user, nil); err != nil { |
diff --git a/internal/mail/walk.go b/internal/mail/walk.go| index 9546f4df2..2e8e7bb30 100644 |
| --- a/internal/mail/walk.go |
| +++ b/internal/mail/walk.go |
| @@ -639,7 +639,10 @@ func claimUnserializedDeclare(ctx context.Context, s release.Store, acct, app, e |
| // The env prefix is LOCKED once delivery has happened: moving it would |
| // leave the old variables standing in every instance's config, and the |
| // app would keep reading the stale pair. |
| - if rec.Declared != nil && rec.Provisioned != nil && rec.Declared.EnvPrefix != envPrefix { |
| + // A switched app counts as delivered too (review P3): its bundles hold |
| + // <stem>_MAIL_FROM, named from this prefix, even once the app-level |
| + // user is reaped and Provisioned is gone. |
| + if rec.Declared != nil && (rec.Provisioned != nil || rec.switched()) && rec.Declared.EnvPrefix != envPrefix { |
| return nil, fmt.Errorf("mail: env prefix is %q and cannot move after delivery", |
| rec.Declared.EnvPrefix) |
| } |
| @@ -773,6 +776,10 @@ func claimUnserializedEnable(ctx context.Context, s release.Store, p Provisioner |
| // user is reaped there is nothing to refresh either, and no provisioner |
| // call is made. |
| if rec.switched() && rec.Provisioned == nil { |
| + // The From may have been re-declared: deliver it (review P3). |
| + if err := writeMailFromIn(ctx, s, acct, app, "", rec.Declared.EnvPrefix, rec.Declared.From); err != nil { |
| + return nil, err |
| + } |
| return rec, nil |
| } |
| @@ -834,6 +841,11 @@ func claimUnserializedEnable(ctx context.Context, s release.Store, p Provisioner |
| // the policy refresh above still runs, and nothing is minted or |
| // delivered. SwitchOff turns the switch off before it calls this walk. |
| if rec.switched() { |
| + // The one thing a switched app is delivered: its From, which a |
| + // re-declare may have changed (review P3). |
| + if err := writeMailFromIn(ctx, s, acct, app, "", rec.Declared.EnvPrefix, rec.Declared.From); err != nil { |
| + return nil, err |
| + } |
| return rec, nil |
| } |
diff --git a/internal/mailer/policy.go b/internal/mailer/policy.go| index 65c2a1aa9..e1ee018c2 100644 |
| --- a/internal/mailer/policy.go |
| +++ b/internal/mailer/policy.go |
| @@ -160,35 +160,36 @@ func (m *Mailer) admit(ctx context.Context, req mailsubmit.SendRequest) decision |
| return refuse(http.StatusBadRequest, mailsubmit.CodeBadRequest) |
| } |
| - // 5. The From domain, granted and verified in the mail region. |
| + // 5. The From domain, by the one rule (mailwire.CheckFromDomain): granted, |
| + // its record lists the app, verified with an identity and a |
| + // configuration set in the mail region. Every send names a |
| + // configuration set (§9.0: an absent parameter lets a header choose one, |
| + // and the set carries the events that count and attribute the send); a |
| + // verified identity has none only on a deployment with no SNS topic, |
| + // where a send through the account's set fails outright, so it is |
| + // refused (review round 1, Task 5 P1-1). |
| at := strings.LastIndexByte(from, '@') |
| domain := strings.ToLower(from[at+1:]) |
| - if sender.Grant == nil || !slices.Contains(sender.Grant.Domains, domain) { |
| - return refuse(http.StatusForbidden, mailsubmit.CodeFromNotAllowed) |
| - } |
| - dv, err := m.domain(ctx, req.Account, domain, now) |
| - if err != nil { |
| - m.logf("mailer: domain %s/%s: %v", req.Account, domain, err) |
| - return unavailable |
| - } |
| - if dv == nil || !slices.Contains(dv.Apps, req.App) { |
| - return refuse(http.StatusForbidden, mailsubmit.CodeFromNotAllowed) |
| - } |
| - region := dv.Regions[m.mailRegion] |
| - if region == nil || region.Status != mailwire.DomainStatusVerified || region.IdentityARN == "" { |
| - return refuse(http.StatusForbidden, mailsubmit.CodeFromNotAllowed) |
| + var granted []string |
| + if sender.Grant != nil { |
| + granted = sender.Grant.Domains |
| + } |
| + var dv *mailwire.DomainView |
| + if slices.Contains(granted, domain) { |
| + if dv, err = m.domain(ctx, req.Account, domain, now); err != nil { |
| + m.logf("mailer: domain %s/%s: %v", req.Account, domain, err) |
| + return unavailable |
| + } |
| } |
| - // Every send names a configuration set (§9.0: an absent parameter lets |
| - // a header choose one, and the set is what carries the events that |
| - // count and attribute the send). A verified identity has none only on a |
| - // deployment with no SNS topic, where the account's set |
| - // (mail.ConfigSetName) does not exist either, and a send through a |
| - // missing set fails outright. So the send is refused rather than made |
| - // without one (review round 1, Task 5 P1-1). |
| - if region.ConfigSet == "" { |
| + switch mailwire.CheckFromDomain(granted, domain, req.App, m.mailRegion, dv) { |
| + case mailwire.FromSendable: |
| + case mailwire.FromNoConfigSet: |
| m.logf("mailer: %s/%s: domain %s has no configuration set in %s (no event destination on this deployment); submission refused", req.Account, req.App, domain, m.mailRegion) |
| return refuse(http.StatusForbidden, mailsubmit.CodeFromNotAllowed) |
| + default: |
| + return refuse(http.StatusForbidden, mailsubmit.CodeFromNotAllowed) |
| } |
| + region := dv.Regions[m.mailRegion] |
| // The sender is the app sender, read from its own key (decision 5): |
| // the key and the tag name it by that id, never by the body's. |
diff --git a/internal/mailwire/mailwire.go b/internal/mailwire/mailwire.go| index 869e2e94c..b85c3308b 100644 |
| --- a/internal/mailwire/mailwire.go |
| +++ b/internal/mailwire/mailwire.go |
| @@ -11,6 +11,7 @@ package mailwire |
| import ( |
| "regexp" |
| + "slices" |
| "time" |
| ) |
| @@ -206,3 +207,42 @@ var ( |
| func IsMailerCaller(caller string) bool { |
| return mailerBareRe.MatchString(caller) || mailerARNRe.MatchString(caller) |
| } |
| + |
| +// FromVerdict is CheckFromDomain's answer. |
| +type FromVerdict int |
| + |
| +// The From-domain verdicts, in the order CheckFromDomain tries them. |
| +const ( |
| + FromSendable FromVerdict = iota // the mailer sends from it |
| + FromNotGranted // not one of the sender's granted domains |
| + FromNoDomainRecord // no record, or one whose body names another domain |
| + FromAppNotListed // the record does not list the app |
| + FromNotVerified // not verified, with an identity, in the mail region |
| + FromNoConfigSet // verified, but no configuration set in the mail region |
| +) |
| + |
| +// CheckFromDomain is the one rule for whether the box-local mailer sends |
| +// from domain for app: granted to the sender exactly, its record (dv, read |
| +// by DomainKey; nil when absent) names the domain and lists the app, and it |
| +// is verified with an identity and a configuration set in region. The mailer |
| +// applies it to every message, and the console's switch door to the app's |
| +// declared From before it switches (review P3: one rule, not two). |
| +func CheckFromDomain(granted []string, domain, app, region string, dv *DomainView) FromVerdict { |
| + if !slices.Contains(granted, domain) { |
| + return FromNotGranted |
| + } |
| + if dv == nil || dv.Domain != domain { |
| + return FromNoDomainRecord |
| + } |
| + if !slices.Contains(dv.Apps, app) { |
| + return FromAppNotListed |
| + } |
| + r := dv.Regions[region] |
| + if r == nil || r.Status != DomainStatusVerified || r.IdentityARN == "" { |
| + return FromNotVerified |
| + } |
| + if r.ConfigSet == "" { |
| + return FromNoConfigSet |
| + } |
| + return FromSendable |
| +} |
diff --git a/internal/provision/platform_mail_submission_census_test.go b/internal/provision/platform_mail_submission_census_test.go| index 57f85331b..a7e609843 100644 |
| --- a/internal/provision/platform_mail_submission_census_test.go |
| +++ b/internal/provision/platform_mail_submission_census_test.go |
| @@ -55,6 +55,14 @@ func platformMailSubmissionWriteCensusInventory() []censusEntry { |
| {"internal/console/updatescore.go", "Server.applyUpdates", "record-writer", "key:UpdateRecord", "9afe3dfe0f6adde778620161ac4f3926cfdaf2cf1b4ba4538d8e42cb813641e5"}, |
| {"internal/console/updatescore.go", "Server.requestInstall", "record-writer", "key:UpdateRecord", "52e7a48fd69c910608ee5a23e4ffa426271d1ef4dc3e9e77810e6be1d533a8c0"}, |
| {"internal/console/routedecls.go", "var routeDecls", "key-site", "lit:instances,lit:sidecars", "5e01c3e29752d228318ad4abd2778226a13cbb51a2955f8e203d240a37772a1d"}, |
| + // Task 6 review (Fable P3s): re-digested, classification and kinds |
| + // unchanged, the same Put of the app sender. |
| + // - Declare refuses a new prefix while switched, not only while |
| + // provisioned. |
| + // - Enable, while switched, delivers the declared From to the |
| + // default bundle (writeMailFromIn), as a re-declare may change it. |
| + {"internal/mail/walk.go", "claimUnserializedDeclare", "reference", "id:Put", "0c93e8131cd554b46ba2cc6bf69689bdd766d552e72d42c3ff309d7f335be802"}, |
| + {"internal/mail/walk.go", "claimUnserializedEnable", "reference", "id:Put", "c1bc29aebbe3d9577b2ca6cd9e6766143876a574a8273854919377dddc2b834b"}, |
| } |
| for _, r := range repins { |
| found := false |
| @@ -79,11 +87,16 @@ func platformMailSubmissionWriteCensusInventory() []censusEntry { |
| // - submissionServeDoors is a list of route patterns, one of which |
| // names .../instances/...; a literal, no store access (key-site, as |
| // routeDecls). |
| + // Task 6 review (Fable P2-5 and P3s) re-digested three of them, the |
| + // same writes and reads: SwitchOn carries the reap mark only while |
| + // Provisioned is nil; the reap also waits out an unrecorded day; and |
| + // switchedRecordHosts records each host's account, so a fleet box fires |
| + // only for its own account's apps. |
| entries = append(entries, |
| - censusEntry{"internal/mail/submission.go", "claimUnserializedSwitchOn", "reference", "id:Put", "b96e39cf352fbaef5792262092aa1d34767acaa6979f7436150243daff631eb5"}, |
| + censusEntry{"internal/mail/submission.go", "claimUnserializedSwitchOn", "reference", "id:Put", "ad8d87d4d40b10f23beac8542ca78ab920b6ecd3578de780ef5a6cfd136e376c"}, |
| censusEntry{"internal/mail/submission.go", "claimUnserializedSwitchOff", "reference", "id:Put", "7d2b913ae9c3f5c82d050d4483f5913cc0aa8d0a8c12cac5a01de27aa4a37f04"}, |
| - censusEntry{"internal/mail/sweep.go", "claimUnserializedReapAppUserAfterSubmission", "reference", "id:Put", "7a3f67b9811f9a8dd037323237e27e85c24ac1f36bc4c8feec7330c6be6cc3b6"}, |
| - censusEntry{"internal/console/alertsignals.go", "engineReads.switchedRecordHosts", "key-site", "key:RecordsPrefix", "d7ddf56fb020fee4bcc194d6bfe68dae778103f86588a679249a1b277e5f827b"}, |
| + 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"}, |
| ) |
| 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 89c2ca8c6..6ba30caac 100644 |
| --- a/internal/provision/testdata/plan14-root-reads-platform-mail-submission.tsv |
| +++ b/internal/provision/testdata/plan14-root-reads-platform-mail-submission.tsv |
| @@ -85,7 +85,7 @@ internal/activator/backend_exec.go ExecBackend.spawnChildFrom legacy accepted-le |
| internal/activator/backend_exec.go ExecBackend.spawnUnitFrom legacy accepted-legacy accepted-legacy;rev3=census-ruling-carlos-run;basis=Re-digested at the pre-land merge: the body includes main's own change under census ruling 292, with no further change from this branch. the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): main's body; it calls prepareKeyedAt and keeps the launch environment and its key layer on the generation's handle; read sites unchanged, offsets moved;rev3=census-ruling-wake-latency-2;basis=times the launch's steps with time.Now() (build, prepare, launch file, gate, root start) and adds them to its existing "started" journal line; no read added or moved;rev3=census-ruling-rootfs-apps-2;basis=the unit names in its error and log lines go through runUnitName, and newUnitProcFor's new error (a role with no unit to observe) fails the start as markStartUncertain after root started the unit; the binary spawn is otherwise unchanged, a rootfs row never reaches it (nestedGate refuses one); no read added;rev3=census-ruling-stateless-replicas-1;basis=Task 3a: Use the verified generation/launch mode to remove CARLOS_DB after environment merges and omit the binary --db argument where applicable. Existing runtime, layout, secrets and exec gates remain; route reads are mode projection only.;rev3=census-ruling-edge-page-cache-1;basis=computes the page cache launch inputs once (launchInputs: sha256 over the staged or pinned exe's Version and the fileEnv this spawn already read; "" with no exe, since root binds the movable live link) and keeps them on the unit handle (up.inputs); no new file, registry or bucket read; read sites unchanged (29); no read added;rev3=census-ruling-gvisor-demos;basis=Task 5: gate launch using startup-captured mode and existing route/role/layout before preparation or execution; migrate structured root start identity and reject mismatches. Unsupported gVisor paths refuse; native behavior and existing root authority checks retained. No new root read source. Merge2 e8a1ddde: retain main launchInputs computed from the captured file environment and pinned/staged build and store them on the handle, alongside branch sandbox gate, validated root StartResponse Unit/Sandbox/InvocationID and all uncertain-start cleanup. No new direct read.;rev3=census-ruling-fix-silent-start-kill-861;basis=#861: one log line before killFailedGen naming the host, the generation unit (runUnitName) and the error already in hand; the +registry:Host sites are those two arguments to log.Printf; no new read source, behaviour unchanged;rev3=census-ruling-instance-gomemlimit-991;basis=#991: the agent as carlos (nested start): resolves the zero tier once (b.tier(rt), the existing live-tier read), adds GOMEMLIMIT=GoMemLimitOf(tier.MemoryMax) to the launch file env unless the app's fileEnv already names it (withGoMemLimit; skipped under gVisor, where root supplies its own and drops any launch value), passes that same tier to startRole, and logs it. No new read source; root still validates memory_max against the size table; read sites unchanged.;rev3=census-ruling-platform-mail-submission;basis=Task 6: calls warnUndeclaredMailBuild with the route and the version being spawned. Logs and emits an instance event once per (host, version) when the app is switched and the staged manifest does not declare --mail submit; never refuses. Agent, not root. registry:Host@1308,registry:Host@2277,registry:Host@2382,registry:Host@2513,registry:Host@2970,registry:Host@4046,registry:Host@4407,registry:Host@5175,registry:Host@5761,registry:Host@6026,registry:Host@6183,registry:Host@6204,registry:Host@6425,registry:Host@6610,registry:Host@7005,registry:Host@7266,registry:Host@7375,registry:Host@8374,registry:Host@8468,registry:Stateless@2327,whole:Route@1093,whole:Route@1472,whole:Route@1714,whole:Route@197,whole:Route@2127,whole:Route@2367,whole:Route@3027,whole:Route@3082,whole:Route@4282,whole:Route@431,whole:Route@6258,whole:Route@7455,whole:Route@995 ddbf6eef60b08fca97a3b63af8a931efb73e014392059996073d41811b488493 |
| internal/activator/prepare.go ExecBackend.listenControl legacy accepted-legacy accepted-legacy;rev3=J1;basis=root-route;rev3=census-ruling-edge-page-cache-1;basis=passes the whole route to edge.ListenControl instead of rt.Host (the -registry:Host +whole:Route change); nothing else;rev3=census-ruling-platform-mail-submission;basis=Task 4: the same replacement as spawnChildFrom, with gen as the write fence's generation, so the nested and rootfs listener mounts exactly what the flat one does. Agent, not root. registry:Host@508,whole:Route@361,whole:Route@389 f6534861cdbeef80dbcfaf6b07df685e4ac2f2a86650db54f174871526a50aff |
| internal/activator/rootfs.go ExecBackend.spawnRootfs legacy accepted-legacy accepted-legacy;rev3=census-ruling-rootfs-apps-2;identity=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos);basis=root-route (J1, as spawnUnitFrom, whose shape it has): new (rootfs Plan 2 Tasks 5 and 9): prepareKeyedAt (the instance's own directories, environment and listeners, unchanged), the schema-2 tenant launch file (environment only, CARLOS_SOCKET and CARLOS_DB set by the agent), the caller's exec gate, then StartRootfs over the control socket naming the image and web; root resolves the command from its own staged manifest (C4) and the tenant file may name no command (the trampoline refuses one); the failure handling is spawnUnitFrom's; its sites are the row's host and route; no root decision; final fix I1: root's answers that guarantee no start (ErrStartRefused: 503 not ready or claim-armed, 501 unconfigured, 400, 409, 507), like its 403, are marked a refusal (refuseRootfs), so verdictOf and classifyStep record no failure of the build and no stop is asked; a 502 and a transport failure still may have run; the same nineteen sites, offsets moved;rev3=census-ruling-rootfs-apps-3;basis=rootfs Plan 3 fix wave 1 (d35fcb1f, census P1-1): takes the tier root is asked for as an argument; a zero tier means GenTier's (the former body), so a caller that chose a limit has it kept, as spawnChildFrom and spawnUnitFrom keep theirs; the same nineteen sites, no read added;rev3=census-ruling-stateless-replicas-1;basis=Task 3a: Use the verified generation/launch mode to remove CARLOS_DB after environment merges and omit the binary --db argument where applicable. Existing runtime, layout, secrets and exec gates remain; route reads are mode projection only.;rev3=census-ruling-edge-page-cache-1;basis=sets up.inputs = launchInputs(id.Version, fileEnv): the image version and env this spawn already read, hashed in memory; no new read; read sites unchanged (20); no read added;rev3=census-ruling-gvisor-demos;basis=Task 5: gate launch using startup-captured mode and existing route/role/layout before preparation or execution; migrate structured root start identity and reject mismatches. Unsupported gVisor paths refuse; native behavior and existing root authority checks retained. No new root read source. Merge2 e8a1ddde: retain main launchInputs on rootfs handle from existing staged image version and fileEnv. Keep branch sandbox gate and root identity validation. No new read.;rev3=census-ruling-fix-silent-start-kill-861;basis=#861: one log line before killFailedRootfsGen naming the host, the unit and the error already in hand; the +registry:Host site is that argument to log.Printf; no new read source, behaviour unchanged;rev3=census-ruling-platform-mail-submission;basis=Task 6: the same warnUndeclaredMailBuild call for a rootfs spawn. Agent, not root. registry:Host@1358,registry:Host@1531,registry:Host@1831,registry:Host@1950,registry:Host@2697,registry:Host@3034,registry:Host@3261,registry:Host@3388,registry:Host@3713,registry:Host@3841,registry:Host@390,registry:Host@3950,registry:Host@4667,registry:Host@4761,whole:Route@1105,whole:Route@1137,whole:Route@1224,whole:Route@199,whole:Route@2057,whole:Route@3094,whole:Route@4026,whole:Route@502,whole:Route@602,whole:Route@732 a19e5be10a746fec3fedc5715314f6cf00fa6f3d4be23db3242bf2f599a1a563 |
| -internal/host/agent.go runAgent authority B,C,D,F rev3=census-ruling-self-serve-moves-1;basis=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): builds the box's lifetime judge once (newBoxJudge, nil with host claims on) and hands it to the seed placement, the moves and runs workers and every loop it starts; read sites unchanged, offsets moved; B,C,D,F authority retained; self-serve moves 1 Task 8: derives the box's lifetimes switch from the judge once (lifetimes := boxJudge != nil) and hands it to the edges file loop; read sites unchanged, offsets moved;rev3=census-ruling-plans-4d-lapse;basis=arms two more plans hooks from the same snapshot: e.SetPlanDisabledFor(planDisabledFor) beside SetPlanGovernedFor, and svc.SetDisabledFor(planDisabledRoute) beside SetMaxRunFor (plans 4d); the reads live in those units (plans-4d-units decision); read sites unchanged, offsets moved;rev3=census-ruling-rootfs-apps-2;basis=main's body as of the merge of origin/main 9b81d97b (with main's plan rate ceiling, edge request records, regional box names, self-serve moves plan 1, plans 4d-1 lapse and its other later changes under main's own census rulings) plus the rootfs placement wiring in the activator start: an agentRootfs built from eb.NestedOK, CARLOS_DEPLOYMENT_SINGLE_TENANT, CARLOS_POOLS, the claim flag, swapArming's answer, the control client's /ready/rootfs and, on a fleet box whose identity resolved, fleetOwnerCheck over the deploy store main already opens for the fleet label (fleetStore), then arm and armedRootfs.Store; this body reads nothing new itself; the closures it wires read later, at a rootfs wake and each status tick: GET /ready/rootfs over the control socket, NestedOK's checks, and release.FleetOwnerKey for the judged row's own account and this box's fleet from the deploy store;rev3=census-ruling-instance-egress-sizes-328-329;basis=#328 plan 2 Tasks 7 and 11, #329 plan 3 Task 7 and plan 1 Task 7's policy cache: the control client is built once and handed to eb.Control, to the status tick (egressStatus) and to a new egressNudgeLoop goroutine; armSizeSource(svc, "/sys/fs/cgroup") after the activator Service; armPolicyCache() after armChangeIndex; statusLoop takes egressStatus. The reads are those units' own (decision rows); this body reads nothing new: the same five sites, offsets moved, in the agent; B,C,D,F authority retained.;rev3=census-ruling-remote-instance-metrics;basis=builds the metrics loop's owners closure (metricsOwners over the agent's registry, the activator and cgm.Leftover) when an activator exists and hands it to metricsLoop; reads nothing new itself;rev3=census-ruling-edge-asset-cache-3;basis=adds file:Statfs. runAgent keeps its authority (B,C,D,F). The new site is assetcache.Statfs, an exported assetcache.FS interface value (var Statfs FS = statfsFS{}), not a function value and not a call in runAgent: the ready hook passes it to armEdgeAssetCache as the store's filesystem, and armEdgeAssetCache calls its Space method on the configured data directory (dataDir(): $CARLOS_DATA_DIR, else /data), which calls unix.Statfs there (statfsFS.Space, accepted legacy at census-ruling-edge-asset-cache-2). No request-supplied pathname reaches it.;rev3=census-ruling-remote-metrics-nested;basis=main's body (merged origin/main acfa4f80, under main's own census rulings) plus: snapshots the nested layout (snapshotNestedUnits over /sys/fs/cgroup/carlos.slice/carlos-instances.slice) once at start, before the activator, and hands the metrics loop a unitSources struct (stamped units, routeHostNames, that root and the snapshot); reads nothing new itself;rev3=census-ruling-region-ha-p1a;basis=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): wires region HA P1a into the activator: cfg.Record = haRecordFacts(openDeployStore, boxJudge) (the box's lifetime judge this body already builds with newBoxJudge, nil with host claims on; CI fix) and cfg.Self = lease.CurrentSelf; eb.Lifetimes (the process's lifetime index), eb.Registry, eb.StartupSwept (seedSweptAtStart.Load), eb.FilesStore from newProductionFilesStore (now lease.NewFilesStore, rootaws-loaded, a log line on failure) and lease.SetObligationDir(<data>/.ha-owed) (logged on failure; HA acquires then refuse); this body reads nothing new itself, the same five sites; the reads are those units' own (haRecordFacts and lease's SetObligationDir are new rows on this card); merge of origin/main d7ae1d76: main's own later changes to this body are kept as main has them, under main's rulings (census-ruling-remote-instance-metrics: the metricsOwners closure for metricsLoop; census-ruling-edge-asset-cache-3: the +file:Statfs site, assetcache.Statfs handed to the asset ready hook); this branch's change is the same as above;rev3=census-ruling-region-ha-p1b1;basis=region HA P1b-1: builds one termfence.Confirmer (Self from lease.CurrentSelf at each call, EC2 DescribeInstances method only, client from rootaws.LoadDefaultConfig with retries off, built lazily on first use) and sets eb.OwnerTerminated; this body reads nothing new itself, the same six sites;rev3=census-ruling-rootfs-apps-3;basis=rootfs Plan 3 Task 7: the startup Sweep literal hands its answer to startupSwept, which logs as before and, only on a clean sweep, marks rootfs admission swept (MarkRootfsSwept); same Sweep call, no read added;rev3=census-ruling-managed-fleets-1b;basis=managed fleets 1b (controller ruling after branch review R1, and Paul's R2 ruling): sets svc.Fleet = fleetWakeFor(os.Getenv, identity, identErr, fleetStore) from the identity it already resolves once and the deployment store the fleet loops already opened, and logs an ERROR naming the identity error when the box is on a fleet with an invalid identity. fleetWakeFor reads CARLOS_REGION and CARLOS_FLEET from the same environment. Read sites unchanged (6). Agent, not root; a platform box is unchanged.;rev3=census-ruling-rootfs-apps-6;basis=rootfs Plan 6 Task 12: one call more beside armRunsPass, armInteractivePass(svc, reg, rolloutSink, boxJudge), in the same activator Configure hook, handing it the same box judge; fix round 1 (Astra P2, shutdown): after svc.Shutdown(ctx), shutdownInteractive(ctx) ends and joins every interactive session under the same shutdown budget; the worker's own reads are its units' (interactive.go); this body reads nothing new, the same six sites; merge of origin/main 6f1f6ca6: main's svc.Fleet = fleetWakeFor(...) and its invalid-identity ERROR line are kept as main has them (census-ruling-managed-fleets-1b); this branch's change is the same as above; read sites unchanged (6);rev3=census-ruling-fix-set-aside-exdev;basis=set-aside EXDEV fix: one field more on the agent ExecBackend literal, RawInstanceDir: layout.RawInstanceDir (a pure path join: <dataDir>/.instances/<InstanceID(host)>), so the start rule set-aside moves a copy out through the raw directory instead of through the nosymfollow bind; this body reads nothing new, the same six sites;rev3=census-ruling-durability-3a-escrow;basis=durability 3a Task 3: one more assignment beside eb.FilesStore: eb.EscrowKey = haEscrowKey(os.Getenv("CARLOS_SECRETS_KEY")), the agent's own environment parsed by appconfig.ParsePrivateKey as the moves pass parses it (unset or unparseable: a log line and nil, and HA publication refuses on the box). No path is opened or read, no read site added; the same six sites, offsets moved; B,C,D,F authority retained. Durability 3a Task 4: one more goroutine beside configSyncLoop: go escrowLoop(agentCtx, reg, svc), the escrow sweep every 30 s over the same registry and Service. This body reads nothing new itself; the same six sites, offsets moved; B,C,D,F authority retained. Durability 3a Task 5: one more call beside eb.EscrowKey: wireRawSecretPages(eb, PageOperator, metricsBoxLabel(os.Getenv, readMachineID())), which sets eb.OnRawSecret to page an operator (alerting.Page through PageOperator, LevelIncident) on its own goroutine with a 20 s timeout; metricsBoxLabel and readMachineID are the reads this body already makes for the moves refusal log; no new read site; the same six sites, offsets moved; B,C,D,F authority retained. Merge of origin/main 90c4d3aa: main's own later changes to this body are kept as main has them, under main's rulings; this branch's change is the same as above. Merge of origin/main 00bf5b8c (fleet set-aside EXDEV fix): main's change to this body is kept as main has it, under its own census ruling; this branch's change is unchanged.;rev3=census-ruling-probe-burst-limit;basis=two more sink wirings beside setAnalyticsSink: setProtectionSink(e.SetProtectionRecordOnly) and setAssetOwnersSource(e.AssetOwners), function values the telemetry pass calls; this body reads nothing new, the same six sites; authority B,C,D,F retained; no new root read or write kind;rev3=census-ruling-region-ha-p1b3a;basis=Arm HA placement exactly once on the existing Service before activatorStart and edges publication, wiring AwakeApps and the PageOperator callback; existing six read sites unchanged, no new root authority.;rev3=census-ruling-stateless-replicas-1;basis=Final review I3: start the concrete coordinator's renewal worker with agent setup; existing closeReplicaCoordinator shutdown cancels and joins it before release. No new read sites or credentials. Merge origin/main c59715e7: retain main's armHAPlacement(svc, PageOperator) wiring beside the existing activator setup; stateless coordinator and shutdown wiring remain. Same read sites; no new root read or credential.;rev3=census-ruling-edge-held-streams;basis=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): in the edge-ready callback, calls act.SetHeldWakeHook(e.HeldWake) when act is non-nil (installing the non-blocking wake callback) and stores e.HeldStreamsForStatus in heldStreamsSource. Wiring of in-memory callbacks only; no read added.;rev3=census-ruling-region-ha-p1b3b-t;basis=Wire Service.SetDutyView to the live edge DutySnapshot in the ready callback. No new read; no new loop or cloud operation. B2 wires the registry as the persistent DutyStore before service startup; no new cloud or filesystem path. B3b: arm one journal-backed termination consumer before service startup using agentCtx and the shared confirmer; expose edge tick and join at edge shutdown. No new direct read sites.;rev3=census-ruling-agent-start-demo-1;basis=Passes the existing registry, data store and hibernation prefix into the demo worker, and the existing instance-control client into the demo before-exec hook. No alternate data store or polling loop. Merge resolution against origin/main 9bd45488 retains main's HA departure controller, lifecycle and duty wiring alongside the demo data store and worker; no read site added by the resolution.;rev3=census-ruling-region-ha-p3a;basis=P3a Task 3: install closed fixed admission before every launch source, bind activator/backend and edge, wire the real termination Started lifecycle and role reader after the change index; close before cancellation/child shutdown. No new external reads or cloud authority. Fix R1: move bind/lifecycle/edge-option wiring into wireAgentAdmission and worker listing into runWorkerBootPassAfterAdmission. Worker boot waits for admission before listing then uses unchanged bounded wakes and per-host serialization; whole Route read moves to the helper. No new storage, cloud, or root execution authority. Preserve merged main's agent wiring and census basis; the branch removes one whole Route use by moving worker iteration to the helper, with no added read kind.;rev3=census-ruling-stateless-replicas-2;basis=Slice 3b: arms a fleet-only worker using the existing registry, activator, backend and authenticated console transport. Owned worker stops and joins at shutdown. No new bucket reader. merge of origin/main 9b8b2c50: retain HA duty/departure lifecycle, wake-slot and existing agent wiring alongside the replica placement worker; no new read introduced by resolution. merge of origin/main 6be08467: Retain main demo configuration, admission, build and expiry wiring alongside the replica worker; merge-only body change, no additional read. merge of origin/main 7920cccf: Retain main box-role/group admission wiring and boot publication beside the owned replica worker and shutdown; main moves the boot registry List into runWorkerBootPassAfterAdmission, removing its inline whole Route site. No new read introduced by conflict resolution.;rev3=census-ruling-stateless-replicas-3;basis=Task 1 fix round 1 M3: retain the private snapshot source and cancel/join ownership, but use the replica-health-specific retry loop. It logs its first failure only and retains the existing exponential backoff capped at 30 seconds; unsupported builds return nil. Existing five direct read sites unchanged; no new credentials, bucket reader or app lifecycle action. Fix round 1 Q20: publish Edge.ReplicaSnapshots as a separate in-memory status source, leaving the tenant-visible Upstreams source unchanged. No new external reader or authority.;rev3=census-ruling-region-ha-p3b;basis=Load root-written group marker/configuration, configure signed boot binding and agent receipt completer, wire cancellable admission into departure work and expose cached GroupReaderSnapshot. New indirect boot reads use protected root files; agent-owned receipt controls duplicate initial completion only, never root restart permission. Same five direct sites. Merge 45cebde4 retains the replica health socket lifecycle and setReplicaSource beside GroupReaderSnapshot; no extra read beyond main.;rev3=census-ruling-agent-start-demo-2;basis=agent.go:309-329 opens demo-traffic.db beside the operator-configured registry when a demo domain exists, closes it at shutdown and wires drain-before-purge; :1010-1019 shares the worker and write gate; :1164-1177 installs the fleet identity and closed-until-worker serving callback. One added whole Route pass; the new indirect filesystem/SQL reads are claimed in openDemoTraffic and worker/store units. No request chooses the database pathname.;rev3=census-ruling-region-ha-p1b3b-s;basis=Wire the service duty view to authoritative cached sidecar manifest placement in LifetimeIndex and the edge sidecar projection; missing policy denies duty. Existing instance duty wiring remains.;rev3=census-ruling-region-ha-g2-t3;basis=T3a: wire eb.Page = PageOperator beside OwnerTerminated before departures arm, so suspect-holder pages work if departure setup fails; no new read; existing nine sites and authority unchanged; pages through the existing sink. T3b: publish the same backend through an atomic pointer for the metrics observer, and clear it on return; no new external read or authority.;rev3=census-ruling-agent-start-demo-3;basis=Wire the claim activator and root snapshot client into the demo worker; pass moved readiness to status reporting. Census read-site delta: unchanged (9).;rev3=census-ruling-region-ha-g2-fixes;basis=Wire local pool evidence, live withdrawal activator, startup ingress scan and alias publication, and edge lookup; no new direct sites; new indirect record/claim reads use existing store/judge paths described in ingress helpers.;rev3=census-ruling-region-ha-g2r-fixes;basis=W3: starts the existing record-view backstop loop with a departure-inventory listener (non-blocking, coalesced signal) even without an armed RecordView; it requests the existing full pass (backstopFullDue) there. Same nine read sites; no new read or authority.;rev3=census-ruling-region-ha-graceful-terminate-t2;basis=Derive one signal-time deadline with a 90-second budget; cap departure stop and startup/seed/service shutdown joins by it. No read added.;rev3=census-ruling-static-sweep-periodic;basis=in the edge-ready callback, publishes e.LargestStaticTree in staticTreeSource for the disk alert line (diskAlertFrac in the metrics loop); in-memory wiring only, no read added; read sites unchanged (9);rev3=census-ruling-edge-page-cache-1;basis=wires the exec backend's CurrentInputs into the edge cache (wireCurrentInputs) and, in the ready hook after armEdgeAssetCache (whose returned store it now keeps), calls armEdgePageCache, which does nothing unless CARLOS_PAGE_CACHE=1; read sites unchanged (9); no read added;rev3=census-ruling-gvisor-demos;basis=Capture sandbox resolution and refusal once; log errors once; gate route admission and BeforeExec before process launch. No new root read. Task 5: pass the once-captured sandbox effective mode/config error into ExecBackend, UnitBackend and the immutable Client expectation. Same startup environment/registry reads; swapArming declines gVisor before placement. Task 8: arm read-only status projection with the existing Client.SandboxStatus callback. Agent status now queries the existing root /ready endpoint; no new root authority or guest-file input. Merge2 e8a1ddde: retain main wireCurrentInputs and armEdgePageCache through the existing asset-store ready hook alongside branch once-captured sandbox mode, wake gates and root status wiring. No new direct read; main page-cache helpers retain their own census overlays.;rev3=census-ruling-region-ha-held-build;basis=wires the drain state: svc.SetDrainingSource(boxDrain.IsDraining), svc.SetPeerDrainView(e.PeerDraining), e.SetPeerDrainedHook(svc.DropHoldersNaming); in-memory only; no read added; region HA held-requests Task 5: on group members, starts the drain driver over the activator, the edge and boxDrain, and serves its root-only drain socket; no read added beyond the socket's own Branch review r1: the drain state follows the root start fence on group members (the fence reader is the existing fenceLocation.read, a root-owned fixed path); e.SetPeerUndrainedHook(svc.AllowHoldersNaming) beside the drained hook (memory only); the drain socket serves only the agent's own user. No read added.;rev3=census-ruling-security-review-mitigations;basis=Wire the cached operator flat-layout choice into the exec backend's new-resident refusal; no read source added, existing authority retained.;rev3=census-ruling-w6-ingress-drain;basis=agent (user carlos), not root. Builds the ingress drain (newIngressDrain) with arming read at ask time from os.Getenv (CARLOS_REGION_HA, CARLOS_INGRESS_TARGET_GROUPS, both from the root-owned host.env), the fixed admission and lease.CurrentSelf (existing IMDS identity); its reader is awstg.Load, the box role's credentials calling ELB DescribeTargetHealth/DescribeTargetGroupAttributes (new AWS reads, by the agent). Wires admission.closeStartsForIngressDrain, the lbhealth drain condition, ingress.setEdge, and ingress.shutdownStarted in WithShutdownStarted. The drain socket (/run/carlos/.ha-drain/drain.sock, agent-user only, existing) is now also served on a fixed box with the drain configured (was group members only), routing /v1/ingress/* to the ingress drain and the group drain verbs to 404 there. armHADepartures now takes fixtureDepartureGetenv() and MakeQueue fixtureDepartureQueue(), which in a production (non-rootrunner) build are os.Getenv and nil, as before. Read sites unchanged (9).;rev3=census-ruling-stateless-replicas-4-task1;basis=Arms the fleet-only replica swap worker next to the placement worker: same console URL and fleet token as the existing replicaCoordinatorAPI, the existing activator Service; stops and joins at shutdown. No new read site, credential or bucket reader.;rev3=census-ruling-stateless-replicas-4-task2;basis=Task 2: sets deployWorker.step to the rollout scheduler answer for the record permit (replicaStepOf over armedRollout), an in-memory callback; no read site, credential or bucket reader added.;rev3=census-ruling-stateless-replicas-4-task2-fix2;basis=Task 2 fix round 2: the swap worker step is armedReplicaStep, the same lazy scheduler lookup as before as a named function; no read site added.;rev3=census-ruling-stateless-replicas-4-merge-main;basis=Merge of main 5fac2ff1: both sides changed it. Main (01d6ca78, linked-deployments-slice1) starts linkLoop beside tunnelLoop; this branch keeps its replica coordinator wiring. Both kept as-is; no read added.;rev3=census-ruling-stateless-replicas-4-final;basis=#511 final wave item 2: wires the swap worker's drive (armedReplicaDrive, the armed rollout manager's DriveReplicaRelease); no read added;rev3=census-ruling-stateless-replicas-4-merge-main2;basis=Merge of main af871da0 (v0.34.49): both sides changed it. Main (178dcfe5, member-backups-2a) moves the inline duty-view closure into armDutyView/dutyView and starts verifyAssignLoop; its sites drop by registry:Host and whole:Route x2 as main recorded them. This branch keeps its replica coordinator, swap worker and drive wiring. Both kept as-is; no read added.;rev3=census-ruling-stateless-replicas-4-drill3;basis=drill 3 R24: makes one in-memory channel, closes it (once) inside the edge's existing shutdown-started callback after ingress.shutdownStarted, and passes it to tunnelLoop, which drains only a fleet channel name; no read added, same six sites; touches no admission, lease, ingress drain, listener or file; the agent process, no root decision;rev3=census-ruling-edge-ppv2;basis=Agent (uid carlos), not root. memwatchLoop now gets edgeProxyCounters(&demoEdge) (in-process counters, no read). The drain socket's driver is newAgentDrainSocket(ingress, e, os.Getenv), which attaches the edge trust handler only when CARLOS_INGRESS_PROXY_SOURCES in the agent's environment (from the root-owned host.env) parses to a non-empty list; the socket is served when drainSocketServed: a group member or a configured ingress drain (both as before), or a box armed for PROXY protocol (new). The socket's path and agent-user-only permissions are unchanged. Read sites unchanged (6).;rev3=census-ruling-same-box-edge-fence;basis=Agent (uid carlos), not root. One added line: armEdgeFenceStatus(ctl.EdgeFence), beside the existing armExecSandboxStatus, so the layout report can ask root's /ready for the edge fence state over the control socket client the agent already holds. No read added.;rev3=census-ruling-platform-mail-submission;basis=Task 4: sets eb.Mail = mailsubmit.SocketForwarder{} on every box, and eb.MailSwitch to a mailSwitchCache's On that opens the deploy store itself through openDeployStore, retried at most once a minute with an error line until it opens (review round 1, Task 4 P3), armed for the serial-move refresh (armedMailSwitch). Agent, not root. file:Exec@21578,file:Open@2191,file:Statfs@57102,registry:App@13287,registry:App@13665,whole:Route@13279,whole:Route@13657,whole:Route@50580 ee6470495a59bc35232da4558dc1082c7c068dbee1893cf3c2da365557b9360b |
| +internal/host/agent.go runAgent authority B,C,D,F rev3=census-ruling-self-serve-moves-1;basis=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): builds the box's lifetime judge once (newBoxJudge, nil with host claims on) and hands it to the seed placement, the moves and runs workers and every loop it starts; read sites unchanged, offsets moved; B,C,D,F authority retained; self-serve moves 1 Task 8: derives the box's lifetimes switch from the judge once (lifetimes := boxJudge != nil) and hands it to the edges file loop; read sites unchanged, offsets moved;rev3=census-ruling-plans-4d-lapse;basis=arms two more plans hooks from the same snapshot: e.SetPlanDisabledFor(planDisabledFor) beside SetPlanGovernedFor, and svc.SetDisabledFor(planDisabledRoute) beside SetMaxRunFor (plans 4d); the reads live in those units (plans-4d-units decision); read sites unchanged, offsets moved;rev3=census-ruling-rootfs-apps-2;basis=main's body as of the merge of origin/main 9b81d97b (with main's plan rate ceiling, edge request records, regional box names, self-serve moves plan 1, plans 4d-1 lapse and its other later changes under main's own census rulings) plus the rootfs placement wiring in the activator start: an agentRootfs built from eb.NestedOK, CARLOS_DEPLOYMENT_SINGLE_TENANT, CARLOS_POOLS, the claim flag, swapArming's answer, the control client's /ready/rootfs and, on a fleet box whose identity resolved, fleetOwnerCheck over the deploy store main already opens for the fleet label (fleetStore), then arm and armedRootfs.Store; this body reads nothing new itself; the closures it wires read later, at a rootfs wake and each status tick: GET /ready/rootfs over the control socket, NestedOK's checks, and release.FleetOwnerKey for the judged row's own account and this box's fleet from the deploy store;rev3=census-ruling-instance-egress-sizes-328-329;basis=#328 plan 2 Tasks 7 and 11, #329 plan 3 Task 7 and plan 1 Task 7's policy cache: the control client is built once and handed to eb.Control, to the status tick (egressStatus) and to a new egressNudgeLoop goroutine; armSizeSource(svc, "/sys/fs/cgroup") after the activator Service; armPolicyCache() after armChangeIndex; statusLoop takes egressStatus. The reads are those units' own (decision rows); this body reads nothing new: the same five sites, offsets moved, in the agent; B,C,D,F authority retained.;rev3=census-ruling-remote-instance-metrics;basis=builds the metrics loop's owners closure (metricsOwners over the agent's registry, the activator and cgm.Leftover) when an activator exists and hands it to metricsLoop; reads nothing new itself;rev3=census-ruling-edge-asset-cache-3;basis=adds file:Statfs. runAgent keeps its authority (B,C,D,F). The new site is assetcache.Statfs, an exported assetcache.FS interface value (var Statfs FS = statfsFS{}), not a function value and not a call in runAgent: the ready hook passes it to armEdgeAssetCache as the store's filesystem, and armEdgeAssetCache calls its Space method on the configured data directory (dataDir(): $CARLOS_DATA_DIR, else /data), which calls unix.Statfs there (statfsFS.Space, accepted legacy at census-ruling-edge-asset-cache-2). No request-supplied pathname reaches it.;rev3=census-ruling-remote-metrics-nested;basis=main's body (merged origin/main acfa4f80, under main's own census rulings) plus: snapshots the nested layout (snapshotNestedUnits over /sys/fs/cgroup/carlos.slice/carlos-instances.slice) once at start, before the activator, and hands the metrics loop a unitSources struct (stamped units, routeHostNames, that root and the snapshot); reads nothing new itself;rev3=census-ruling-region-ha-p1a;basis=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): wires region HA P1a into the activator: cfg.Record = haRecordFacts(openDeployStore, boxJudge) (the box's lifetime judge this body already builds with newBoxJudge, nil with host claims on; CI fix) and cfg.Self = lease.CurrentSelf; eb.Lifetimes (the process's lifetime index), eb.Registry, eb.StartupSwept (seedSweptAtStart.Load), eb.FilesStore from newProductionFilesStore (now lease.NewFilesStore, rootaws-loaded, a log line on failure) and lease.SetObligationDir(<data>/.ha-owed) (logged on failure; HA acquires then refuse); this body reads nothing new itself, the same five sites; the reads are those units' own (haRecordFacts and lease's SetObligationDir are new rows on this card); merge of origin/main d7ae1d76: main's own later changes to this body are kept as main has them, under main's rulings (census-ruling-remote-instance-metrics: the metricsOwners closure for metricsLoop; census-ruling-edge-asset-cache-3: the +file:Statfs site, assetcache.Statfs handed to the asset ready hook); this branch's change is the same as above;rev3=census-ruling-region-ha-p1b1;basis=region HA P1b-1: builds one termfence.Confirmer (Self from lease.CurrentSelf at each call, EC2 DescribeInstances method only, client from rootaws.LoadDefaultConfig with retries off, built lazily on first use) and sets eb.OwnerTerminated; this body reads nothing new itself, the same six sites;rev3=census-ruling-rootfs-apps-3;basis=rootfs Plan 3 Task 7: the startup Sweep literal hands its answer to startupSwept, which logs as before and, only on a clean sweep, marks rootfs admission swept (MarkRootfsSwept); same Sweep call, no read added;rev3=census-ruling-managed-fleets-1b;basis=managed fleets 1b (controller ruling after branch review R1, and Paul's R2 ruling): sets svc.Fleet = fleetWakeFor(os.Getenv, identity, identErr, fleetStore) from the identity it already resolves once and the deployment store the fleet loops already opened, and logs an ERROR naming the identity error when the box is on a fleet with an invalid identity. fleetWakeFor reads CARLOS_REGION and CARLOS_FLEET from the same environment. Read sites unchanged (6). Agent, not root; a platform box is unchanged.;rev3=census-ruling-rootfs-apps-6;basis=rootfs Plan 6 Task 12: one call more beside armRunsPass, armInteractivePass(svc, reg, rolloutSink, boxJudge), in the same activator Configure hook, handing it the same box judge; fix round 1 (Astra P2, shutdown): after svc.Shutdown(ctx), shutdownInteractive(ctx) ends and joins every interactive session under the same shutdown budget; the worker's own reads are its units' (interactive.go); this body reads nothing new, the same six sites; merge of origin/main 6f1f6ca6: main's svc.Fleet = fleetWakeFor(...) and its invalid-identity ERROR line are kept as main has them (census-ruling-managed-fleets-1b); this branch's change is the same as above; read sites unchanged (6);rev3=census-ruling-fix-set-aside-exdev;basis=set-aside EXDEV fix: one field more on the agent ExecBackend literal, RawInstanceDir: layout.RawInstanceDir (a pure path join: <dataDir>/.instances/<InstanceID(host)>), so the start rule set-aside moves a copy out through the raw directory instead of through the nosymfollow bind; this body reads nothing new, the same six sites;rev3=census-ruling-durability-3a-escrow;basis=durability 3a Task 3: one more assignment beside eb.FilesStore: eb.EscrowKey = haEscrowKey(os.Getenv("CARLOS_SECRETS_KEY")), the agent's own environment parsed by appconfig.ParsePrivateKey as the moves pass parses it (unset or unparseable: a log line and nil, and HA publication refuses on the box). No path is opened or read, no read site added; the same six sites, offsets moved; B,C,D,F authority retained. Durability 3a Task 4: one more goroutine beside configSyncLoop: go escrowLoop(agentCtx, reg, svc), the escrow sweep every 30 s over the same registry and Service. This body reads nothing new itself; the same six sites, offsets moved; B,C,D,F authority retained. Durability 3a Task 5: one more call beside eb.EscrowKey: wireRawSecretPages(eb, PageOperator, metricsBoxLabel(os.Getenv, readMachineID())), which sets eb.OnRawSecret to page an operator (alerting.Page through PageOperator, LevelIncident) on its own goroutine with a 20 s timeout; metricsBoxLabel and readMachineID are the reads this body already makes for the moves refusal log; no new read site; the same six sites, offsets moved; B,C,D,F authority retained. Merge of origin/main 90c4d3aa: main's own later changes to this body are kept as main has them, under main's rulings; this branch's change is the same as above. Merge of origin/main 00bf5b8c (fleet set-aside EXDEV fix): main's change to this body is kept as main has it, under its own census ruling; this branch's change is unchanged.;rev3=census-ruling-probe-burst-limit;basis=two more sink wirings beside setAnalyticsSink: setProtectionSink(e.SetProtectionRecordOnly) and setAssetOwnersSource(e.AssetOwners), function values the telemetry pass calls; this body reads nothing new, the same six sites; authority B,C,D,F retained; no new root read or write kind;rev3=census-ruling-region-ha-p1b3a;basis=Arm HA placement exactly once on the existing Service before activatorStart and edges publication, wiring AwakeApps and the PageOperator callback; existing six read sites unchanged, no new root authority.;rev3=census-ruling-stateless-replicas-1;basis=Final review I3: start the concrete coordinator's renewal worker with agent setup; existing closeReplicaCoordinator shutdown cancels and joins it before release. No new read sites or credentials. Merge origin/main c59715e7: retain main's armHAPlacement(svc, PageOperator) wiring beside the existing activator setup; stateless coordinator and shutdown wiring remain. Same read sites; no new root read or credential.;rev3=census-ruling-edge-held-streams;basis=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): in the edge-ready callback, calls act.SetHeldWakeHook(e.HeldWake) when act is non-nil (installing the non-blocking wake callback) and stores e.HeldStreamsForStatus in heldStreamsSource. Wiring of in-memory callbacks only; no read added.;rev3=census-ruling-region-ha-p1b3b-t;basis=Wire Service.SetDutyView to the live edge DutySnapshot in the ready callback. No new read; no new loop or cloud operation. B2 wires the registry as the persistent DutyStore before service startup; no new cloud or filesystem path. B3b: arm one journal-backed termination consumer before service startup using agentCtx and the shared confirmer; expose edge tick and join at edge shutdown. No new direct read sites.;rev3=census-ruling-agent-start-demo-1;basis=Passes the existing registry, data store and hibernation prefix into the demo worker, and the existing instance-control client into the demo before-exec hook. No alternate data store or polling loop. Merge resolution against origin/main 9bd45488 retains main's HA departure controller, lifecycle and duty wiring alongside the demo data store and worker; no read site added by the resolution.;rev3=census-ruling-region-ha-p3a;basis=P3a Task 3: install closed fixed admission before every launch source, bind activator/backend and edge, wire the real termination Started lifecycle and role reader after the change index; close before cancellation/child shutdown. No new external reads or cloud authority. Fix R1: move bind/lifecycle/edge-option wiring into wireAgentAdmission and worker listing into runWorkerBootPassAfterAdmission. Worker boot waits for admission before listing then uses unchanged bounded wakes and per-host serialization; whole Route read moves to the helper. No new storage, cloud, or root execution authority. Preserve merged main's agent wiring and census basis; the branch removes one whole Route use by moving worker iteration to the helper, with no added read kind.;rev3=census-ruling-stateless-replicas-2;basis=Slice 3b: arms a fleet-only worker using the existing registry, activator, backend and authenticated console transport. Owned worker stops and joins at shutdown. No new bucket reader. merge of origin/main 9b8b2c50: retain HA duty/departure lifecycle, wake-slot and existing agent wiring alongside the replica placement worker; no new read introduced by resolution. merge of origin/main 6be08467: Retain main demo configuration, admission, build and expiry wiring alongside the replica worker; merge-only body change, no additional read. merge of origin/main 7920cccf: Retain main box-role/group admission wiring and boot publication beside the owned replica worker and shutdown; main moves the boot registry List into runWorkerBootPassAfterAdmission, removing its inline whole Route site. No new read introduced by conflict resolution.;rev3=census-ruling-stateless-replicas-3;basis=Task 1 fix round 1 M3: retain the private snapshot source and cancel/join ownership, but use the replica-health-specific retry loop. It logs its first failure only and retains the existing exponential backoff capped at 30 seconds; unsupported builds return nil. Existing five direct read sites unchanged; no new credentials, bucket reader or app lifecycle action. Fix round 1 Q20: publish Edge.ReplicaSnapshots as a separate in-memory status source, leaving the tenant-visible Upstreams source unchanged. No new external reader or authority.;rev3=census-ruling-region-ha-p3b;basis=Load root-written group marker/configuration, configure signed boot binding and agent receipt completer, wire cancellable admission into departure work and expose cached GroupReaderSnapshot. New indirect boot reads use protected root files; agent-owned receipt controls duplicate initial completion only, never root restart permission. Same five direct sites. Merge 45cebde4 retains the replica health socket lifecycle and setReplicaSource beside GroupReaderSnapshot; no extra read beyond main.;rev3=census-ruling-agent-start-demo-2;basis=agent.go:309-329 opens demo-traffic.db beside the operator-configured registry when a demo domain exists, closes it at shutdown and wires drain-before-purge; :1010-1019 shares the worker and write gate; :1164-1177 installs the fleet identity and closed-until-worker serving callback. One added whole Route pass; the new indirect filesystem/SQL reads are claimed in openDemoTraffic and worker/store units. No request chooses the database pathname.;rev3=census-ruling-region-ha-p1b3b-s;basis=Wire the service duty view to authoritative cached sidecar manifest placement in LifetimeIndex and the edge sidecar projection; missing policy denies duty. Existing instance duty wiring remains.;rev3=census-ruling-region-ha-g2-t3;basis=T3a: wire eb.Page = PageOperator beside OwnerTerminated before departures arm, so suspect-holder pages work if departure setup fails; no new read; existing nine sites and authority unchanged; pages through the existing sink. T3b: publish the same backend through an atomic pointer for the metrics observer, and clear it on return; no new external read or authority.;rev3=census-ruling-agent-start-demo-3;basis=Wire the claim activator and root snapshot client into the demo worker; pass moved readiness to status reporting. Census read-site delta: unchanged (9).;rev3=census-ruling-region-ha-g2-fixes;basis=Wire local pool evidence, live withdrawal activator, startup ingress scan and alias publication, and edge lookup; no new direct sites; new indirect record/claim reads use existing store/judge paths described in ingress helpers.;rev3=census-ruling-region-ha-g2r-fixes;basis=W3: starts the existing record-view backstop loop with a departure-inventory listener (non-blocking, coalesced signal) even without an armed RecordView; it requests the existing full pass (backstopFullDue) there. Same nine read sites; no new read or authority.;rev3=census-ruling-region-ha-graceful-terminate-t2;basis=Derive one signal-time deadline with a 90-second budget; cap departure stop and startup/seed/service shutdown joins by it. No read added.;rev3=census-ruling-static-sweep-periodic;basis=in the edge-ready callback, publishes e.LargestStaticTree in staticTreeSource for the disk alert line (diskAlertFrac in the metrics loop); in-memory wiring only, no read added; read sites unchanged (9);rev3=census-ruling-edge-page-cache-1;basis=wires the exec backend's CurrentInputs into the edge cache (wireCurrentInputs) and, in the ready hook after armEdgeAssetCache (whose returned store it now keeps), calls armEdgePageCache, which does nothing unless CARLOS_PAGE_CACHE=1; read sites unchanged (9); no read added;rev3=census-ruling-gvisor-demos;basis=Capture sandbox resolution and refusal once; log errors once; gate route admission and BeforeExec before process launch. No new root read. Task 5: pass the once-captured sandbox effective mode/config error into ExecBackend, UnitBackend and the immutable Client expectation. Same startup environment/registry reads; swapArming declines gVisor before placement. Task 8: arm read-only status projection with the existing Client.SandboxStatus callback. Agent status now queries the existing root /ready endpoint; no new root authority or guest-file input. Merge2 e8a1ddde: retain main wireCurrentInputs and armEdgePageCache through the existing asset-store ready hook alongside branch once-captured sandbox mode, wake gates and root status wiring. No new direct read; main page-cache helpers retain their own census overlays.;rev3=census-ruling-region-ha-held-build;basis=wires the drain state: svc.SetDrainingSource(boxDrain.IsDraining), svc.SetPeerDrainView(e.PeerDraining), e.SetPeerDrainedHook(svc.DropHoldersNaming); in-memory only; no read added; region HA held-requests Task 5: on group members, starts the drain driver over the activator, the edge and boxDrain, and serves its root-only drain socket; no read added beyond the socket's own Branch review r1: the drain state follows the root start fence on group members (the fence reader is the existing fenceLocation.read, a root-owned fixed path); e.SetPeerUndrainedHook(svc.AllowHoldersNaming) beside the drained hook (memory only); the drain socket serves only the agent's own user. No read added.;rev3=census-ruling-security-review-mitigations;basis=Wire the cached operator flat-layout choice into the exec backend's new-resident refusal; no read source added, existing authority retained.;rev3=census-ruling-w6-ingress-drain;basis=agent (user carlos), not root. Builds the ingress drain (newIngressDrain) with arming read at ask time from os.Getenv (CARLOS_REGION_HA, CARLOS_INGRESS_TARGET_GROUPS, both from the root-owned host.env), the fixed admission and lease.CurrentSelf (existing IMDS identity); its reader is awstg.Load, the box role's credentials calling ELB DescribeTargetHealth/DescribeTargetGroupAttributes (new AWS reads, by the agent). Wires admission.closeStartsForIngressDrain, the lbhealth drain condition, ingress.setEdge, and ingress.shutdownStarted in WithShutdownStarted. The drain socket (/run/carlos/.ha-drain/drain.sock, agent-user only, existing) is now also served on a fixed box with the drain configured (was group members only), routing /v1/ingress/* to the ingress drain and the group drain verbs to 404 there. armHADepartures now takes fixtureDepartureGetenv() and MakeQueue fixtureDepartureQueue(), which in a production (non-rootrunner) build are os.Getenv and nil, as before. Read sites unchanged (9).;rev3=census-ruling-stateless-replicas-4-task1;basis=Arms the fleet-only replica swap worker next to the placement worker: same console URL and fleet token as the existing replicaCoordinatorAPI, the existing activator Service; stops and joins at shutdown. No new read site, credential or bucket reader.;rev3=census-ruling-stateless-replicas-4-task2;basis=Task 2: sets deployWorker.step to the rollout scheduler answer for the record permit (replicaStepOf over armedRollout), an in-memory callback; no read site, credential or bucket reader added.;rev3=census-ruling-stateless-replicas-4-task2-fix2;basis=Task 2 fix round 2: the swap worker step is armedReplicaStep, the same lazy scheduler lookup as before as a named function; no read site added.;rev3=census-ruling-stateless-replicas-4-merge-main;basis=Merge of main 5fac2ff1: both sides changed it. Main (01d6ca78, linked-deployments-slice1) starts linkLoop beside tunnelLoop; this branch keeps its replica coordinator wiring. Both kept as-is; no read added.;rev3=census-ruling-stateless-replicas-4-final;basis=#511 final wave item 2: wires the swap worker's drive (armedReplicaDrive, the armed rollout manager's DriveReplicaRelease); no read added;rev3=census-ruling-stateless-replicas-4-merge-main2;basis=Merge of main af871da0 (v0.34.49): both sides changed it. Main (178dcfe5, member-backups-2a) moves the inline duty-view closure into armDutyView/dutyView and starts verifyAssignLoop; its sites drop by registry:Host and whole:Route x2 as main recorded them. This branch keeps its replica coordinator, swap worker and drive wiring. Both kept as-is; no read added.;rev3=census-ruling-stateless-replicas-4-drill3;basis=drill 3 R24: makes one in-memory channel, closes it (once) inside the edge's existing shutdown-started callback after ingress.shutdownStarted, and passes it to tunnelLoop, which drains only a fleet channel name; no read added, same six sites; touches no admission, lease, ingress drain, listener or file; the agent process, no root decision;rev3=census-ruling-edge-ppv2;basis=Agent (uid carlos), not root. memwatchLoop now gets edgeProxyCounters(&demoEdge) (in-process counters, no read). The drain socket's driver is newAgentDrainSocket(ingress, e, os.Getenv), which attaches the edge trust handler only when CARLOS_INGRESS_PROXY_SOURCES in the agent's environment (from the root-owned host.env) parses to a non-empty list; the socket is served when drainSocketServed: a group member or a configured ingress drain (both as before), or a box armed for PROXY protocol (new). The socket's path and agent-user-only permissions are unchanged. Read sites unchanged (6).;rev3=census-ruling-same-box-edge-fence;basis=Agent (uid carlos), not root. One added line: armEdgeFenceStatus(ctl.EdgeFence), beside the existing armExecSandboxStatus, so the layout report can ask root's /ready for the edge fence state over the control socket client the agent already holds. No read added.;rev3=census-ruling-platform-mail-submission;basis=Task 4: sets eb.Mail = mailsubmit.SocketForwarder{} on every box, and eb.MailSwitch to a mailSwitchCache's On that opens the deploy store itself through openDeployStore, retried at most once a minute with an error line until it opens (review round 1, Task 4 P3), armed for the serial-move refresh (armedMailSwitch). Task 6: also sets the ExecBackend's ManifestOf, the same staged-manifest read as TierOf (rt.App and RouteAccount(rt), hence +registry:App and +whole:Route), for the spawn-time check of decision 10, which logs and emits an event and never refuses. Agent, not root. file:Exec@21578,file:Open@2191,file:Statfs@57102,registry:App@13287,registry:App@13665,whole:Route@13279,whole:Route@13657,whole:Route@50580 ee6470495a59bc35232da4558dc1082c7c068dbee1893cf3c2da365557b9360b |
| @coverage . 92eeac6b896196505876a5a4c5dea470134c43cc45996e9343b32481b3ec4baa |
| @coverage infra/modules/region-host d1a978ca67367880d0940ae7aa460f311addd4335c196a279d86caa6fe1e1721 |
| @coverage infra/modules/region-host/tests 1aa5c549b79e7d8b19a266a2aeae8e4e2bb22b40072f36362da95bcf2c439a07 |
| @@ -95,9 +95,9 @@ 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 36bb8e0cd052a8cac07ffc96803a8187ef7ebf7861136700077c51e78cc7c99e |
| +@coverage internal/mailer 2f20d6b5968e8e4264fc183865a671d3d89db274e79eb207df06ecf7c31cf186 |
| @coverage internal/mailsubmit 519123e15891e0802427595306d8caca1fd7f4f861ae1a2ec70e1c10f012e263 |
| -@coverage internal/mailwire 58b9cbb8a003ed11feb1c0352c5c23992fe532da895471ec76045528ab12e077 |
| +@coverage internal/mailwire 0242392c670a0f61b875056b0d79576ccb69c2e29f56735cbb191e7d038222a0 |
| @coverage internal/moves 9390702695d308a327f5572f4ff5967718141c5d385dff7671ff1e2c825ef407 |
| @coverage internal/provision a7fca446b2464e9d0804272a46146013085cdec8fecb96a3508cc055295f31d3 |
| @coverage internal/release 26028ee5f49462e120b401530ce539a81c76c632bfa6065f6881b80680a3e9cb |