carlos / platform Public

Fleet public routes follow-ups (#457 Phase 1a deferred minors, triaged by Astra on the whole-branch review). PutForward refuses a non-forward kind, an empty Host or a non-fleet Region with the sentinel ErrNotForward (carried over the remote transport) and builds its kept-column list from one production literal checked against PRAGMA. One owner map, Registry.FleetOwners, is used by both Edge.Reload and the hub's forward phase. New tests pin the membership subquery's fleet condition, dns_checked_at preservation, the upgrade close cancelling the request, the HTTP plan-throttle path for a forward row, the box's throttle exemption, the display reader keeping forward rows, the edges-file removal PUT, the catch-all after trash, a time-aware rate ceiling, no first-dial 401 and the gate's origin; comment and spec wording fixes. No behaviour change beyond PutForward's up-front refusals. Reviews: Astra R1 READY AFTER FIXES (two test P2s fixed); census fleet-routes-followups approved by Astra on #280. Not released.

Squashed from fleet-routes-followups into main.
Paul Campbell pushed by claude agent, operated by paul@keymail.dev c24e7a04b16ebafe305f662bdd19fd915e5ff8c5 parent 65fd806
24 files changed, +733 −136
  • docs/superpowers/notes/census-proposal-fleet-routes-followups.md +28 −0
  • docs/superpowers/plans/2026-10-30-fleet-public-routes.md +1 −1
  • docs/superpowers/reviews/CODEX-FINDINGS-fleet-routes-followups-R1.md +35 −0
  • docs/superpowers/reviews/CODEX-REVIEW-BRIEF-fleet-routes-followups.md +20 −0
  • docs/superpowers/reviews/fleet-public-routes-deferred-minors.md +20 −0
  • docs/superpowers/specs/2026-10-29-fleet-public-routes-design.md +28 −7
  • fleet_public_routes_e2e_test.go +43 −14
  • internal/console/regionfacts.go +21 −20
  • internal/console/regionfacts_test.go +22 −0
  • internal/console/sealkey.go +5 −4
  • internal/console/view.go +2 −2
  • internal/edge/edge.go +7 −10
  • internal/edge/fleetforward_policy_test.go +115 −9
  • internal/edge/ratelimit.go +6 −6
  • internal/host/fleet_forward_budget_test.go +50 −16
  • internal/host/hub.go +11 −8
  • internal/provision/testdata/plan14-root-reads-chain.tsv +1 −0
  • internal/provision/testdata/plan14-root-reads-fleet-routes-followups.tsv +17 −0
  • internal/registry/fleetbox_if_test.go +32 −0
  • internal/registry/fleets.go +18 −0
  • internal/registry/fleets_test.go +28 −0
  • internal/registry/forward.go +54 −15
  • internal/registry/forward_test.go +168 −23
  • internal/registry/remote.go +1 −1

CI cancelled — superseded by a newer push — run details

diff --git a/docs/superpowers/notes/census-proposal-fleet-routes-followups.md b/docs/superpowers/notes/census-proposal-fleet-routes-followups.md
new file mode 100644
index 000000000..c1db74c27
--- /dev/null
+++ b/docs/superpowers/notes/census-proposal-fleet-routes-followups.md
@@ -0,0 +1,28 @@
+# Census approval: fleet-routes-followups
+
+Ruling `census-ruling-fleet-routes-followups`. The independent reviewer approves or rejects every change below, 4 with a new disposition; nothing goes to the census owner (Paul, #280, 2026-10-26).
+
+| unit | change | read sites | what changed |
+|---|---|---|---|
+| `internal/edge/edge.go` `Edge.Reload` | sites | -registry:Account, -registry:Name, -whole:Fleet ×2 | the owners map is now e.reg.FleetOwners() instead of ListFleets folded inline: the same fresh-connection ListFleets read and the same name->account map (-registry:Account, -registry:Name, -whole:Fleet x2 move into Registry.FleetOwners); no read added; same error path (abort the reload) |
+| `internal/registry/forward.go` `Registry.PutForward` | sites | +registry:Host ×2, +registry:Region ×2 | refuses up front, with the new sentinel ErrNotForward and before any read or write, an rt that is not a forward row (as before, now a sentinel), has an empty Host, or whose Region is not a fleet placement (registry.FleetPlacement); +registry:Host x2 and +registry:Region x2 read only the argument in those checks; the transaction and statement are unchanged |
+
+Envelopes re-pinned: `internal/edge`, `internal/host`, `internal/registry`.
+
+Review: a model from the other family than the author reads the branch's diff against main on the amadan.net remote (`origin` or `amadan`, whichever points at amadan.net) and gives a verdict for every unit and every re-pinned envelope above. For a unit, compare the change with its recorded disposition and basis below; for an envelope, read every changed function in the package and what it reaches. Reject if the change lets root open, run, query or follow anything it did not before from a path or input a tenant, an app or a box agent can create, write or name; if it weakens a check, refusal, validation, argument or environment the basis relies on; or if the diff cannot settle either. Otherwise approve. Record each verdict on #280 with the tip. A rejected unit goes back to the author to correct; nothing escalates to the census owner.
+
+Recorded dispositions, which each change must still satisfy:
+
+- `internal/edge/edge.go` `Edge.Reload`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=J1;basis=root-route;rev3=census-ruling-design-edge-rate-limit-358;basis=each route's upstream entry gains rate: e.parseRateSettings(t), the row's rate_limit column parsed once per reload; the one added site is that whole:Route pass of t (parseRateSettings is a new unit, classified in the decisions overlay); no other read added;rev3=census-ruling-certwarm-wake;basis=the single reload hook call becomes runReloadHooks(), which runs every registered hook in order (#386); no read added, same 57 sites (56 before #358 landed on main);rev3=census-ruling-edge-asset-cache-3;basis=each tenant reverse proxy built in the switch (the tunnel, fleet, socket and TCP arms, every *httputil.ReverseProxy) is installed behind assetScrubbedProxy, which hands the proxy an assetInformationalScrub writer so an app's 1xx (103) loses the asset cache's reserved headers (X-Carlos-Asset-Fill, -Fill-Ack, -Expires, Carlos-Cache) on every local path, as the backhaul already does (final review F6); a type check of the proxy it just built and a wrapper around it; static and status handlers untouched; read sites unchanged (57), offsets moved; no read added;rev3=census-ruling-alias-wake-338;basis=#338 follow-up: after the path fold, a resolved platform alias takes its source's own upstream entry (same proxy, route, hibernating: the existing activator wake, lease and fence), keeping its own prefix map (none for a minted apex) and never inheriting the source's (Astra r2 P1); a refused alias, or one whose source has no entry, is dropped from the map (not served, not Allowed); the attached-hostname fold clears platformAlias;rev3=census-ruling-rootfs-apps-3;basis=rootfs Plan 3 Task 5: the activator-managed test (generation proxy, hib, no-activator 404) is Route.ActivatorOwned instead of Kind and Hibernate inline, so a resident rootfs instance goes through the activator; binary rows unchanged;rev3=census-ruling-edge-roll-blip;basis=the tcpProxy and multiProxy calls pass e.hold (the per-Edge localHold set once in newEdge): a loopback TCP upstream that refuses is redialled for up to 13 s and a probed route with a local upstream waits for prober readmission instead of answering 502/503 (#434 part B); edge-side dial policy only, no read added, same 52 sites;rev3=census-ruling-regional-domains-447;basis=#447 Task 5: after the alias fold, reads the regional_domains rows (e.reg.ListRegional; an error aborts the reload as every registry read here does) and applies them with foldRegional against the routes slice the same reload read; the added reads are that one registry list and the routes already read;rev3=census-ruling-fleet-public-routes;basis=fleet public routes (spec 2026-10-29 rev 4, §4.2 writer rule): Tasks 4 and 6: the forward case (fleetProxy toward the binding's FleetBox, throttled refusal); one refusal check before the switch from FleetArmVerdict (sidecar not judged; a non-ready forward row refused; a forward row always judged by FleetServeEligible, any other row only where tunnels are on; an alias of a refused source refused with it); the accountless note; path rows of a forward host not folded; no alias folded onto a refused row; refusedHosts held through every fold. ListFleets and FleetChannelAuth read before the loop (+registry:FleetBox, +registry:Host x7, +whole:Route x3). Serving only; the hub's agent, not root. Review R1 finding 2: the switch reads verdict.Served (FleetArmVerdict) by host; the forward case and the fleet-placed case take their fleet from it (served.Fleet) instead of FleetPlacement(t.Region), and an admitted forward row not Served continues rather than falling through (+registry:Host, -registry:Region); the same rows take the same arms; no read added. Review R2: the switch is on DispatchArm(t, viaFleet, tunnels) (the order moved there unchanged: forward only when in Arm, own Tunnel, fleet, socket, addrs, static, status, else continue), the fleet cases read verdict.Arm (renamed from Served), and the platform-alias fold is foldPlatformAliases with the same take (source entry, own paths, alias marks) and the same refusal log (-registry:Kind x2, -registry:Socket, -registry:Tunnel, +whole:Route: those reads moved into DispatchArm); same rows, same arms, same entries; no read added.
+- `internal/registry/forward.go` `Registry.PutForward`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-fleet-public-routes;basis=fleet public routes (spec 2026-10-29 rev 4, §4.2 writer rule): Task 2: the only writer of a forward row's declared columns: refuses an argument whose kind is not forward; copies only the declared fields from its argument (Status ready, Provisioned true; no forbidden column is ever written); inside one IMMEDIATE transaction refuses a host a non-forward row holds (ErrHostHeld); keeps FleetBox while Region is unchanged; preserves the observational columns (+file:Exec, +file:QueryRow, +registry:Account, App, Channel, RateLimit, Region, Slug, +registry:Host x3, +registry:Kind, +registry:remote x2, +whole:Route x3, +whole:remoteClient x2).
+
+New dispositions, which census-propose wrote and the reviewer checks against the unit's reads and the diff:
+
+- new `internal/registry/fleets.go:Registry.FleetOwners`: reads +registry:Account, +registry:Name, +whole:Fleet ×2; written legacy, accepted-legacy, frozen
+- other `changed registry schema`: closed only if it is the registry schema (re-pinned)
+- quiet `internal/host/hub.go:hubFleetOwners`: reads nothing now; retired while it reads nothing (or its row keeps no sites)
+- reads `internal/registry/forward.go:var putForwardSQL`: +registry:Column, +registry:OnConflict ×2, +whole:ForwardColumn, +whole:forwardKeptColumn ×2; keeps legacy, task accepted-legacy
+
+Seal: `bca6ef741a96b72767b1747789cd01b3111d61b68548cbe368258c31f3d53a2e` → `1379d066c8dd2335d95d5f6e9c7bce65ff57f00b2b287a308d9b3f47911ae5e7`.
+
+Overlay: `internal/provision/testdata/plan14-root-reads-fleet-routes-followups.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`.
diff --git a/docs/superpowers/plans/2026-10-30-fleet-public-routes.md b/docs/superpowers/plans/2026-10-30-fleet-public-routes.md
index 2a9af0627..cffb44bc2 100644
--- a/docs/superpowers/plans/2026-10-30-fleet-public-routes.md
+++ b/docs/superpowers/plans/2026-10-30-fleet-public-routes.md
@@ -18,7 +18,7 @@
- declared, written only by `PutForward`: `Host`; `Kind` = `"forward"` (`registry.KindForward`); `Slug`; `App`; `Account`; `Region` = `fleet/<f>`; `Channel` (display only); `RateLimit` = `rec.RateLimitColumn()`; `Status` = `"ready"`; `Provisioned` = true; `CreatedAt` (kept from the existing row, else now);
- binding: `FleetBox`, written only by `SetFleetBoxIf`; `PutForward` keeps it while `Region` is unchanged and clears it when `Region` changes;
- observational, preserved by `PutForward`, read by no dispatch, publication or eligibility decision: `DNSStatus`, `DNSCheckedAt`, `CertExpiresAt`;
- - forbidden, zero, checked one by one by `InertForward`: `Socket`, `Addr`, `Addrs`, `Health`, `HoldOp`, `Incarnation`, `ServingSeq`, `SeedSource`, `ImportGate`, `AssetsOff`, `AssetGen`, `LastError`, `DBPath`, `Version`, `PrevVersion`, `GoodVersion`, `GoodDigest`, `GoodDemand`, `ServingVersion`, `Pool`, `Environment`, `Tunnel`, `Caps`, `Hibernate`, `HA`, `Runtime`, `Gate`, `Canary`, `Replication`, `NextDue`, `StatusNamed`, `Backing`, `Unit`, `Platform`, `Seed`, `Args`, `IdleSeconds`, `MaxRunSeconds`, `Steering`, `UpdateSettings`, `EgressAllow`, `Size`, `PolicyExpiresAt`, `BuildState`, `Replicas`, `Replica`, `ClaimIncarnation`, `ClaimStamp`, `ClaimOwner`, `ClaimRowID`.
+ - forbidden (50 fields), zero, checked one by one by `InertForward`: `Socket`, `Addr`, `Addrs`, `Health`, `HoldOp`, `Incarnation`, `ServingSeq`, `SeedSource`, `ImportGate`, `AssetsOff`, `AssetGen`, `LastError`, `DBPath`, `Version`, `PrevVersion`, `GoodVersion`, `GoodDigest`, `GoodDemand`, `ServingVersion`, `Pool`, `Environment`, `Tunnel`, `Caps`, `Hibernate`, `HA`, `Runtime`, `Gate`, `Canary`, `Replication`, `NextDue`, `StatusNamed`, `Backing`, `Unit`, `Platform`, `Seed`, `Args`, `IdleSeconds`, `MaxRunSeconds`, `Steering`, `UpdateSettings`, `EgressAllow`, `Size`, `PolicyExpiresAt`, `BuildState`, `Replicas`, `Replica`, `ClaimIncarnation`, `ClaimStamp`, `ClaimOwner`, `ClaimRowID`.
- Writer rule (§4.2, R3-1): refuse forward inputs before transactional side effects, guard the route writes. Only `PutForward`, `DeleteForward`, `SetFleetBoxIf`, `SetDNSStatus` and `SetCertExpiresAt` may write a forward row. Every other `routes` statement carries `kind <> 'forward'`; an insert or upsert over a forward host returns `ErrForwardRow`.
- Hub: a box with `CARLOS_TUNNEL_HOST` set and `CARLOS_FLEET` unset (`hubArmed`). Only a hub mints forward rows or runs the bindings pass; every other box retires any it holds.
- Tenancy (§4.4): a forward row is eligible only on a hub, inert, fleet-placed, its fleet in the hub's `fleets` table, and its raw `Account` non-empty and equal to the fleet's owner. A non-forward fleet-placed row taking the fleet arm: an empty raw `Account` is served and logged; otherwise `release.RouteAccount(rt)` must equal the owner. Raw field checked before `RouteAccount`.
diff --git a/docs/superpowers/reviews/CODEX-FINDINGS-fleet-routes-followups-R1.md b/docs/superpowers/reviews/CODEX-FINDINGS-fleet-routes-followups-R1.md
new file mode 100644
index 000000000..8697dd381
--- /dev/null
+++ b/docs/superpowers/reviews/CODEX-FINDINGS-fleet-routes-followups-R1.md
@@ -0,0 +1,35 @@
+Reviewed `d9c4666e361a2b1f0fe331ddfa738af085fe41b0`, branch `fleet-routes-followups`, round 1 of 3, against `65fd8060`.
+
+**P1: None.**
+
+**P2 findings**
+
+1. **The remote refusal test never exercises sentinel transport.** [forward_test.go:307](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/fleet-routes-followups/internal/registry/forward_test.go:307) calls `reg.PutForward` for both registries, but every invalid argument returns at [forward.go:332](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/fleet-routes-followups/internal/registry/forward.go:332), before `r.remote.call`. Removing `ErrNotForward` from `remoteErrors` would leave these assertions passing while server-originated refusals lose their sentinel identity.
+
+ **Fix:** Send malformed `PutForward` requests through `remote.remote.call`, bypassing client validation, and assert `errors.Is(err, ErrNotForward)` and no writes. Verify removing the sentinel registration fails the test. **Invariant:** sentinel identity survives the remote transport.
+
+2. **The new rate-test ceiling can reject correct behavior.** [fleet_public_routes_e2e_test.go:620](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/fleet-routes-followups/fleet_public_routes_e2e_test.go:620) permits at most six successes, but the limiter uses `time.Now` and the request loop has no duration bound. Five immediate requests followed by a pause until 2.1 seconds legitimately allow two more successes before a 429. The new assertion fails that valid schedule.
+
+ **Fix:** Account for elapsed refill time in the e2e ceiling; retain the exact burst assertion and mutation witness in the frozen-clock edge fixture. **Invariant:** test expectations remain valid under scheduling delays.
+
+**P3: None.** The remaining skips are reasonable within this slice, including the WebSocket work under #471 and the separate TLS-retirement behavior change.
+
+**Census verdicts**
+
+| Unit / envelope | Verdict and evidence |
+|---|---|
+| `Edge.Reload` | **APPROVE.** [edge.go:781](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/fleet-routes-followups/internal/edge/edge.go:781): same owner read and abort-on-error behavior; eligibility and publication remain unchanged. |
+| `Registry.PutForward` | **APPROVE.** [forward.go:331](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/fleet-routes-followups/internal/registry/forward.go:331): additional argument refusals only; transaction guards remain intact. Legitimate forward-phase inputs satisfy them. |
+| `var putForwardSQL` | **APPROVE.** [forward.go:273](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/fleet-routes-followups/internal/registry/forward.go:273): compiled metadata only. Independent comparison confirmed all 14 kept-column assignments and forbidden-column metadata are unchanged. |
+| `Registry.FleetOwners` | **APPROVE**, new `legacy / accepted-legacy`. [fleets.go:285](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/fleet-routes-followups/internal/registry/fleets.go:285): unchanged `ListFleets` query and transport; preserves raw accounts, missing-fleet semantics and errors. |
+| `hubFleetOwners` | **APPROVE**, quiet retirement. [hub.go:52](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/fleet-routes-followups/internal/host/hub.go:52): direct field reads moved into `FleetOwners`; error wrapping is unchanged. |
+| Registry field-list re-pin | **APPROVE.** [overlay:17](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/fleet-routes-followups/internal/provision/testdata/plan14-root-reads-fleet-routes-followups.tsv:17): only `OnConflict` added, matching `forwardKeptColumn`; no fields removed. |
+| Envelope `internal/edge` | **APPROVE.** [edge.go:786](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/fleet-routes-followups/internal/edge/edge.go:786), [ratelimit.go:117](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/fleet-routes-followups/internal/edge/ratelimit.go:117): equivalent owner fold and comment changes; no authority expansion. |
+| Envelope `internal/host` | **APPROVE.** [hub.go:38](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/fleet-routes-followups/internal/host/hub.go:38): equivalent helper call and corrected convergence commentary; no new root inputs. |
+| Envelope `internal/registry` | **APPROVE.** Changes above plus [remote.go:17](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/fleet-routes-followups/internal/registry/remote.go:17): validation tightens, SQL remains equivalent, sentinel registration is appended without renumbering existing entries. |
+
+No files changed. `GOCACHE` remained unset. Targeted Go tests could not start because the read-only sandbox denied Go’s work-directory creation. Runtime, mutation and census-test results remain unverified. Formatting and `git diff --check` passed.
+
+With no P1, apply the P2 fixes without reopening review, subject to the required census and newly changed security-behavior checks.
+
+READY AFTER FIXES
\ No newline at end of file
diff --git a/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-fleet-routes-followups.md b/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-fleet-routes-followups.md
new file mode 100644
index 000000000..a3316572d
--- /dev/null
+++ b/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-fleet-routes-followups.md
@@ -0,0 +1,20 @@
+# Review brief: fleet-routes-followups (deferred minors of #457 Phase 1a), round 1 of 3
+
+Repo carlos/platform, branch `fleet-routes-followups`, diff `65fd8060..<this brief's parent>`.
+Authorities: main's code (fleet public routes merged 65fd8060, live in v0.32.0 on dev and flagship), the spec docs/superpowers/specs/2026-10-29-fleet-public-routes-design.md, AGENTS.md (census, stopping rules).
+
+You are an independent reviewer. The branch closes the follow-ups listed in docs/superpowers/reviews/fleet-public-routes-deferred-minors.md (dispositions at its end) as triaged in docs/superpowers/reviews/CODEX-FINDINGS-fleet-public-routes-branch-R2.md. Commits by area: registry (SetFleetBoxIf membership witness; PutForward's kept-column list from one production literal `forwardKept`; dns_checked_at preservation; PutForward refuses a non-forward kind, empty Host or non-fleet Region with new sentinel ErrNotForward in remoteErrors), edge (upgrade-close cancels the request context; HTTP plan-throttle path for a forward row; box-side throttle exemption test; comment), console (comments, merged loop firstFleetPlacement, TestFleetFromRoutesSplitOnForwardRows), host (comments; budget test checks the removal PUT; §6 baseline clause), 27fe53bb (one owner map: Registry.FleetOwners used by Edge.Reload and hubFleetOwners), e2e (catch-all after trash, oks<=6, no first-dial 401, gate origin pinned, Region passed), docs, census overlay.
+
+## What to check
+1. No behaviour change beyond the stated tightenings: PutForward's new refusals cannot reject anything the forward phase legitimately writes (read internal/provision/forward.go's call sites); ErrNotForward over the remote transport; the owner-map fold keeps Reload's and the hub's owner semantics identical (raw account, missing fleets, read errors), and keeps the forward phase and the edge converging and failing closed.
+2. The tests: does each new test fail without its fix (the report claims mutations), and is any vacuous.
+3. Census: verdict for every unit and envelope on docs/superpowers/notes/census-proposal-fleet-routes-followups.md (Edge.Reload, Registry.PutForward, var putForwardSQL, Registry.FleetOwners (new), hubFleetOwners, the registry field list re-pin, envelopes internal/edge, internal/host, internal/registry), per AGENTS.md "Getting a change approved".
+4. The skipped items: is any skip wrong (something that should have been done here)?
+
+## Severity
+P1 unsafe/wrong/fails, blocks merge; P2 wrong or missing, fixed without another round; P3 polish.
+
+## Output
+Findings P1, P2, P3 with evidence (file:line), failure scenario, fix. Census verdicts. End with exactly one verdict: READY, READY AFTER FIXES, or NOT READY.
+
+Do not edit files. Do not spawn Anthropic-model reviewers or subagents of your own. Do not run the full test suites.
diff --git a/docs/superpowers/reviews/fleet-public-routes-deferred-minors.md b/docs/superpowers/reviews/fleet-public-routes-deferred-minors.md
index d5f5cb0c5..266744f2a 100644
--- a/docs/superpowers/reviews/fleet-public-routes-deferred-minors.md
+++ b/docs/superpowers/reviews/fleet-public-routes-deferred-minors.md
@@ -21,3 +21,23 @@ Task 12: minor (deferred): census basis text for fastConvergeLoop says boxProvis
Task 13: minor (deferred) + TASK 15 CARRY: a retired name with an existing cert is refused at HTTP (no map entry), not at the TLS handshake (wildcard cert, cert mirror, autocert cache answer without Allowed); Task 15 checks a retired name by its HTTP answer.
Task 13: minor (deferred): step 6 does not assert the catch-all alias refused after trash; step 4 rebuilds alias-pass inputs by hand (omits Region); step 3 lacks an upper bound (oks <= 6); noisy 401 on first dial and status/boxes 404; step 2 does not pin which edge drew the login form.
Task 13: final-review carry: confirm Task 6 tests cover a foreign account's record for the edges-file exclusion.
+
+## Dispositions (branch fleet-routes-followups, 2026-10-30)
+
+Done, test-first, each with a mutation shown where the item is a missing check:
+
+- Task 1: membership witness, TestSetFleetBoxIfMembershipIsTheRowsOwnFleet.
+- Task 2: kept columns are one production list (forwardKept), checked with ForwardForbidden against PRAGMA, and the conflict arm read back (TestPutForwardSetsEveryColumnButHost); dns_checked_at preservation; PutForward refuses a non-forward kind, an empty Host or a non-fleet Region with the sentinel ErrNotForward; the plan's list now says 50 (no committed doc said 51; the code has 50).
+- Task 5: cancellation (TestForwardUpgradeCloseCancelsTheRequest); HTTP plan throttle for a forward row (TestForwardPlanThrottlePlainHTTPAtTheHub); box-side plan-throttle tunnel exemption (TestForwardPlanThrottleExemptsTheTunnelAtTheBox); rateAdmit comment rewrapped.
+- Task 11: fleetFromRoutes comment; one loop (firstFleetPlacement) and TestFleetFromRoutesSplitOnForwardRows; sealkey.go comment.
+- Task 12: hub.go, budget test and spec §7 now say the phase and the edge converge and fail closed; the edges-file PUT when the row goes; the counting store's hidden optional interfaces noted in the test and spec §6; spec §6 says what the baseline is. R2's "Reload's inline owner-map construction": Registry.FleetOwners, one fold for the edge and the hub.
+- Task 13: catch-all refused after trash; oks <= 6; first dial after the hub's reload (no 401); the box draws the login form (metered on both edges); alias-pass inputs through FleetOwners with Region. Carry: Task 6's fpWorld already covers a foreign account's row (baj on bah's fleet) and its aliases; no change.
+
+Not done:
+
+- Task 5: TestForwardUpgradeIsLimitedAtTheHub's vacuous `ups > 2` and 101-or-502 acceptance, and the box-side upgrade exemption: WebSockets do not cross the tunnel (#471).
+- Task 11: C08 with no fleet to name needs new copy (R2: follow-up).
+- Task 11: test-report noise (buildvcs, a plan9 timeout under load): not a code item.
+- Task 13: a retired name with an existing certificate answers the TLS handshake (wildcard cert, cert mirror, autocert cache) and is refused only at HTTP: a behaviour change at the TLS layer, not a minor.
+- Task 13: the fleetapi store door answers 404 to a fleet box's alias-pass read of status/boxes/ (deployment route set unknown that pass). Production fleet boxes get the same answer, so the test keeps it.
+- R2: Fingerprint does not hash Runtime outside fleet admission (pre-existing ActivatorOwned dependency).
diff --git a/docs/superpowers/specs/2026-10-29-fleet-public-routes-design.md b/docs/superpowers/specs/2026-10-29-fleet-public-routes-design.md
index 808bf386d..dc1711e46 100644
--- a/docs/superpowers/specs/2026-10-29-fleet-public-routes-design.md
+++ b/docs/superpowers/specs/2026-10-29-fleet-public-routes-design.md
@@ -277,11 +277,18 @@ published by nobody and skipped by nothing that would skip an inert one
The registry enforces the shape where rows are written, so a stray value
cannot get there in the first place (R1-7, R2-6):
-- `PutForward(rt)`: one transaction. If a row exists at the host and is
- not a forward row, it returns `ErrHostHeld` and writes nothing.
+- `PutForward(rt)`: one transaction. An `rt` that is not a forward row,
+ has no `Host`, or whose `Region` is not a fleet placement
+ (`FleetPlacement`) is refused with `ErrNotForward` before anything is
+ read or written (follow-up to the deferred minors, defence in depth:
+ §4.4 already refuses to serve such a row). If a row exists at the host
+ and is not a forward row, it returns `ErrHostHeld` and writes nothing.
Otherwise it writes the declared columns from `rt`, keeps the
observational ones and (by the rule above) `FleetBox`, and writes zero
- to every forbidden column. Never `Upsert`, which keeps non-empty
+ to every forbidden column. The conflict arm is built from one
+ production list of the kept columns (`forwardKept`) and
+ `ForwardForbidden`, which a test checks together against
+ `PRAGMA table_info(routes)`. Never `Upsert`, which keeps non-empty
existing values (`registry.go:1512`).
- `DeleteForward(host)`: deletes the row only if it is still a forward
row, in the same statement.
@@ -868,9 +875,18 @@ retention, build states, bindings, edges file, the status tick's
reconciliation, `aliasPassReporting` with the box's judge in the context)
run over identical records and registry twice, once without and once
with a fleet-placed app on a `canary/*` channel and its forward row, with
-a counting store keyed by object prefix; the difference must equal the
+a counting store keyed by object prefix. The baseline is not a bucket
+without the app: both runs hold the fleet app's records, and they differ
+only in the forward phase, dormant in the baseline (today's hub, which
+skips a fleet-placed record at the fleet boundary) and armed in the
+other, which mints the row. The difference must equal the
table's `A = 1, C = 1` row by row, with zero manifest, policy, seed and
-channel-pointer reads for the forward app. Two more cases **(R3-2)**: the
+channel-pointer reads for the forward app, and the edges file must gain
+one PUT on the pass the row appears and one on the pass it goes (the
+app's records deleted). The counts are those of the counting store,
+which hides the store's optional interfaces, so every reader takes its
+fallback path on both runs alike, as the telemetry rows are those of the
+index off. Two more cases **(R3-2)**: the
forward app with an instance catch-all claim attached (the difference
gains exactly one instance-prefix `List` per alias pass, `K = 1`), and
the same with two of its instances sharing a label (it gains the two
@@ -1353,8 +1369,13 @@ Units, by file (N = new, R = removed, otherwise a changed body or sites):
`+whole:Fleet` x2): the hub's `ReconcileConfig.FleetOwners`, the
fleets table read on each call. Those are the reads Task 6 listed under
`fleetArmInputs`, which now takes its owners from `hubFleetOwners` so
- the forward phase and the edge's fleet arm judge by one map;
- `fleetArmInputs` keeps no read site and leaves the card.
+ the forward phase, the edges file and the alias pass read the table
+ the same way. The edge's Reload reads it itself (since the follow-ups,
+ through the same `Registry.FleetOwners`), so the phase and the edge
+ can disagree for one pass after a fleet is created, deleted or changes
+ owner; they converge on their next reads, and the disagreement fails
+ closed, since the edge serves a forward row only on its own read of the
+ owner. `fleetArmInputs` keeps no read site and leaves the card.
`BoxProvisionConfig` replaces `boxProvisionConfig`, which was never on
the card: it reads its environment through its `getenv` parameter
(`hubArmed(getenv)`, `provisionTickConfig(getenv)`) and the owner map
diff --git a/fleet_public_routes_e2e_test.go b/fleet_public_routes_e2e_test.go
index 66ff7935f..e9b38735d 100644
--- a/fleet_public_routes_e2e_test.go
+++ b/fleet_public_routes_e2e_test.go
@@ -64,6 +64,7 @@ import (
"fmt"
"io"
"log"
+ "math"
"net"
"net/http"
"net/http/httptest"
@@ -514,10 +515,12 @@ func TestFleetAppServesThroughTheHub(t *testing.T) {
t.Fatalf("box reload: %v", err)
}
}
+ // The hub's pass reloads its edge, which loads box-1's token, before
+ // the box first dials: a dial ahead of that reload is refused 401 and
+ // retried, which only adds noise.
+ hubPass()
stopBox := dial(boxToken[1])
t.Cleanup(stopBox)
-
- hubPass()
boxPass()
// The hub admits the instance's name: a fresh connection's handshake
// with it as SNI succeeds only while hub.Allowed says yes.
@@ -562,12 +565,22 @@ func TestFleetAppServesThroughTheHub(t *testing.T) {
}
time.Sleep(100 * time.Millisecond)
}
+ if strings.Contains(tap.String(), "box-1: tunnel dial: tunnel register: 401") {
+ t.Fatalf("box-1's first dial was refused: the hub had not loaded its token yet; the log:\n%s", tap.String())
+ }
// --- step 2: the gate, through the hub's TLS listener -------------------
+ // The fleet edge draws the login form, not the hub: the one request is
+ // metered on both edges, so it crossed the tunnel to be answered.
+ hubMeter.Drain()
+ boxMeter.Drain()
resp, page := hubURL.mustDo(http.MethodGet, shopHost, "/up", nil, nil)
if !isLoginForm(resp, page) {
t.Fatalf("GET /up = %d %q, want the fleet edge's login form", resp.StatusCode, page)
}
+ if h, b := hubMeter.Drain()[shopHost], boxMeter.Drain()[shopHost]; h.Requests != 1 || b.Requests != 1 {
+ t.Fatalf("the login form's request was metered %d times on the hub and %d on the box, want once on each: the box draws the form", h.Requests, b.Requests)
+ }
resp, body := hubURL.login(shopHost, page, "not the password")
if resp.StatusCode != http.StatusUnauthorized || !strings.Contains(body, "That password is not right.") || len(resp.Cookies()) != 0 {
t.Fatalf("wrong password = %d %v %q, want the wrong-password page and no cookie", resp.StatusCode, resp.Cookies(), body)
@@ -593,6 +606,7 @@ func TestFleetAppServesThroughTheHub(t *testing.T) {
oks := 0
var refused *http.Response
var refusedBody string
+ started := time.Now()
for i := 0; i < 12 && refused == nil; i++ {
resp, body := hubURL.mustDo(http.MethodGet, shopHost, "/limited", nil, withCookie)
switch {
@@ -604,8 +618,16 @@ func TestFleetAppServesThroughTheHub(t *testing.T) {
t.Fatalf("GET /limited %d = %d %q, want the app's 200 or the hub's 429", i+1, resp.StatusCode, body)
}
}
- if refused == nil || oks < 5 {
- t.Fatalf("%d answered before a refusal (%v), want the burst of 5 and then a 429", oks, refused != nil)
+ // The limiter runs on the wall clock and refills one token a second, so
+ // the ceiling is the burst plus what the loop's own duration refilled,
+ // rounded up (Astra followups R1 P2-2): a slow scheduler earns the hub
+ // more admissions, never a failure here. The exact burst is pinned on a
+ // frozen clock in internal/edge (TestForwardRateLimitAtTheHubOnly).
+ const burst, rate = 5, 1
+ ceiling := burst + int(math.Ceil(rate*time.Since(started).Seconds()))
+ if refused == nil || oks < burst || oks > ceiling {
+ t.Fatalf("%d answered before a refusal (%v), want the burst of %d and at most %d (the burst plus refill over %s), then a 429",
+ oks, refused != nil, burst, ceiling, time.Since(started).Round(time.Millisecond))
}
if refused.Header.Get("Retry-After") == "" || refused.Header.Get("Cache-Control") != "no-store" ||
refusedBody != "Too many requests. Try again in a moment." {
@@ -622,21 +644,20 @@ func TestFleetAppServesThroughTheHub(t *testing.T) {
const parent = "shops.example.com"
mustCarlos("domains", "attach", "--app", "shop", "--account", owner, parent)
mustCarlos("domains", "attach", "--app", "shop", "--account", owner, "*."+parent)
- aliasPass := func(s release.Store, reg *registry.Registry, hubSide bool) domains.AliasReport {
+ aliasPass := func(s release.Store, reg *registry.Registry, env func(string) string, hubSide bool) domains.AliasReport {
t.Helper()
// What the agent's alias pass (aliasPassReporting) hands the
- // domains package: the deployment's routes from the edges files, and
- // the edge's own fleet-arm refusals over the listing.
+ // domains package: the deployment's routes from the edges files,
+ // the box's region from the pass config it runs under, and the
+ // edge's own fleet-arm refusals over the listing, judged by the
+ // owners the edge reads (Registry.FleetOwners).
deploymentRoutes, whole := edgesfile.DeploymentRoutesComplete(ctx, s, time.Now())
- fleets, err := reg.ListFleets()
+ owners, err := reg.FleetOwners()
if err != nil {
t.Fatal(err)
}
- owners := map[string]string{}
- for _, f := range fleets {
- owners[f.Name] = f.Account
- }
rep := domains.AliasReport{DeploymentRoutesPartial: deploymentRoutes != nil && !whole,
+ Region: host.BoxProvisionConfig(reg, env, nil, nil).Region,
FleetRefused: func(routes []registry.Route) map[string]string {
return edge.FleetArmVerdict(routes, owners, hubSide, hubSide).Refused
}}
@@ -646,12 +667,12 @@ func TestFleetAppServesThroughTheHub(t *testing.T) {
return rep
}
hubPass()
- aliasPass(store, hubReg, true)
+ aliasPass(store, hubReg, hubEnv, true)
if err := hub.Reload(); err != nil {
t.Fatal(err)
}
boxPass()
- aliasPass(boxStore, boxReg, false)
+ aliasPass(boxStore, boxReg, boxEnv, false)
if err := box.Reload(); err != nil {
t.Fatal(err)
}
@@ -710,6 +731,9 @@ func TestFleetAppServesThroughTheHub(t *testing.T) {
boxPass() // the box's pass runs over the door with its new token
// --- step 6: trash the app ----------------------------------------------
+ if err := hubURL.handshake(slugHost); err != nil {
+ t.Fatalf("before the trash, a TLS handshake with SNI %s: %v, want it admitted (the catch-all's name serves)", slugHost, err)
+ }
mustCarlos("apps", "delete", "--account", owner, "shop")
if rt, err := hubReg.Get(shopHost); err != nil || rt == nil || !rt.IsForward() {
t.Fatalf("before the hub's pass, the row at %s = %+v (%v), want the forward row still there: only the hub's pass retires it", shopHost, rt, err)
@@ -721,6 +745,11 @@ func TestFleetAppServesThroughTheHub(t *testing.T) {
if err := hubURL.handshake(shopHost); err == nil {
t.Fatalf("a fresh TLS handshake with SNI %s succeeded after the app was trashed, want it refused", shopHost)
}
+ // The catch-all's name goes with its primary, at once: the hub's alias
+ // pass has not run since, so its alias row still names the gone row.
+ if err := hubURL.handshake(slugHost); err == nil {
+ t.Fatalf("a fresh TLS handshake with SNI %s (the instance catch-all's name) succeeded after the app was trashed, want it refused", slugHost)
+ }
// --- step 7: another account's record on this fleet ---------------------
// No row and no admission. Whether the host reaches the hub's edges file
diff --git a/internal/console/regionfacts.go b/internal/console/regionfacts.go
index fd02869aa..9bedc4f54 100644
--- a/internal/console/regionfacts.go
+++ b/internal/console/regionfacts.go
@@ -108,31 +108,32 @@ func (f appRegionFacts) SourceSentence() string {
}
// legacyFleetFromRoutes is the placement an app placed by an older build
-// carries only in its rows: fleetFromRoutes over the rows that can carry
-// one. A forward row is skipped (fleet public routes, controller ruling 1):
-// the hub mints it from a record already placed, and retires it only on its
-// next pass after the record leaves the fleet, so it is never a legacy
-// placement, and reading it after an unplace would hand the app its old
-// fleet back. appPlacement, the startup backfill and fleetPlacedApps read
-// this; the display readers keep fleetFromRoutes.
+// carries only in its rows: the first fleet placement among sqid/app's rows
+// that can carry one. A forward row is skipped (fleet public routes,
+// controller ruling 1): the hub mints it from a record already placed, and
+// retires it only on its next pass after the record leaves the fleet, so it
+// is never a legacy placement, and reading it after an unplace would hand
+// the app its old fleet back. appPlacement, the startup backfill and
+// fleetPlacedApps read this; the display readers keep fleetFromRoutes.
func legacyFleetFromRoutes(routes []registry.Route, sqid, app string) string {
- for _, rt := range routes {
- if rt.IsForward() || rt.Account != sqid || rt.App != app {
- continue
- }
- if _, ok := registry.FleetPlacement(rt.Region); ok {
- return rt.Region
- }
- }
- return ""
+ return firstFleetPlacement(routes, sqid, app, true)
}
-// fleetFromRoutes is appPlacement's legacy fallback over rows already
-// listed: the first fleet placement among sqid/app's rows, compared on the
-// raw account column exactly as appPlacement always has (fleets.go).
+// fleetFromRoutes is the display readers' fold over rows already listed
+// (the app view, the temporary-apps list, region facts): the first fleet
+// placement among sqid/app's rows, a forward row's included. appPlacement's
+// own fallback is legacyFleetFromRoutes, which skips forward rows.
func fleetFromRoutes(routes []registry.Route, sqid, app string) string {
+ return firstFleetPlacement(routes, sqid, app, false)
+}
+
+// firstFleetPlacement is the one loop behind both folds: the first fleet
+// placement among sqid/app's rows, compared on the raw account column
+// exactly as appPlacement always has (fleets.go), forward rows skipped when
+// skipForward is set.
+func firstFleetPlacement(routes []registry.Route, sqid, app string, skipForward bool) string {
for _, rt := range routes {
- if rt.Account != sqid || rt.App != app {
+ if (skipForward && rt.IsForward()) || rt.Account != sqid || rt.App != app {
continue
}
if _, ok := registry.FleetPlacement(rt.Region); ok {
diff --git a/internal/console/regionfacts_test.go b/internal/console/regionfacts_test.go
index 3c7fe1011..d6fd70db7 100644
--- a/internal/console/regionfacts_test.go
+++ b/internal/console/regionfacts_test.go
@@ -91,6 +91,28 @@ func TestFleetFromRoutesIsAppPlacementsFallback(t *testing.T) {
}
}
+// TestFleetFromRoutesSplitOnForwardRows pins the one difference between the
+// two folds over listed rows (fleet public routes, controller ruling 1): the
+// display fold, fleetFromRoutes, reads a forward row's placement like any
+// row's; appPlacement's legacy fold, legacyFleetFromRoutes, skips it, since
+// a forward row is never a legacy placement. Both read only sqid/app's rows.
+func TestFleetFromRoutesSplitOnForwardRows(t *testing.T) {
+ routes := []registry.Route{
+ {Host: "other.example.com", Kind: "instance", App: "shop", Account: "baj", Region: "fleet/theirs"},
+ {Host: "shop.example.com", Kind: registry.KindForward, App: "shop", Account: "bah", Region: "fleet/home"},
+ }
+ if got := fleetFromRoutes(routes, "bah", "shop"); got != "fleet/home" {
+ t.Errorf("fleetFromRoutes = %q, want fleet/home from the forward row", got)
+ }
+ if got := legacyFleetFromRoutes(routes, "bah", "shop"); got != "" {
+ t.Errorf("legacyFleetFromRoutes = %q, want empty: a forward row is not a legacy placement", got)
+ }
+ routes = append(routes, registry.Route{Host: "legacy.example.com", Kind: "instance", App: "shop", Account: "bah", Region: "fleet/private"})
+ if got := legacyFleetFromRoutes(routes, "bah", "shop"); got != "fleet/private" {
+ t.Errorf("legacyFleetFromRoutes = %q, want fleet/private from the instance row", got)
+ }
+}
+
func TestRegistryRoutesSeamAndFailure(t *testing.T) {
fx := newConsoleFixture(t)
fx.srv.listRoutes = func() ([]registry.Route, error) { return nil, errors.New("registry unreadable") }
diff --git a/internal/console/sealkey.go b/internal/console/sealkey.go
index 26bf69a1a..c02575d0a 100644
--- a/internal/console/sealkey.go
+++ b/internal/console/sealkey.go
@@ -198,10 +198,11 @@ func (s *Server) deploymentSealKey() (*ecdh.PublicKey, error) {
// backfillAppPlacements writes the placement column from routes for every
// live app whose column is empty and whose routes say fleet/<f>
-// (legacyFleetFromRoutes, which skips forward rows), so the column becomes the one authority (spec §5.2 step
-// 2). It does not change any answer appPlacement gives: appPlacement already
-// falls back to the same routes for those apps. That is why it need not
-// finish before the first seal (plan ruling R-1).
+// (legacyFleetFromRoutes, which skips forward rows), so the column becomes
+// the one authority (spec §5.2 step 2). It does not change any answer
+// appPlacement gives: appPlacement already falls back to the same routes
+// for those apps. That is why it need not finish before the first seal
+// (plan ruling R-1).
//
// One route listing picks the candidates. Each candidate is then decided
// again under the account lock and its app lock, the lock placeAppTarget
diff --git a/internal/console/view.go b/internal/console/view.go
index 233b9986d..b74dd8b42 100644
--- a/internal/console/view.go
+++ b/internal/console/view.go
@@ -42,8 +42,8 @@ type AppView struct {
// as the console shows it — see ProductionView.
Production ProductionView
// routeFleet is the first fleet placement among this app's rows in the
- // console box's registry (fleetFromRoutes): appPlacement's legacy
- // fallback, folded from the listing Assemble already made.
+ // console box's registry (fleetFromRoutes, the display fold, forward
+ // rows included), folded from the listing Assemble already made.
routeFleet string
// RouteAccount is the account the app's ROUTES say it belongs to, when
// that disagrees with the account whose page this is; "" when they agree
diff --git a/internal/edge/edge.go b/internal/edge/edge.go
index a953c2455..f6a9f8421 100644
--- a/internal/edge/edge.go
+++ b/internal/edge/edge.go
@@ -757,11 +757,12 @@ func (e *Edge) Reload() error {
//
// The store door's tenancy map comes from the SAME pass: a box's
// credentials and the account its reads are scoped to must never come
- // from two different reads of the registry. ListFleets goes over a fresh
- // connection (like FleetChannelAuth), so a fleet the console created
- // moments ago is visible here rather than stuck behind a stale WAL
- // snapshot on the long-lived handle. The same map is the owners map the
- // eligibility rule reads.
+ // from two different reads of the registry. FleetOwners (ListFleets)
+ // goes over a fresh connection (like FleetChannelAuth), so a fleet the
+ // console created moments ago is visible here rather than stuck behind a
+ // stale WAL snapshot on the long-lived handle. The same map is the
+ // owners map the eligibility rule reads, folded as the hub's forward
+ // phase folds it.
//
// hub is the one hub test (HubArmed, shared with the agent's bindings
// pass and the edges-file writer) on a box whose tunnels are enabled.
@@ -782,14 +783,10 @@ func (e *Edge) Reload() error {
if err != nil {
return err
}
- fleets, err := e.reg.ListFleets()
+ owners, err = e.reg.FleetOwners()
if err != nil {
return err
}
- owners = make(map[string]string, len(fleets))
- for _, f := range fleets {
- owners[f.Name] = f.Account
- }
hub = HubArmed(os.Getenv)
}
verdict := FleetArmVerdict(routes, owners, hub, e.tunnels != nil)
diff --git a/internal/edge/fleetforward_policy_test.go b/internal/edge/fleetforward_policy_test.go
index 6ac865621..72bc8e0ea 100644
--- a/internal/edge/fleetforward_policy_test.go
+++ b/internal/edge/fleetforward_policy_test.go
@@ -13,6 +13,8 @@ package edge
import (
"bufio"
+ "context"
+ "errors"
"fmt"
"io"
"net"
@@ -84,29 +86,46 @@ func (b *polBackend) counts() (gets, upgrades int) {
// polHost carries polHubRate, the box's own row polBoxRate, and both edges'
// limiters are on a frozen clock.
func policyScene(t *testing.T) (hubURL string, hub, box *Edge, app *polBackend) {
+ t.Helper()
+ return policySceneRates(t, polHubRate, polBoxRate)
+}
+
+// policySceneRates is policyScene with the two rows' rate limits given, so a
+// plan-throttle test can keep the per-instance limit out of its way. Both
+// edges' plan limiters are on the same frozen clock as their rate limiters.
+func policySceneRates(t *testing.T, hubRate, boxRate string) (hubURL string, hub, box *Edge, app *polBackend) {
t.Helper()
t.Setenv("CARLOS_RATE_LIMIT", "enforce")
app = &polBackend{closed: make(chan struct{}, 8)}
appAddr := startPolBackend(t, app)
fwd := forwardRow(polHost, "home", fwdOwner)
- fwd.RateLimit = polHubRate
+ fwd.RateLimit = hubRate
hubURL, hub, box = forwardHubAndBox(t, []registry.Route{fwd},
- []registry.Route{{Host: polHost, Kind: "instance", Status: "ready", Addr: appAddr, Account: fwdOwner, App: "shop", RateLimit: polBoxRate}},
+ []registry.Route{{Host: polHost, Kind: "instance", Status: "ready", Addr: appAddr, Account: fwdOwner, App: "shop", RateLimit: boxRate}},
nil)
for name, e := range map[string]*Edge{"hub": hub, "box": box} {
if e.rateMode != RateEnforce {
t.Fatalf("the %s's rate mode is %v, want enforce", name, e.rateMode)
}
}
- if got := hub.current()[polHost].rate; got.Burst != 2 {
- t.Fatalf("the hub's forward row parsed to %+v, want burst 2 (the row's RateLimit)", got)
- }
- if got := box.current()[polHost].rate; got.Burst != 1 {
- t.Fatalf("the box's row parsed to %+v, want burst 1", got)
+ for _, c := range []struct {
+ name string
+ e *Edge
+ col string
+ }{{"hub's forward row", hub, hubRate}, {"box's row", box, boxRate}} {
+ want, err := ratelimit.Parse(c.col)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if got := c.e.current()[polHost].rate; got.Burst != want.Burst {
+ t.Fatalf("the %s parsed to %+v, want burst %d (the row's RateLimit)", c.name, got, want.Burst)
+ }
}
frozen := time.Date(2026, 10, 30, 12, 0, 0, 0, time.UTC)
- hub.rateLimiter = ratelimit.NewLimiter(func() time.Time { return frozen }, 1000)
- box.rateLimiter = ratelimit.NewLimiter(func() time.Time { return frozen }, 1000)
+ for _, e := range []*Edge{hub, box} {
+ e.rateLimiter = ratelimit.NewLimiter(func() time.Time { return frozen }, 1000)
+ e.planLimiter = ratelimit.NewLimiter(func() time.Time { return frozen }, 1000)
+ }
return hubURL, hub, box, app
}
@@ -257,3 +276,90 @@ func TestForwardPlanThrottleAndUpgradeClose(t *testing.T) {
t.Fatalf("CloseAccountUpgrades after the handshake ended closed %d, want 0", n)
}
}
+
+// polWideRate keeps the per-instance limit out of a plan-throttle test's
+// way: a burst far above plans.ThrottleRule's, on both rows.
+const polWideRate = `{"rate":1,"burst":500}`
+
+// TestForwardPlanThrottlePlainHTTPAtTheHub (deferred minor, Task 5): a plain
+// request to a forward row spends the account's plan-throttle bucket at the
+// hub. The rule's burst is admitted and reaches the app; the next request is
+// the hub's 429 and never crosses the tunnel.
+func TestForwardPlanThrottlePlainHTTPAtTheHub(t *testing.T) {
+ hubURL, hub, _, app := policySceneRates(t, polWideRate, polWideRate)
+ hub.SetPlanThrottleFor(func(rt registry.Route) (plans.Throttle, bool) {
+ if rt.Account != fwdOwner {
+ return plans.Throttle{}, false
+ }
+ return plans.Throttle{Bandwidth: true, Until: time.Now().Add(time.Hour)}, true
+ })
+ for i := 1; i <= plans.ThrottleRule.Burst; i++ {
+ resp, body := fwdDo(t, hubURL, "GET", polHost, "/", "", nil)
+ if resp.StatusCode != http.StatusOK || string(body) != "ok" {
+ t.Fatalf("GET %d: %d %q, want the app's 200 within the plan throttle's burst of %d", i, resp.StatusCode, body, plans.ThrottleRule.Burst)
+ }
+ }
+ resp, body := fwdDo(t, hubURL, "GET", polHost, "/", "", nil)
+ wantHubRefusal(t, resp, string(body), "a GET past the plan throttle's burst")
+ if gets, _ := app.counts(); gets != plans.ThrottleRule.Burst {
+ t.Fatalf("the app saw %d requests, want %d: the refused one never crosses the tunnel", gets, plans.ThrottleRule.Burst)
+ }
+}
+
+// TestForwardPlanThrottleExemptsTheTunnelAtTheBox (deferred minor, Task 5):
+// the fleet box keeps exempting what arrives over the tunnel from the plan
+// throttle (planThrottleOf's fromTunnel), so a throttle the box holds for
+// the account does not judge the hub's forwarded requests a second time. The
+// hub holds none here: every request past the rule's burst still reaches the
+// app.
+func TestForwardPlanThrottleExemptsTheTunnelAtTheBox(t *testing.T) {
+ hubURL, _, box, app := policySceneRates(t, polWideRate, polWideRate)
+ box.SetPlanThrottleFor(func(rt registry.Route) (plans.Throttle, bool) {
+ if rt.Account != fwdOwner {
+ return plans.Throttle{}, false
+ }
+ return plans.Throttle{Bandwidth: true, Until: time.Now().Add(time.Hour)}, true
+ })
+ n := plans.ThrottleRule.Burst + 5
+ for i := 1; i <= n; i++ {
+ resp, body := fwdDo(t, hubURL, "GET", polHost, "/", "", nil)
+ if resp.StatusCode != http.StatusOK || string(body) != "ok" {
+ t.Fatalf("GET %d: %d %q, want the app's 200: the box must not plan-throttle a tunneled request", i, resp.StatusCode, body)
+ }
+ }
+ if gets, _ := app.counts(); gets != n {
+ t.Fatalf("the app saw %d requests, want %d", gets, n)
+ }
+}
+
+// TestForwardUpgradeCloseCancelsTheRequest (deferred minor, Task 5):
+// CloseAccountUpgrades does not only count a forward row's tracked upgrade,
+// it cancels the context of the request it tracked, which is what ends the
+// proxied connection. Driven directly, since no upgrade stays open across the
+// tunnel (#471).
+func TestForwardUpgradeCloseCancelsTheRequest(t *testing.T) {
+ _, hub, _, _ := policyScene(t)
+ hub.SetPlanGovernedFor(func(rt registry.Route) bool { return rt.Account == fwdOwner })
+ up := hub.current()[polHost]
+ if !up.route.IsForward() {
+ t.Fatalf("the hub's row for %s is %+v, want its forward row", polHost, up.route)
+ }
+ req, err := http.NewRequest("GET", "http://"+polHost+"/socket", nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ tracked, done := hub.trackUpgrade(req, up)
+ defer done()
+ if tracked.Context().Err() != nil {
+ t.Fatalf("the tracked request is done before any close: %v", tracked.Context().Err())
+ }
+ if n := hub.CloseAccountUpgrades(fwdOwner); n != 1 {
+ t.Fatalf("CloseAccountUpgrades(%q) = %d, want 1", fwdOwner, n)
+ }
+ if err := tracked.Context().Err(); !errors.Is(err, context.Canceled) {
+ t.Fatalf("after CloseAccountUpgrades the tracked request's context is %v, want canceled", err)
+ }
+ if req.Context().Err() != nil {
+ t.Fatal("CloseAccountUpgrades cancelled the caller's own context, not the tracked one")
+ }
+}
diff --git a/internal/edge/ratelimit.go b/internal/edge/ratelimit.go
index 10a08a268..a111d3601 100644
--- a/internal/edge/ratelimit.go
+++ b/internal/edge/ratelimit.go
@@ -117,12 +117,12 @@ func (e *Edge) parseRateSettings(rt registry.Route) ratelimit.Settings {
//
// Not judged: anything but an instance or a forward row (fleet public
// routes §4.8: the hub judges a forward row once, with the app's own
-// settings from the row's rate_limit column), a door caller (the box itself, on
-// this box or on the box that backhauled it, hopDoorFrom), and a request
-// that arrived over a fleet tunnel. On the fleet side of a tunnel every
-// request comes from the hub, so keying on it would put every client in one
-// bucket; the hub has the route row and the real client, and limits there
-// (its route is viaTunnel).
+// settings from the row's rate_limit column), a door caller (the box
+// itself, on this box or on the box that backhauled it, hopDoorFrom), and a
+// request that arrived over a fleet tunnel. On the fleet side of a tunnel
+// every request comes from the hub, so keying on it would put every client
+// in one bucket; the hub has the route row and the real client, and limits
+// there (its route is viaTunnel).
func (e *Edge) rateAdmit(w http.ResponseWriter, r *http.Request, up upstream) (release func(), ok bool) {
if e.rateMode == RateOff || (up.route.Kind != "instance" && !up.route.IsForward()) {
return nil, true
diff --git a/internal/host/fleet_forward_budget_test.go b/internal/host/fleet_forward_budget_test.go
index a366d2aba..d1e7502df 100644
--- a/internal/host/fleet_forward_budget_test.go
+++ b/internal/host/fleet_forward_budget_test.go
@@ -60,9 +60,11 @@ func TestBoxProvisionConfigArmsForwardingOnTheHubOnly(t *testing.T) {
if err != nil {
t.Fatal(err)
}
- // Parity: the owners the edge's fleet arm, the edges file and the alias
- // pass judge by on this box (fleetArmInputs), so the phase never mints a
- // row the hub's edge refuses for want of an owner, nor the reverse.
+ // Parity: the owners the edges file and the alias pass judge by on this
+ // box (fleetArmInputs) are the phase's own read. The edge's Reload reads
+ // the fleets table itself, so it can trail them by one pass; it
+ // converges on its next reload and fails closed meanwhile, serving a
+ // forward row only on its own read of the owner (hubFleetOwners).
edgeOwners, edgeHub, tunnels, err := fleetArmInputs(reg, hub)
if err != nil {
t.Fatal(err)
@@ -94,7 +96,10 @@ func TestBoxProvisionConfigArmsForwardingOnTheHubOnly(t *testing.T) {
}
// budgetStore counts every call made through it by operation and key while
-// counting is on.
+// counting is on. It embeds release.Store, so it hides every optional
+// interface the DirStore below has (release.ConditionalGetter, ETagLister,
+// ModLister, SizeLister, PageLister and Opener among them): each reader
+// that asks for one takes its fallback path here, on both hubs alike.
type budgetStore struct {
release.Store
mu sync.Mutex
@@ -287,8 +292,11 @@ func (w *budgetWorld) passSet(t *testing.T, cfg provision.ReconcileConfig) {
// nothing (the hub as it is today, settled), then two with the forward
// phase as armed says. It returns the calls of the first of those (where a
// forward row first appears) and of the second (steady state: nothing
-// changing).
-func budgetRun(t *testing.T, c budgetCase, armed bool) (first, steady map[string]int, reg *registry.Registry) {
+// changing). Then it deletes the fleet app's records and returns the calls
+// of one more pass set (gone: where the armed hub retires the rows). On an
+// armed world it checks a forward row stands at each host before the
+// deletion and none after.
+func budgetRun(t *testing.T, c budgetCase, armed bool) (first, steady, gone map[string]int) {
t.Helper()
w := newBudgetWorld(t, c)
cfg := BoxProvisionConfig(w.reg, func(k string) string {
@@ -315,7 +323,26 @@ func budgetRun(t *testing.T, c budgetCase, armed bool) (first, steady map[string
}
first = w.s.count(func() { w.passSet(t, cfg) })
steady = w.s.count(func() { w.passSet(t, cfg) })
- return first, steady, w.reg
+ if armed {
+ for _, h := range c.shopHosts {
+ rt, err := w.reg.Get(h)
+ if err != nil || rt == nil || !rt.IsForward() {
+ t.Fatalf("the armed hub holds no forward row at %s (%+v, %v): the comparison measures nothing", h, rt, err)
+ }
+ }
+ }
+ for _, h := range c.shopHosts {
+ if err := provision.DeleteRecord(context.Background(), w.s, fpOwner, "shop", h); err != nil {
+ t.Fatalf("delete record %s: %v", h, err)
+ }
+ }
+ gone = w.s.count(func() { w.passSet(t, cfg) })
+ for _, h := range c.shopHosts {
+ if rt, err := w.reg.Get(h); err != nil || rt != nil {
+ t.Fatalf("after the records went the hub still holds %+v at %s (%v)", rt, h, err)
+ }
+ }
+ return first, steady, gone
}
// writes is how many PUTs and DELETEs calls holds.
@@ -376,7 +403,16 @@ func showCalls(m map[string]int) string {
// (C = 1: no other row of the owner's is on the hub). Bindings, build
// states, retention, canary status, the domains pass and the alias pass
// without a catch-all: unchanged. The edges file: one PUT when the row
-// appears, none in steady state.
+// appears, none in steady state, and one when the row goes (the app's
+// records deleted, the phase retires the row).
+//
+// The numbers hold for the store this test counts through, as the telemetry
+// rows hold for the index off: budgetStore hides the store's optional
+// interfaces, so every reader that would use one (a conditional GET, an
+// ETag or modification-time listing, a paged listing) runs its fallback, on
+// the dormant hub and the armed one alike. A production store that has them
+// can make other calls than these on both hubs; the difference between the
+// two is what this test pins.
//
// Two more cases (R3-2): an instance catch-all claim for shop adds one List
// of the app's instance records per alias pass (K = 1); two of shop's
@@ -426,14 +462,8 @@ func TestForwardRequestBudget(t *testing.T) {
twoHosts},
} {
t.Run(tc.name, func(t *testing.T) {
- beforeFirst, before, _ := budgetRun(t, tc.c, false)
- afterFirst, after, reg := budgetRun(t, tc.c, true)
- for _, h := range tc.c.shopHosts {
- rt, err := reg.Get(h)
- if err != nil || rt == nil || !rt.IsForward() {
- t.Fatalf("the armed hub holds no forward row at %s (%+v, %v): the comparison measures nothing", h, rt, err)
- }
- }
+ beforeFirst, before, beforeGone := budgetRun(t, tc.c, false)
+ afterFirst, after, afterGone := budgetRun(t, tc.c, true)
if got := callDiff(before, after); !reflect.DeepEqual(got, tc.want) {
t.Errorf("steady-state difference per pass set:%s\nwant:%s", showCalls(got), showCalls(tc.want))
}
@@ -454,6 +484,10 @@ func TestForwardRequestBudget(t *testing.T) {
if b, a := edgesPuts(beforeFirst), edgesPuts(afterFirst); a != b+1 {
t.Errorf("edges file PUTs on the pass the forward row appears: %d, want %d (one more than the dormant hub's)%s", a, b+1, showCalls(callDiff(beforeFirst, afterFirst)))
}
+ // The pass where the forward row goes: one more PUT again.
+ if b, a := edgesPuts(beforeGone), edgesPuts(afterGone); a != b+1 {
+ t.Errorf("edges file PUTs on the pass the forward row goes: %d, want %d (one more than the dormant hub's)%s", a, b+1, showCalls(callDiff(beforeGone, afterGone)))
+ }
})
}
}
diff --git a/internal/host/hub.go b/internal/host/hub.go
index f67dda28a..29c3f183f 100644
--- a/internal/host/hub.go
+++ b/internal/host/hub.go
@@ -39,19 +39,22 @@ func fleetArmInputs(reg *registry.Registry, getenv func(string) string) (owners
// routes spec §4.3): each fleet in this box's own fleets table with its
// owning account, read afresh on each call, so a loop that builds its config
// once still sees every fleet created or deleted since. It is also where
-// fleetArmInputs reads the owners the edge's fleet arm, the edges file and
-// the alias pass judge by, so the forward phase and the edge cannot disagree
-// about who owns a fleet.
+// fleetArmInputs reads the owners the edges file and the alias pass judge
+// by, so the forward phase and those two read the same table the same way.
+//
+// The edge's Reload reads the table itself (the same FleetOwners), so for
+// one pass after a fleet is created, deleted or changes owner the phase and
+// the edge can disagree. They converge on their next reads, and the
+// disagreement fails closed: the edge serves a forward row only when its own read names
+// the row's account as the fleet's owner, so a row the phase minted first
+// is refused until the edge reads the same, and a row the phase has not yet
+// retired is refused once the edge's read stops naming that owner.
func hubFleetOwners(reg *registry.Registry) func() (map[string]string, error) {
return func() (map[string]string, error) {
- fleets, err := reg.ListFleets()
+ owners, err := reg.FleetOwners()
if err != nil {
return nil, fmt.Errorf("list fleets: %w", err)
}
- owners := make(map[string]string, len(fleets))
- for _, f := range fleets {
- owners[f.Name] = f.Account
- }
return owners, nil
}
}
diff --git a/internal/provision/testdata/plan14-root-reads-chain.tsv b/internal/provision/testdata/plan14-root-reads-chain.tsv
index 4005745f0..1ab671e64 100644
--- a/internal/provision/testdata/plan14-root-reads-chain.tsv
+++ b/internal/provision/testdata/plan14-root-reads-chain.tsv
@@ -42,3 +42,4 @@ plan14-root-reads-analytics-agents.tsv 5b559ba7a42084908cb0fec08083bb2b9b3c9d960
plan14-root-reads-region-ha-dead-holder-backoff.tsv 8f6a1865b0abcea9d4fb68232cc2a25263a106ec87f73bd4b3f2fb388971ebe5
plan14-root-reads-managed-fleets-1c-451.tsv af326671321edda76c7e6217a47892605a9e3b886fa880ad6d049c2f28f63873
plan14-root-reads-fleet-public-routes.tsv bca6ef741a96b72767b1747789cd01b3111d61b68548cbe368258c31f3d53a2e
+plan14-root-reads-fleet-routes-followups.tsv 1379d066c8dd2335d95d5f6e9c7bce65ff57f00b2b287a308d9b3f47911ae5e7
diff --git a/internal/provision/testdata/plan14-root-reads-fleet-routes-followups.tsv b/internal/provision/testdata/plan14-root-reads-fleet-routes-followups.tsv
new file mode 100644
index 000000000..55d895ca3
--- /dev/null
+++ b/internal/provision/testdata/plan14-root-reads-fleet-routes-followups.tsv
@@ -0,0 +1,17 @@
+# Census overlay fleet-routes-followups, written by census-propose (#369). census-ruling-fleet-routes-followups, approved on #280 before the merge; the approval card is docs/superpowers/notes/census-proposal-fleet-routes-followups.md.
+# 0 body, 2 sites, 3 envelope: each changed unit re-frozen at its existing disposition with its claim appended.
+# 4 new dispositions: 1 reads re-frozen at their disposition with the claim, 1 new units frozen accepted-legacy, 1 quiet units retired while they read nothing, 1 other.
+@legacy 1390307beb444f133a32c53182280cf12b141d7625a291e9369e73c34bd1de00 internal/registry/fleets.go Registry.FleetOwners legacy accepted-legacy accepted-legacy;rev3=census-ruling-fleet-routes-followups;basis=new: ListFleets folded to fleet name -> owning account (reads Fleet.Name and Fleet.Account), the fold Edge.Reload and hubFleetOwners each did inline; no new query, connection or remote method (ListFleets is unchanged) registry:Account@226,registry:Name@216,whole:Fleet@170,whole:Fleet@198 65f9562910b29675b8c48338d888ecd7210017228fe28245d9c1c21c8a5fb8b2
+@legacy 113b7211acd13e4de3aa2f9dd2a872519e10515cbc62e92d34564f902c3cb084 internal/registry/forward.go var putForwardSQL legacy accepted-legacy accepted-legacy;rev3=census-ruling-fleet-public-routes;basis=fleet public routes (spec 2026-10-29 rev 4, §4.2 writer rule): Task 2: PutForward's statement, its conflict arm built once from the ForwardForbidden literal (+registry:Column, +registry:Type, +whole:ForwardColumn); reads only a package literal.;rev3=census-ruling-fleet-routes-followups;basis=the conflict arm is built from the package literal forwardKept (column, OnConflict) plus ForwardForbidden instead of an inline string list; the generated SQL assigns the same columns the same values as before (checked by TestPutForwardSetsEveryColumnButHost against PRAGMA); reads only package literals registry:Column@182,registry:Column@336,registry:OnConflict@140,registry:OnConflict@197,registry:Type@276,whole:ForwardColumn@237,whole:ForwardColumn@83,whole:forwardKeptColumn@121,whole:forwardKeptColumn@66 4df872e1a8d3dd06ac717a88fe32e2cafd12fae4b7d63bd34d340537268f585e
+@legacy 9f1fa7dcf03a9ab26cb80edef4a65a8d62c7922495b21e722e283db14e4537b6 internal/edge/edge.go Edge.Reload legacy accepted-legacy accepted-legacy;rev3=J1;basis=root-route;rev3=census-ruling-design-edge-rate-limit-358;basis=each route's upstream entry gains rate: e.parseRateSettings(t), the row's rate_limit column parsed once per reload; the one added site is that whole:Route pass of t (parseRateSettings is a new unit, classified in the decisions overlay); no other read added;rev3=census-ruling-certwarm-wake;basis=the single reload hook call becomes runReloadHooks(), which runs every registered hook in order (#386); no read added, same 57 sites (56 before #358 landed on main);rev3=census-ruling-edge-asset-cache-3;basis=each tenant reverse proxy built in the switch (the tunnel, fleet, socket and TCP arms, every *httputil.ReverseProxy) is installed behind assetScrubbedProxy, which hands the proxy an assetInformationalScrub writer so an app's 1xx (103) loses the asset cache's reserved headers (X-Carlos-Asset-Fill, -Fill-Ack, -Expires, Carlos-Cache) on every local path, as the backhaul already does (final review F6); a type check of the proxy it just built and a wrapper around it; static and status handlers untouched; read sites unchanged (57), offsets moved; no read added;rev3=census-ruling-alias-wake-338;basis=#338 follow-up: after the path fold, a resolved platform alias takes its source's own upstream entry (same proxy, route, hibernating: the existing activator wake, lease and fence), keeping its own prefix map (none for a minted apex) and never inheriting the source's (Astra r2 P1); a refused alias, or one whose source has no entry, is dropped from the map (not served, not Allowed); the attached-hostname fold clears platformAlias;rev3=census-ruling-rootfs-apps-3;basis=rootfs Plan 3 Task 5: the activator-managed test (generation proxy, hib, no-activator 404) is Route.ActivatorOwned instead of Kind and Hibernate inline, so a resident rootfs instance goes through the activator; binary rows unchanged;rev3=census-ruling-edge-roll-blip;basis=the tcpProxy and multiProxy calls pass e.hold (the per-Edge localHold set once in newEdge): a loopback TCP upstream that refuses is redialled for up to 13 s and a probed route with a local upstream waits for prober readmission instead of answering 502/503 (#434 part B); edge-side dial policy only, no read added, same 52 sites;rev3=census-ruling-regional-domains-447;basis=#447 Task 5: after the alias fold, reads the regional_domains rows (e.reg.ListRegional; an error aborts the reload as every registry read here does) and applies them with foldRegional against the routes slice the same reload read; the added reads are that one registry list and the routes already read;rev3=census-ruling-fleet-public-routes;basis=fleet public routes (spec 2026-10-29 rev 4, §4.2 writer rule): Tasks 4 and 6: the forward case (fleetProxy toward the binding's FleetBox, throttled refusal); one refusal check before the switch from FleetArmVerdict (sidecar not judged; a non-ready forward row refused; a forward row always judged by FleetServeEligible, any other row only where tunnels are on; an alias of a refused source refused with it); the accountless note; path rows of a forward host not folded; no alias folded onto a refused row; refusedHosts held through every fold. ListFleets and FleetChannelAuth read before the loop (+registry:FleetBox, +registry:Host x7, +whole:Route x3). Serving only; the hub's agent, not root. Review R1 finding 2: the switch reads verdict.Served (FleetArmVerdict) by host; the forward case and the fleet-placed case take their fleet from it (served.Fleet) instead of FleetPlacement(t.Region), and an admitted forward row not Served continues rather than falling through (+registry:Host, -registry:Region); the same rows take the same arms; no read added. Review R2: the switch is on DispatchArm(t, viaFleet, tunnels) (the order moved there unchanged: forward only when in Arm, own Tunnel, fleet, socket, addrs, static, status, else continue), the fleet cases read verdict.Arm (renamed from Served), and the platform-alias fold is foldPlatformAliases with the same take (source entry, own paths, alias marks) and the same refusal log (-registry:Kind x2, -registry:Socket, -registry:Tunnel, +whole:Route: those reads moved into DispatchArm); same rows, same arms, same entries; no read added.;rev3=census-ruling-fleet-routes-followups;basis=the owners map is now e.reg.FleetOwners() instead of ListFleets folded inline: the same fresh-connection ListFleets read and the same name->account map (-registry:Account, -registry:Name, -whole:Fleet x2 move into Registry.FleetOwners); no read added; same error path (abort the reload) registry:Alias@23545,registry:Alias@23632,registry:Alias@24212,registry:FleetBox@10371,registry:FleetBox@6410,registry:Health@12498,registry:Health@12624,registry:Host@10226,registry:Host@10283,registry:Host@10319,registry:Host@10920,registry:Host@13107,registry:Host@13202,registry:Host@13490,registry:Host@13516,registry:Host@13568,registry:Host@18021,registry:Host@19928,registry:Host@20236,registry:Host@20263,registry:Host@21064,registry:Host@21636,registry:Host@23966,registry:Host@24015,registry:Host@4537,registry:Host@4591,registry:Host@4641,registry:Host@5508,registry:Kind@16357,registry:Kind@16379,registry:Prefix@21611,registry:Socket@10984,registry:Socket@20244,registry:Status@4462,registry:Target@21623,registry:Tunnel@8842,registry:Version@16338,registry:Version@16440,whole:RegionalDomain@24682,whole:Route@10435,whole:Route@11040,whole:Route@130,whole:Route@13641,whole:Route@13705,whole:Route@13756,whole:Route@20296,whole:Route@20303,whole:Route@20399,whole:Route@21499,whole:Route@22667,whole:Route@24674,whole:Route@3217,whole:Route@3275,whole:Route@5537,whole:Route@6474,whole:Route@8904,whole:RouteAlias@23516,whole:RoutePath@21042 88586bab6777f8ba12797b1e8b8d5dad7ca3d0b29c4703039b0a56041f8db6d0
+@legacy 48da5748ec910f5f73c055224bd7b0521302ee49d73c31709d298aa3b14e7217 internal/registry/forward.go Registry.PutForward legacy accepted-legacy accepted-legacy;rev3=census-ruling-fleet-public-routes;basis=fleet public routes (spec 2026-10-29 rev 4, §4.2 writer rule): Task 2: the only writer of a forward row's declared columns: refuses an argument whose kind is not forward; copies only the declared fields from its argument (Status ready, Provisioned true; no forbidden column is ever written); inside one IMMEDIATE transaction refuses a host a non-forward row holds (ErrHostHeld); keeps FleetBox while Region is unchanged; preserves the observational columns (+file:Exec, +file:QueryRow, +registry:Account, App, Channel, RateLimit, Region, Slug, +registry:Host x3, +registry:Kind, +registry:remote x2, +whole:Route x3, +whole:remoteClient x2).;rev3=census-ruling-fleet-routes-followups;basis=refuses up front, with the new sentinel ErrNotForward and before any read or write, an rt that is not a forward row (as before, now a sentinel), has an empty Host, or whose Region is not a fleet placement (registry.FleetPlacement); +registry:Host x2 and +registry:Region x2 read only the argument in those checks; the transaction and statement are unchanged file:Exec@1166,file:QueryRow@942,registry:Account@693,registry:App@670,registry:Channel@746,registry:Host@197,registry:Host@234,registry:Host@419,registry:Host@594,registry:Host@996,registry:Kind@206,registry:RateLimit@773,registry:Region@428,registry:Region@720,registry:Region@84,registry:Slug@646,registry:remote@446,registry:remote@476,whole:Route@1199,whole:Route@531,whole:Route@539,whole:remoteClient@448,whole:remoteClient@478 e46e8df164ed32403309e37d8470bc4c96319890ccf66fc0d276e452fef7b8e2
+internal/registry/fleets.go Registry.FleetOwners legacy accepted-legacy accepted-legacy;rev3=census-ruling-fleet-routes-followups;basis=new: ListFleets folded to fleet name -> owning account (reads Fleet.Name and Fleet.Account), the fold Edge.Reload and hubFleetOwners each did inline; no new query, connection or remote method (ListFleets is unchanged) registry:Account@226,registry:Name@216,whole:Fleet@170,whole:Fleet@198 65f9562910b29675b8c48338d888ecd7210017228fe28245d9c1c21c8a5fb8b2
+internal/registry/forward.go var putForwardSQL legacy accepted-legacy accepted-legacy;rev3=census-ruling-fleet-public-routes;basis=fleet public routes (spec 2026-10-29 rev 4, §4.2 writer rule): Task 2: PutForward's statement, its conflict arm built once from the ForwardForbidden literal (+registry:Column, +registry:Type, +whole:ForwardColumn); reads only a package literal.;rev3=census-ruling-fleet-routes-followups;basis=the conflict arm is built from the package literal forwardKept (column, OnConflict) plus ForwardForbidden instead of an inline string list; the generated SQL assigns the same columns the same values as before (checked by TestPutForwardSetsEveryColumnButHost against PRAGMA); reads only package literals registry:Column@182,registry:Column@336,registry:OnConflict@140,registry:OnConflict@197,registry:Type@276,whole:ForwardColumn@237,whole:ForwardColumn@83,whole:forwardKeptColumn@121,whole:forwardKeptColumn@66 4df872e1a8d3dd06ac717a88fe32e2cafd12fae4b7d63bd34d340537268f585e
+internal/edge/edge.go Edge.Reload legacy accepted-legacy accepted-legacy;rev3=J1;basis=root-route;rev3=census-ruling-design-edge-rate-limit-358;basis=each route's upstream entry gains rate: e.parseRateSettings(t), the row's rate_limit column parsed once per reload; the one added site is that whole:Route pass of t (parseRateSettings is a new unit, classified in the decisions overlay); no other read added;rev3=census-ruling-certwarm-wake;basis=the single reload hook call becomes runReloadHooks(), which runs every registered hook in order (#386); no read added, same 57 sites (56 before #358 landed on main);rev3=census-ruling-edge-asset-cache-3;basis=each tenant reverse proxy built in the switch (the tunnel, fleet, socket and TCP arms, every *httputil.ReverseProxy) is installed behind assetScrubbedProxy, which hands the proxy an assetInformationalScrub writer so an app's 1xx (103) loses the asset cache's reserved headers (X-Carlos-Asset-Fill, -Fill-Ack, -Expires, Carlos-Cache) on every local path, as the backhaul already does (final review F6); a type check of the proxy it just built and a wrapper around it; static and status handlers untouched; read sites unchanged (57), offsets moved; no read added;rev3=census-ruling-alias-wake-338;basis=#338 follow-up: after the path fold, a resolved platform alias takes its source's own upstream entry (same proxy, route, hibernating: the existing activator wake, lease and fence), keeping its own prefix map (none for a minted apex) and never inheriting the source's (Astra r2 P1); a refused alias, or one whose source has no entry, is dropped from the map (not served, not Allowed); the attached-hostname fold clears platformAlias;rev3=census-ruling-rootfs-apps-3;basis=rootfs Plan 3 Task 5: the activator-managed test (generation proxy, hib, no-activator 404) is Route.ActivatorOwned instead of Kind and Hibernate inline, so a resident rootfs instance goes through the activator; binary rows unchanged;rev3=census-ruling-edge-roll-blip;basis=the tcpProxy and multiProxy calls pass e.hold (the per-Edge localHold set once in newEdge): a loopback TCP upstream that refuses is redialled for up to 13 s and a probed route with a local upstream waits for prober readmission instead of answering 502/503 (#434 part B); edge-side dial policy only, no read added, same 52 sites;rev3=census-ruling-regional-domains-447;basis=#447 Task 5: after the alias fold, reads the regional_domains rows (e.reg.ListRegional; an error aborts the reload as every registry read here does) and applies them with foldRegional against the routes slice the same reload read; the added reads are that one registry list and the routes already read;rev3=census-ruling-fleet-public-routes;basis=fleet public routes (spec 2026-10-29 rev 4, §4.2 writer rule): Tasks 4 and 6: the forward case (fleetProxy toward the binding's FleetBox, throttled refusal); one refusal check before the switch from FleetArmVerdict (sidecar not judged; a non-ready forward row refused; a forward row always judged by FleetServeEligible, any other row only where tunnels are on; an alias of a refused source refused with it); the accountless note; path rows of a forward host not folded; no alias folded onto a refused row; refusedHosts held through every fold. ListFleets and FleetChannelAuth read before the loop (+registry:FleetBox, +registry:Host x7, +whole:Route x3). Serving only; the hub's agent, not root. Review R1 finding 2: the switch reads verdict.Served (FleetArmVerdict) by host; the forward case and the fleet-placed case take their fleet from it (served.Fleet) instead of FleetPlacement(t.Region), and an admitted forward row not Served continues rather than falling through (+registry:Host, -registry:Region); the same rows take the same arms; no read added. Review R2: the switch is on DispatchArm(t, viaFleet, tunnels) (the order moved there unchanged: forward only when in Arm, own Tunnel, fleet, socket, addrs, static, status, else continue), the fleet cases read verdict.Arm (renamed from Served), and the platform-alias fold is foldPlatformAliases with the same take (source entry, own paths, alias marks) and the same refusal log (-registry:Kind x2, -registry:Socket, -registry:Tunnel, +whole:Route: those reads moved into DispatchArm); same rows, same arms, same entries; no read added.;rev3=census-ruling-fleet-routes-followups;basis=the owners map is now e.reg.FleetOwners() instead of ListFleets folded inline: the same fresh-connection ListFleets read and the same name->account map (-registry:Account, -registry:Name, -whole:Fleet x2 move into Registry.FleetOwners); no read added; same error path (abort the reload) registry:Alias@23545,registry:Alias@23632,registry:Alias@24212,registry:FleetBox@10371,registry:FleetBox@6410,registry:Health@12498,registry:Health@12624,registry:Host@10226,registry:Host@10283,registry:Host@10319,registry:Host@10920,registry:Host@13107,registry:Host@13202,registry:Host@13490,registry:Host@13516,registry:Host@13568,registry:Host@18021,registry:Host@19928,registry:Host@20236,registry:Host@20263,registry:Host@21064,registry:Host@21636,registry:Host@23966,registry:Host@24015,registry:Host@4537,registry:Host@4591,registry:Host@4641,registry:Host@5508,registry:Kind@16357,registry:Kind@16379,registry:Prefix@21611,registry:Socket@10984,registry:Socket@20244,registry:Status@4462,registry:Target@21623,registry:Tunnel@8842,registry:Version@16338,registry:Version@16440,whole:RegionalDomain@24682,whole:Route@10435,whole:Route@11040,whole:Route@130,whole:Route@13641,whole:Route@13705,whole:Route@13756,whole:Route@20296,whole:Route@20303,whole:Route@20399,whole:Route@21499,whole:Route@22667,whole:Route@24674,whole:Route@3217,whole:Route@3275,whole:Route@5537,whole:Route@6474,whole:Route@8904,whole:RouteAlias@23516,whole:RoutePath@21042 88586bab6777f8ba12797b1e8b8d5dad7ca3d0b29c4703039b0a56041f8db6d0
+internal/registry/forward.go Registry.PutForward legacy accepted-legacy accepted-legacy;rev3=census-ruling-fleet-public-routes;basis=fleet public routes (spec 2026-10-29 rev 4, §4.2 writer rule): Task 2: the only writer of a forward row's declared columns: refuses an argument whose kind is not forward; copies only the declared fields from its argument (Status ready, Provisioned true; no forbidden column is ever written); inside one IMMEDIATE transaction refuses a host a non-forward row holds (ErrHostHeld); keeps FleetBox while Region is unchanged; preserves the observational columns (+file:Exec, +file:QueryRow, +registry:Account, App, Channel, RateLimit, Region, Slug, +registry:Host x3, +registry:Kind, +registry:remote x2, +whole:Route x3, +whole:remoteClient x2).;rev3=census-ruling-fleet-routes-followups;basis=refuses up front, with the new sentinel ErrNotForward and before any read or write, an rt that is not a forward row (as before, now a sentinel), has an empty Host, or whose Region is not a fleet placement (registry.FleetPlacement); +registry:Host x2 and +registry:Region x2 read only the argument in those checks; the transaction and statement are unchanged file:Exec@1166,file:QueryRow@942,registry:Account@693,registry:App@670,registry:Channel@746,registry:Host@197,registry:Host@234,registry:Host@419,registry:Host@594,registry:Host@996,registry:Kind@206,registry:RateLimit@773,registry:Region@428,registry:Region@720,registry:Region@84,registry:Slug@646,registry:remote@446,registry:remote@476,whole:Route@1199,whole:Route@531,whole:Route@539,whole:remoteClient@448,whole:remoteClient@478 e46e8df164ed32403309e37d8470bc4c96319890ccf66fc0d276e452fef7b8e2
+@remove internal/host/hub.go hubFleetOwners
+@removed internal/host/hub.go hubFleetOwners H3 census-ruling-fleet-routes-followups;basis=now calls reg.FleetOwners() and wraps its error as before; its own read sites moved into Registry.FleetOwners; comment reworded (phase and edge converge and fail closed)
+@coverage internal/edge 37fbc2d03adfb340d819820d2613e8787652a45b60467ac04fc2ed4fe6bfc7c6
+@coverage internal/host 52a048a60bfc9fdbf61e1f317a24748c35b20a564a33a2a5e52067b996d71837
+@coverage internal/registry 8f3e1414926911fa603c0f29ba0080fb5bf12f93e0f9ed5d5923d5e072c26f17
+@fields A,Account,Accounts,AddedAt,Addr,Addrs,Alias,Aliases,Alive,AllowAbsent,App,Archives,Args,AssetGen,AssetsOff,At,Attempts,B,Backing,Bucket,BuildState,By,Callback,CallbackError,CallbackFailed,Canary,Caps,CertExpiresAt,Changed,Channel,CheckedAt,Claim,ClaimIncarnation,ClaimOwner,ClaimOwnership,ClaimRowID,ClaimStamp,Class,Column,Contents,CreatedAt,DBPath,DNSCheckedAt,DNSStatus,Deadline,Default,Demand,Digest,DoneBefore,Due,DueAt,EgressAllow,Env,EnvBefore,Environment,Error,ErrorKind,ExcludeHosts,ExpectGood,ExpectOp,ExpectPair,Expected,F,Failed,FenceGen,Field,Fleet,FleetBox,FleetBoxes,Fleets,From,FromDB,FromOp,FromSock,Gate,GoodDemand,GoodDigest,GoodVersion,HA,Hash,Health,Held,Hibernate,HoldOp,Host,Hosts,ID,Id,IdValue,Idle,IdleSeconds,ImportGate,Incarnation,Journal,Keep,KeyFP,Kind,Label,LastAt,LastError,LastMs,LastStatus,Limit,MaxRun,MaxRunSeconds,Method,Ms,Name,Next,NextAt,NextDue,NextGood,NextValue,Now,Number,Number64,Observed,ObservedValue,Old,On,OnConflict,Op,Original,Owner,Ownership,P,Pair,Path,Paths,Platform,PolicyExpiresAt,Pool,Prefix,Prev,PrevVersion,Provisioned,Pub,RDs,RateLimit,RecordKey,Region,Regional,Registration,Replica,Replicas,Replication,Retirement,Route,Routes,Row,Rows,Runtime,SecretsKeyFP,SecretsKeySetAt,SecretsKeySetBy,SecretsPub,Seed,SeedID,SeedSource,ServingSeq,ServingVersion,Size,Slug,Socket,Spec,Sqid,State,Status,StatusNamed,Steering,StringMap,T,TValue,Tags,Target,Targets,Text,Timer,Timers,Times,To,ToDB,ToOp,ToSock,TokenHash,Tunnel,Type,Unit,UpdateSettings,Ver,Version,W,WakeIncarnation,Wildcards,closed,conn,connect,ctx,d,dec,done,enc,full,input,mu,output,path,readOnly,remote,sql,wait
diff --git a/internal/registry/fleetbox_if_test.go b/internal/registry/fleetbox_if_test.go
index bf4b66023..94c0bd2ac 100644
--- a/internal/registry/fleetbox_if_test.go
+++ b/internal/registry/fleetbox_if_test.go
@@ -111,6 +111,38 @@ func TestSetFleetBoxIfBindsPlacementKindAndMembership(t *testing.T) {
}
}
+// TestSetFleetBoxIfMembershipIsTheRowsOwnFleet isolates the membership
+// subquery's fleet condition (deferred minor, Task 1). The label box-2 is
+// detached on the row's own fleet and active on another fleet, and the call
+// names the row's own fleet, so placement and kind both match: only the
+// subquery's `fleet = ?` stands between the call and a binding. Without it,
+// another fleet's active box would vouch for a label this fleet detached.
+func TestSetFleetBoxIfMembershipIsTheRowsOwnFleet(t *testing.T) {
+ reg := openTestRegistry(t)
+ const host = "shop.example.com"
+ fleetBoundRow(t, reg, host, "home", "box-1")
+ if err := reg.AddFleetBox(FleetBox{Fleet: "home", Label: "box-2", TokenHash: tokenHashB, Status: "detached"}); err != nil {
+ t.Fatal(err)
+ }
+ if err := reg.UpsertFleet(Fleet{Name: "away", Account: "baj", Bucket: "away-data"}); err != nil {
+ t.Fatal(err)
+ }
+ if err := reg.AddFleetBox(FleetBox{Fleet: "away", Label: "box-2", TokenHash: tokenHashC, Status: "active"}); err != nil {
+ t.Fatal(err)
+ }
+
+ changed, err := reg.SetFleetBoxIf(host, "home", "box-2")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if changed {
+ t.Error("SetFleetBoxIf(home, box-2) bound the row: box-2 is detached on home and active only on away")
+ }
+ if got, err := reg.Get(host); err != nil || got.FleetBox != "box-1" {
+ t.Errorf("FleetBox = %q (err %v), want box-1 kept", got.FleetBox, err)
+ }
+}
+
// TestSetFleetBoxIfOverRemote: the remote case answers the same as the local
// statement, the bool included, so an agent on the remote registry sees the
// same refusal.
diff --git a/internal/registry/fleets.go b/internal/registry/fleets.go
index 6676d6e61..7877503e0 100644
--- a/internal/registry/fleets.go
+++ b/internal/registry/fleets.go
@@ -276,6 +276,24 @@ func (r *Registry) GetFleet(name string) (*Fleet, error) {
return &f, nil
}
+// FleetOwners is ListFleets folded to each fleet's name and its owning
+// account: the owners map the edge's Reload (FleetArmVerdict) and the hub's
+// forward phase judge a forward row by (fleet public routes spec §4.3,
+// §4.4). One fold, so the two read the table the same way; they still read
+// it separately, and converge on their next reads. Never nil when err is
+// nil.
+func (r *Registry) FleetOwners() (map[string]string, error) {
+ fleets, err := r.ListFleets()
+ if err != nil {
+ return nil, err
+ }
+ owners := make(map[string]string, len(fleets))
+ for _, f := range fleets {
+ owners[f.Name] = f.Account
+ }
+ return owners, nil
+}
+
// ListFleets returns every fleet, ordered by name, over a fresh connection.
func (r *Registry) ListFleets() ([]Fleet, error) {
if r.remote != nil {
diff --git a/internal/registry/fleets_test.go b/internal/registry/fleets_test.go
index 39ccc134c..aa4432daa 100644
--- a/internal/registry/fleets_test.go
+++ b/internal/registry/fleets_test.go
@@ -4,6 +4,7 @@ import (
"database/sql"
"errors"
"path/filepath"
+ "reflect"
"regexp"
"strings"
"sync"
@@ -700,3 +701,30 @@ CREATE TABLE fleet_boxes (
t.Fatalf("pre-tags row should default tags=\"\": %+v", boxes)
}
}
+
+// TestFleetOwnersMapsEachFleetToItsAccount: FleetOwners is ListFleets folded
+// to fleet name -> owning account, the one map the edge's Reload and the
+// hub's forward phase both judge forward rows by. Locally and over the
+// remote transport; an empty table is an empty map, not nil.
+func TestFleetOwnersMapsEachFleetToItsAccount(t *testing.T) {
+ local := openTestRegistry(t)
+ remote, _ := remoteTestRegistry(t)
+ for name, reg := range map[string]*Registry{"local": local, "remote": remote} {
+ got, err := reg.FleetOwners()
+ if err != nil || got == nil || len(got) != 0 {
+ t.Fatalf("%s: FleetOwners on no fleets = %v, %v; want an empty map", name, got, err)
+ }
+ for _, f := range []Fleet{{Name: "home", Account: "bah", Bucket: "home-data"}, {Name: "away", Account: "baj", Bucket: "away-data"}} {
+ if err := reg.UpsertFleet(f); err != nil {
+ t.Fatal(err)
+ }
+ }
+ got, err = reg.FleetOwners()
+ if err != nil {
+ t.Fatal(err)
+ }
+ if want := map[string]string{"home": "bah", "away": "baj"}; !reflect.DeepEqual(got, want) {
+ t.Fatalf("%s: FleetOwners = %v, want %v", name, got, want)
+ }
+ }
+}
diff --git a/internal/registry/forward.go b/internal/registry/forward.go
index b10fe4f1f..e14c18096 100644
--- a/internal/registry/forward.go
+++ b/internal/registry/forward.go
@@ -64,6 +64,11 @@ func (t Route) IsForward() bool { return t.Kind == KindForward }
// §4.2, the writer rule). One of remoteErrors.
var ErrForwardRow = errors.New("registry: the host is a forward row")
+// ErrNotForward is PutForward's answer when the row it is handed is not a
+// forward row it may write: another kind, no host, or a Region that is not
+// a fleet placement. Nothing is read or written. One of remoteErrors.
+var ErrNotForward = errors.New("registry: not a forward row")
+
// ErrHostHeld is PutForward's answer when a row that is not a forward row
// already holds the host: that row is another writer's, and PutForward
// writes nothing. One of remoteErrors.
@@ -252,23 +257,50 @@ var fingerprintForwardInert = func() string {
return "CASE WHEN kind <> 'forward' OR (" + strings.Join(zero, " AND ") + ") THEN 1 ELSE 0 END"
}()
+// forwardKeptColumn is one routes column of a forward row that is not
+// ForwardForbidden: its Route field, its column, and the value PutForward's
+// conflict arm writes to it (empty for host, the conflict target).
+type forwardKeptColumn struct{ Field, Column, OnConflict string }
+
+// forwardKept is every routes column that is not ForwardForbidden, with the
+// value PutForward's conflict arm gives it when a forward row is already
+// stored: declared columns from the call (excluded.*), CreatedAt and the
+// observational ones kept (routes.*), FleetBox kept only while the region is
+// unchanged. putForwardSQL is built from this list and ForwardForbidden, and
+// TestForwardForbiddenMatchesTheTable checks the two together against
+// PRAGMA table_info(routes), so a column a migration adds is either classed
+// here or fails that test.
+var forwardKept = []forwardKeptColumn{
+ {"Host", "host", ""},
+ {"Kind", "kind", "excluded.kind"},
+ {"Slug", "slug", "excluded.slug"},
+ {"App", "app", "excluded.app"},
+ {"Account", "account", "excluded.account"},
+ {"Region", "region", "excluded.region"},
+ {"Channel", "channel", "excluded.channel"},
+ {"RateLimit", "rate_limit", "excluded.rate_limit"},
+ {"Status", "status", "excluded.status"},
+ {"Provisioned", "provisioned", "excluded.provisioned"},
+ {"CreatedAt", "created_at", "routes.created_at"},
+ {"FleetBox", "fleet_box", "CASE WHEN routes.region = excluded.region THEN routes.fleet_box ELSE '' END"},
+ {"DNSStatus", "dns_status", "routes.dns_status"},
+ {"DNSCheckedAt", "dns_checked_at", "routes.dns_checked_at"},
+ {"CertExpiresAt", "cert_expires_at", "routes.cert_expires_at"},
+}
+
// putForwardSQL is PutForward's one statement. The INSERT binds every column
-// through routeArgs (the forbidden ones zero). The conflict arm names every
-// column too: declared ones from the call, CreatedAt and the observational
-// ones kept, FleetBox kept only while the region is unchanged, and every
-// ForwardForbidden column set to zero, so a stray value on a stored forward
+// through routeArgs (the forbidden ones zero). The conflict arm assigns
+// every column but host: each forwardKept column its OnConflict value, and
+// every ForwardForbidden column zero, so a stray value on a stored forward
// row does not survive a put. Its WHERE matches only a forward row: a row of
// another kind is never overwritten, even if the transaction's own check
// were bypassed.
var putForwardSQL = func() string {
- set := []string{
- "slug = excluded.slug", "kind = excluded.kind", "app = excluded.app",
- "account = excluded.account", "region = excluded.region", "channel = excluded.channel",
- "rate_limit = excluded.rate_limit", "status = excluded.status",
- "provisioned = excluded.provisioned", "created_at = routes.created_at",
- "fleet_box = CASE WHEN routes.region = excluded.region THEN routes.fleet_box ELSE '' END",
- "dns_status = routes.dns_status", "dns_checked_at = routes.dns_checked_at",
- "cert_expires_at = routes.cert_expires_at",
+ set := make([]string, 0, len(forwardKept)+len(ForwardForbidden))
+ for _, k := range forwardKept {
+ if k.OnConflict != "" {
+ set = append(set, k.Column+" = "+k.OnConflict)
+ }
}
for _, c := range ForwardForbidden {
zero := "''"
@@ -285,7 +317,9 @@ WHERE routes.kind = 'forward'`
}()
// PutForward writes rt as a forward row (spec §4.2), in one transaction. It
-// refuses an rt that is not a forward row. A row at the host that is not a
+// refuses, with ErrNotForward and before any read, an rt that is not a
+// forward row, has no Host, or whose Region is not a fleet placement
+// (FleetPlacement). A row at the host that is not a
// forward row is another writer's: ErrHostHeld, nothing written. Otherwise
// it writes the declared columns from rt (Host, Kind, Slug, App, Account,
// Region, Channel, RateLimit; Status "ready" and Provisioned true whatever rt
@@ -295,8 +329,13 @@ WHERE routes.kind = 'forward'`
// or the stored row carries. Never Upsert, which keeps non-empty stored
// values.
func (r *Registry) PutForward(rt Route) error {
- if !rt.IsForward() {
- return fmt.Errorf("registry: PutForward(%q): kind %q is not %q", rt.Host, rt.Kind, KindForward)
+ switch _, placed := FleetPlacement(rt.Region); {
+ case !rt.IsForward():
+ return fmt.Errorf("%w: PutForward(%q): kind %q is not %q", ErrNotForward, rt.Host, rt.Kind, KindForward)
+ case rt.Host == "":
+ return fmt.Errorf("%w: PutForward: no host", ErrNotForward)
+ case !placed:
+ return fmt.Errorf("%w: PutForward(%q): region %q is not a fleet placement", ErrNotForward, rt.Host, rt.Region)
}
if r.remote != nil {
_, err := r.remote.call(nil, remoteRequest{Method: "PutForward", TValue: rt}, nil)
diff --git a/internal/registry/forward_test.go b/internal/registry/forward_test.go
index 20d17656a..9766d6e62 100644
--- a/internal/registry/forward_test.go
+++ b/internal/registry/forward_test.go
@@ -97,21 +97,12 @@ func TestForwardShapeClassesEveryField(t *testing.T) {
}
}
-// forwardKeptColumns is the SQL column of every field that is not
-// forbidden. With ForwardForbidden it must name every column of routes once.
-var forwardKeptColumns = map[string]string{
- "Host": "host", "Kind": "kind", "Slug": "slug", "App": "app",
- "Account": "account", "Region": "region", "Channel": "channel",
- "RateLimit": "rate_limit", "Status": "status", "Provisioned": "provisioned",
- "CreatedAt": "created_at", "FleetBox": "fleet_box", "DNSStatus": "dns_status",
- "DNSCheckedAt": "dns_checked_at", "CertExpiresAt": "cert_expires_at",
-}
-
// TestForwardForbiddenMatchesTheTable: ForwardForbidden is the forbidden
// class exactly, each field once, and each entry's Column and Type are the
-// routes table's own (PRAGMA table_info). With the kept columns it covers
-// every column of routes, the ClaimOwnership ones included, so a column a
-// migration adds later fails here until it is classed.
+// routes table's own (PRAGMA table_info). With the kept columns
+// (forwardKept, the production list PutForward's conflict arm is built from)
+// it covers every column of routes, the ClaimOwnership ones included, so a
+// column a migration adds later fails here until it is classed.
func TestForwardForbiddenMatchesTheTable(t *testing.T) {
reg := openTestRegistry(t)
rows, err := reg.sql.Query(`SELECT name, type FROM pragma_table_info('routes')`)
@@ -175,18 +166,24 @@ func TestForwardForbiddenMatchesTheTable(t *testing.T) {
t.Errorf("ForwardForbidden fields = %v\nforbidden class = %v", listed, forbidden)
}
- for f, col := range forwardKeptColumns {
+ kept := map[string]bool{}
+ for _, k := range forwardKept {
+ f, col := k.Field, k.Column
+ if kept[f] {
+ t.Errorf("forwardKept lists %s twice", f)
+ }
+ kept[f] = true
if forwardShape[f] == "forbidden" || forwardShape[f] == "" {
t.Errorf("kept column %s: field %s has class %q", col, f, forwardShape[f])
}
if prev, ok := columns[col]; ok {
- t.Errorf("column %s is both kept (%s) and forbidden (%s)", col, f, prev)
+ t.Errorf("column %s is both kept (%s) and forbidden or kept again (%s)", col, f, prev)
}
columns[col] = f
}
for f, class := range forwardShape {
- if _, ok := forwardKeptColumns[f]; class != "forbidden" && !ok {
- t.Errorf("field %s (%s) has no column in this test's kept list", f, class)
+ if class != "forbidden" && !kept[f] {
+ t.Errorf("field %s (%s) has no entry in forwardKept", f, class)
}
}
for col := range table {
@@ -201,6 +198,154 @@ func TestForwardForbiddenMatchesTheTable(t *testing.T) {
}
}
+// TestPutForwardSetsEveryColumnButHost reads putForwardSQL's conflict arm
+// back against PRAGMA table_info(routes) (deferred minor, Task 2): it
+// assigns every column except host (the conflict target) exactly once, so
+// a column the arm forgets cannot keep a stale value through a put. Each
+// kept column's value follows its class: declared ones from the call
+// (excluded.*) except created_at, observational ones and created_at from
+// the stored row (routes.*), fleet_box cleared when the region moves.
+func TestPutForwardSetsEveryColumnButHost(t *testing.T) {
+ reg := openTestRegistry(t)
+ rows, err := reg.sql.Query(`SELECT name FROM pragma_table_info('routes')`)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var table []string
+ for rows.Next() {
+ var name string
+ if err := rows.Scan(&name); err != nil {
+ t.Fatal(err)
+ }
+ if name != "host" {
+ table = append(table, name)
+ }
+ }
+ if err := rows.Err(); err != nil {
+ t.Fatal(err)
+ }
+ rows.Close()
+ sort.Strings(table)
+
+ _, arm, ok := strings.Cut(putForwardSQL, "DO UPDATE SET")
+ if !ok {
+ t.Fatalf("putForwardSQL has no conflict arm:\n%s", putForwardSQL)
+ }
+ arm, _, ok = strings.Cut(arm, "\nWHERE ")
+ if !ok {
+ t.Fatalf("putForwardSQL's conflict arm has no WHERE:\n%s", putForwardSQL)
+ }
+ set := map[string]string{}
+ var assigned []string
+ for _, a := range strings.Split(arm, ",\n") {
+ col, val, ok := strings.Cut(strings.TrimSpace(a), " = ")
+ if !ok {
+ t.Fatalf("conflict-arm assignment %q has no ' = '", a)
+ }
+ if _, dup := set[col]; dup {
+ t.Errorf("the conflict arm assigns %s twice", col)
+ }
+ set[col] = val
+ assigned = append(assigned, col)
+ }
+ sort.Strings(assigned)
+ if !reflect.DeepEqual(assigned, table) {
+ t.Errorf("conflict arm assigns %v\nroutes columns but host %v", assigned, table)
+ }
+
+ for _, k := range forwardKept {
+ want := ""
+ switch {
+ case k.Column == "host":
+ if _, ok := set["host"]; ok {
+ t.Error("the conflict arm assigns host, the conflict target")
+ }
+ continue
+ case k.Column == "created_at", forwardShape[k.Field] == "observational":
+ want = "routes." + k.Column
+ case forwardShape[k.Field] == "declared":
+ want = "excluded." + k.Column
+ case k.Column == "fleet_box":
+ want = "CASE WHEN routes.region = excluded.region THEN routes.fleet_box ELSE '' END"
+ }
+ if set[k.Column] != want {
+ t.Errorf("conflict arm sets %s = %q, want %q (class %s)", k.Column, set[k.Column], want, forwardShape[k.Field])
+ }
+ }
+ for _, c := range ForwardForbidden {
+ want := "''"
+ if c.Type == "INTEGER" {
+ want = "0"
+ }
+ if set[c.Column] != want {
+ t.Errorf("conflict arm sets forbidden %s = %q, want %s", c.Column, set[c.Column], want)
+ }
+ }
+}
+
+// TestPutForwardRefusesWhatIsNotAForwardRow: a call that is not a forward
+// row, has no host, or is not placed on a fleet is ErrNotForward and writes
+// nothing (deferred minor, Task 2; spec §4.4 refuses serving such a row, so
+// this is defence in depth). Locally, through the remote client, and as a
+// raw request on the remote transport (Astra followups R1 P2-1): the
+// client refuses before it calls, so only the raw request reaches the
+// worker's own refusal and shows the sentinel survives the transport
+// (remoteErrors).
+func TestPutForwardRefusesWhatIsNotAForwardRow(t *testing.T) {
+ local := openTestRegistry(t)
+ remote, _ := remoteTestRegistry(t)
+ if remote.remote == nil {
+ t.Fatal("remoteTestRegistry has no remote client")
+ }
+ calls := []struct {
+ name string
+ reg *Registry
+ put func(Route) error
+ }{
+ {"local", local, local.PutForward},
+ {"remote client", remote, remote.PutForward},
+ {"raw remote request", remote, func(rt Route) error {
+ _, err := remote.remote.call(nil, remoteRequest{Method: "PutForward", TValue: rt}, nil)
+ return err
+ }},
+ }
+ for _, call := range calls {
+ for _, c := range []struct {
+ why string
+ edit func(*Route)
+ }{
+ {"an instance row", func(rt *Route) { rt.Kind = "instance" }},
+ {"no host", func(rt *Route) { rt.Host = "" }},
+ {"no placement", func(rt *Route) { rt.Region = "" }},
+ {"a residency code", func(rt *Route) { rt.Region = "eu" }},
+ {"an empty fleet name", func(rt *Route) { rt.Region = "fleet/" }},
+ {"a fleet name ValidTunnelName refuses", func(rt *Route) { rt.Region = "fleet/Not A Fleet" }},
+ } {
+ rt := validForward("shop.example.com", "home")
+ c.edit(&rt)
+ if err := call.put(rt); !errors.Is(err, ErrNotForward) {
+ t.Errorf("%s: PutForward(%s) = %v, want ErrNotForward", call.name, c.why, err)
+ }
+ all, err := call.reg.List()
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(all) != 0 {
+ t.Fatalf("%s: PutForward(%s) wrote %+v", call.name, c.why, all)
+ }
+ }
+ }
+ // The raw request is not refused for its shape alone: a valid forward
+ // row sent the same way is written, so the refusals above are the
+ // worker's judgment of each argument.
+ if _, err := remote.remote.call(nil, remoteRequest{Method: "PutForward", TValue: validForward("shop.example.com", "home")}, nil); err != nil {
+ t.Fatalf("raw remote PutForward of a valid forward row: %v", err)
+ }
+ if got, err := remote.Get("shop.example.com"); err != nil || got == nil || !got.InertForward() {
+ t.Fatalf("raw remote PutForward of a valid row wrote %+v (%v)", got, err)
+ }
+}
+
// TestInertForwardChecksEachForbiddenField: one forbidden field set, and
// only that one, makes a forward row not inert.
func TestInertForwardChecksEachForbiddenField(t *testing.T) {
@@ -249,12 +394,12 @@ func TestPutForwardWritesTheExactShape(t *testing.T) {
t.Fatal("a minted forward row has no CreatedAt")
}
if _, err := reg.sql.Exec(`UPDATE routes SET tunnel = 't1', caps = 'x', unit = 'u.service', seed = 's',
-dns_status = 'pointing', cert_expires_at = 5, fleet_box = 'box-1', created_at = 1000 WHERE host = ?`, host); err != nil {
+dns_status = 'pointing', dns_checked_at = 7, cert_expires_at = 5, fleet_box = 'box-1', created_at = 1000 WHERE host = ?`, host); err != nil {
t.Fatal(err)
}
stored, err := reg.Get(host)
if err != nil || stored.Tunnel != "t1" || stored.Caps != "x" || stored.Unit != "u.service" || stored.Seed != "s" ||
- stored.DNSStatus != "pointing" || stored.CertExpiresAt != 5 || stored.FleetBox != "box-1" || stored.CreatedAt != 1000 {
+ stored.DNSStatus != "pointing" || stored.DNSCheckedAt != 7 || stored.CertExpiresAt != 5 || stored.FleetBox != "box-1" || stored.CreatedAt != 1000 {
t.Fatalf("raw SQL did not persist: %+v, %v", stored, err)
}
@@ -278,7 +423,7 @@ dns_status = 'pointing', cert_expires_at = 5, fleet_box = 'box-1', created_at =
Host: host, Kind: KindForward, Slug: "shop2", App: "shop", Account: "bah",
Region: PlacementTarget("home"), Channel: "stable", RateLimit: `{"rps":9}`,
Status: "ready", Provisioned: true, CreatedAt: 1000,
- FleetBox: "box-1", DNSStatus: "pointing", CertExpiresAt: 5,
+ FleetBox: "box-1", DNSStatus: "pointing", DNSCheckedAt: 7, CertExpiresAt: 5,
}
if *got != want {
t.Fatalf("after PutForward:\n got %+v\nwant %+v", *got, want)
@@ -298,7 +443,7 @@ dns_status = 'pointing', cert_expires_at = 5, fleet_box = 'box-1', created_at =
if got.FleetBox != "" {
t.Fatalf("FleetBox = %q after Region moved home -> away, want empty", got.FleetBox)
}
- if got.Region != PlacementTarget("away") || got.DNSStatus != "pointing" || got.CertExpiresAt != 5 || got.CreatedAt != 1000 {
+ if got.Region != PlacementTarget("away") || got.DNSStatus != "pointing" || got.DNSCheckedAt != 7 || got.CertExpiresAt != 5 || got.CreatedAt != 1000 {
t.Fatalf("after the move: %+v", *got)
}
}
@@ -372,8 +517,8 @@ func TestPutForwardRefusesAHeldHost(t *testing.T) {
notForward := validForward("other.example.com", "home")
notForward.Kind = "instance"
- if err := reg.PutForward(notForward); err == nil {
- t.Fatal("PutForward accepted an instance row")
+ if err := reg.PutForward(notForward); !errors.Is(err, ErrNotForward) {
+ t.Fatalf("PutForward(instance row) = %v, want ErrNotForward", err)
}
if got, err := reg.Get("other.example.com"); err != nil || got != nil {
t.Fatalf("a refused PutForward wrote a row: %+v, %v", got, err)
diff --git a/internal/registry/remote.go b/internal/registry/remote.go
index 380b91071..481c1e2c8 100644
--- a/internal/registry/remote.go
+++ b/internal/registry/remote.go
@@ -14,7 +14,7 @@ import (
var errRemoteMethod = errors.New("registry: unsupported remote operation")
-var remoteErrors = []error{os.ErrNotExist, os.ErrPermission, sql.ErrNoRows, ErrClaimOwnership, ErrTimerChanged, ErrTimerKind, ErrPathsChanged, ErrFleetBoxActive, context.Canceled, context.DeadlineExceeded, ErrGoodBuildChanged, ErrRuntimeFixed, ErrRootfsRow, ErrRuntimePlacement, ErrFleetKeyInUse, ErrForwardRow, ErrHostHeld}
+var remoteErrors = []error{os.ErrNotExist, os.ErrPermission, sql.ErrNoRows, ErrClaimOwnership, ErrTimerChanged, ErrTimerKind, ErrPathsChanged, ErrFleetBoxActive, context.Canceled, context.DeadlineExceeded, ErrGoodBuildChanged, ErrRuntimeFixed, ErrRootfsRow, ErrRuntimePlacement, ErrFleetKeyInUse, ErrForwardRow, ErrHostHeld, ErrNotForward}
func responseError(out remoteResponse) error {
if !out.Failed {