carlos / platform Public

Fleet public routes Task 1: bindings bind only their own fleet, at write time

A fleet box writes its bindings through the store door, which lets it
write anything under fleets/<own>/, so a binding's body could name another
fleet's host and the pass would stamp it (the body's fleet matched the
row's placement). And the pass checked placement, then wrote with a
hostname-only UPDATE, so a row moved between the two was stamped by the
old fleet's box.

- registry: SetFleetBoxIf(host, fleet, label) (new forward.go) is one
  conditional UPDATE judging placement (region = fleet/<fleet>), kind (not
  a sidecar) and membership (label an active box of that fleet); answers
  whether a row changed; no row is no change, not an error. Remote case
  "SetFleetBoxIf". SetFleetBox is gone (its clear and unknown-host error
  had no production caller).
- host: ReconcileFleetBindings applies a binding only when its key is
  fleetBindingKey(b.Fleet, b.Host), then writes through SetFleetBoxIf; the
  pre-checks stay as a filter. Test seam bindingsAfterChecks (nil in
  production). instancesLoop runs the pass only on the hub (hubArmed, new
  hub.go: CARLOS_TUNNEL_HOST set, CARLOS_FLEET unset).
- tests: one fixture builder per package (fleetBoundRow, seedFleetRoute)
  seeds the fleet, an active box and the matching placement; migrated
  binding tests use it. New: SetFleetBoxIf placement/kind/membership and
  remote, TestHubArmed, and door tests for forged and stale bindings.
- spec §7: Task 1's census card recorded (forward.go, hub.go; instancesLoop
  and hubArmed envelope-only).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev 08d71e39fe18e45becbd212448dbb8e8beee9564 parent 057cf7b
13 files changed, +632 −142
  • docs/superpowers/specs/2026-10-29-fleet-public-routes-design.md +16 −3
  • internal/host/agent.go +8 −10
  • internal/host/fleetbind.go +48 −14
  • internal/host/fleetbind_door_test.go +250 −0
  • internal/host/fleetbind_test.go +59 −31
  • internal/host/hub.go +13 −0
  • internal/host/hub_test.go +20 −0
  • internal/registry/fleetbox_if_test.go +134 −0
  • internal/registry/fleets_test.go +7 −5
  • internal/registry/forward.go +40 −0
  • internal/registry/registry.go +7 −31
  • internal/registry/registry_test.go +28 −46
  • internal/registry/remote_dispatch.go +2 −2

Intent

Human

<task-notification> <task-id>afd6d4ccb5ed61caa</task-id> <tool-use-id>toolu_018vLzAUry8aGzi6CnWAYn4N</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/ba9fa944-a429-4788-9b3c-f2b2f42617f3/tasks/afd6d4ccb5ed61caa.output</output-file> <status>completed</status> <summary>Agent "SDD preflight conflict scan" finished</summary> <note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note> <result>I wrote the preflight table to /home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-fleet-public-routes/.superpowers/sdd/2026-10-30-fleet-public-routes/preflight.md. It has 55 rows: 23 task pairs, 16 single-task rows (0 to 15), 7 defects and 9 conflicts. I edited no repo file and committed nothing; I ran no Go builds or tests, only reads and greps. The most important finding is that the plan's test-account names make Task 4's eligibility test wrong. `bab` is `release.OpsAccount`, and `k3x` fails `ValidAccount` (`^[a-z]{3,16}$`). Under spec §4.4 as written, both `k3x` and `!!` map to `bab`, which equals the owner, so both rows are eligible and Task 4's test, which expects false, fails. Spec §8 test 5 says the opposite. The local `main` is stale (671d3d11); use `origin/main`, which does contain 43c8677a and 11c6f199. **Problems and proposed rulings** 1. Accounts `k3x` and `bab` (Tasks 4, 6, 10, 13; spec §4.4 vs §8.5): a non-empty raw account that fails `ValidAccount` is refused before `RouteAccount`. Replace `k3x` with a valid non-ops name (a real sqid wherever records are involved), and record the rule in spec §4.4. 2. Main has moved: merge `origin/main` into the branch before dispatching Task 1. Main changed the `apiinstances.go` health code (`fleetHealth`), the record-write census inventory and the census chain file. 3. The record-write census pins `SwapForImport` and `runRoute` (Task 3), `Reconcile` (Task 10), and `placeAppTarget` and `handleAPIInstanceList` (Task 11). Add one `fleetPublicRoutesWriteCensusInventory` layered on main's newest inventory. Tasks 3, 10 and 11 each add their re-pins and run `TestPlan9B8RecordWriteCensus`; otherwise CI fails. 4. Task 11 health: after the merge, "the fleet answer" means main's `fleetHealth` rollout word. The test should seed a fleet box report and assert Running with a forward row present, and unknown with no report. 5. Task 11 REASON: there is no `Reason` field to fill; the CLI builds REASON in `instances_cli.go` `reasonCell`. Add a JSON field (e.g. `route_held`) and a `reasonCell` change, and add `instances_cli.go` and a root census unit to Task 11. 6. Tasks 10 and 11: placing an app from the platform onto a fleet takes two passes on the hub. The old instance row is retired as "record gone" after the forward phase has already hit `ErrHostHeld`. Accept this, run two passes in the migrated accountfleet test, and add the missing spec §4.6 row and a Task 10 test. 7. Two definitions of "hub": the edge uses `e.tunnels != nil`, the host uses `hubArmed`. Define it once in `internal/edge` (e.g. `edge.HubArmed`) and use it in both Reload and the edges-file writer. 8. `ForwardColumn` has no column type, and the base columns can't be derived from `routeAddedColumns`. Make `ForwardForbidden` an explicit `{Field, Column, Type}` literal, checked against `PRAGMA table_info(routes)`. 9. Task 8's first-publication test needs a hook that only Task 9 creates. Call `fleetFloorPublish` directly with a nil current pointer. Task 9 also needs `server.go` added to its files. 10. Task 9's "both create doors": only `handleAPIFleetNew` exists. Barrier that one door, amend spec §9, and use the hook name `createBeforeLock` in case (c). 11. Copy deck: C06 and C07 name `fleets.go`, but `fleetCreateFloorRefusal` lives in `fleetfloor.go`. Fix the file cell or the literal's location before approval. All eight rows are still pending, so copy review must finish before Task 3. 12. Task 13 steps 4 and 7 use functions the root package can't call (`aliasPassReporting`, `edgesFilePass`). Call `domains.ReconcileAliasesReport` for step 4. For step 7, assert no row and `Allowed` false, and drop the edges-file clause (Task 6 covers it). 13. Task 13 / R3 P2-3 ruling: Task 10 must log every owner-mismatch refusal once per host per pass and assert it, so the witness has something to observe. 14. Task 14's inventory must list every fleet-placed row's raw account next to its fleet's owner, including accountless rows and other accounts' rows, before the roll. Otherwise a hand row like railsdemo's could go dark at the dev roll. 15. Task 5's box-limiter check can never fail (the box only sees 2 requests). Give the box row a lower limit (1) than the hub's (2). 16. Task 4's two cache tests and Task 7's expired-canary test need positive controls using a non-forward row. 17. Task 7's readers table, the `frobnicate` case and Task 4's version-once test already pass before any code is written. Show each failing by a mutation. 18. Tasks 1, 8 and 12 say the migrated tests stay green, but they reference symbols that don't exist yet. For Tasks 1 and 12 the red state is a compile failure. Task 8 Step 1 should add the unused `allowFleet` parameter together with its callers. 19. Missing `-run` patterns. Task 12: use `TestBoxProvisionConfig|TestForwardRequestBudget|TestProvisioningLoopsShareThePolicyCache|TestBoxJudgeIsSharedAndGated|TestPolicyChangedNotesTheSize`. Task 8: add `TestPlacementsRefusesBelowAPublishedChannel|TestPlan9Operator`. 20. Task 1: the forged-binding negative case and its positive control share one object key, so run them as two sequential passes. The stale-binding hook's raw-SQL clear does nothing; drop it or stamp first. 21. Task 3's inventory test needs a map from each statement's enclosing function to the writer-table entry that reaches it. About 16 unclassified SQL arguments are expected. 22. Task 10: there is no "existing throttled report" in `internal/provision`; use a plain log line per held host per pass and amend spec §4.3. Add tests for the host-collision, `FleetOwners` read-error and `ClaimEnabled` cases, and bind `bab` to the fixture's real sqid. 23. Spec §8 test 9's "request goes to B's box" isn't covered anywhere. Add that case to Task 4. 24. The Global Constraints require cross-builds before every commit, which conflicts with the machine policy (cross-builds once, not in a loop). Run them once before Task 14's push. 25. Minor: spec §7 files the new units under `registry.go` and `agent.go`, but the plan puts them in `forward.go` and `hub.go`; fix §7 at the census steps. Task 6's "90 call sites" is really 30, with no effect. The R3 findings file is untracked and should be committed. Checked and fine: - **Task 1:** the `SetFleetBox` caller list is exact. - **Task 2:** the four classes cover all 67 `Route` fields. - **Task 3:** the writer inventory matches spec §4.2. - **Task 8:** the floor caller lists are exact. - **Task 13:** a detached box label can be re-added. - **Task 15:** v0.31.0 is tagged, so the v0.32.0 floor is consistent.</result> <usage><subagent_tokens>276409</subagent_tokens><tool_uses>107</tool_uses><duration_ms>1127587</duration_ms></usage> </task-notification>

Attributed to this commit: 26.6 g CO₂e (3,386,602 tokens). This is an attribution, not a measurement — usage counted from this commit's own marker forward to the next one on design-fleet-public-routes, never backward from it. A turn that produced more than one commit books all of its tokens to the last one, and a concurrent session on this branch can add to the same figure. Some of it was priced using the shared default rate, because no model-specific factor row exists yet for at least one model involved. The Carbon view has the repo total, which is never derived from this attribution.

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 fa9571a50..57c192302 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
@@ -814,7 +814,7 @@ Units, by file (N = new, R = removed, otherwise a changed body or sites):
- `internal/registry/registry.go`: `Route.IsForward` (N, reads `Kind`);
`Route.InertForward` (N, reads every forbidden column of §4.2);
`Registry.PutForward` (N); `Registry.DeleteForward` (N);
- `Registry.SetFleetBoxIf` (N); `Registry.SetFleetBox` (R); and every
+ `Registry.SetFleetBox` (R); and every
writer that gains `kind <> 'forward'` and reads a `Route` field in its
body: `Upsert`, `UpsertUnlessRootfs`, `DeleteIfUnchanged`, and those of
the §4.2 setter list whose bodies select a `Route` field. A setter whose
@@ -838,8 +838,16 @@ Units, by file (N = new, R = removed, otherwise a changed body or sites):
`carryAliasesTx`. Those with read sites appear on the card as `body` or
`sites`; the rest move only the `internal/registry` envelope. Callers in
other packages are unchanged (§4.2).
+- `internal/registry/forward.go` (a new file; the plan puts the forward
+ row's writers here rather than in `registry.go`): `Registry.SetFleetBoxIf`
+ (N, Task 1). Task 1's card shows it with `+file:Exec`,
+ `+registry:Changed`, `+registry:remote` x2, `+registry:sql`,
+ `+whole:remoteClient` x2: the remote-or-local shape every narrow setter
+ has.
- `internal/registry/remote_dispatch.go`: `Registry.dispatchRemote` (the
- three new cases, `SetFleetBox` gone).
+ three new cases, `SetFleetBox` gone). Task 1's card shows it as `sites`
+ (`+registry:Changed`, `+registry:Fleet`: the `SetFleetBoxIf` case reads
+ the request's `Fleet` and answers `Changed`).
- `internal/provision/reconcile.go`: `Reconcile` (forward phase, trash-only
prefetch, `retirable` guard); the forward phase's own helpers (N), named
by the plan; `ReconcileConfig` (the `FleetOwners` field; envelope unless
@@ -847,7 +855,12 @@ Units, by file (N = new, R = removed, otherwise a changed body or sites):
- `internal/domains/reconcile.go`: `Reconcile` (trash-loop skip).
- `internal/host/agent.go`: `boxProvisionConfig` (hub predicate, owner map,
reads `Fleet.Name`, `Fleet.Account`); `instancesLoop` (hub-only
- bindings); `countExpiredCanaries` (skip); the hub predicate helper (N).
+ bindings); `countExpiredCanaries` (skip). The hub predicate `hubArmed`
+ is in a new file, `internal/host/hub.go`. Neither `instancesLoop`'s
+ change nor `hubArmed` shows on Task 1's card: `hubArmed` reads its
+ environment through its `getenv` parameter and `instancesLoop` gained
+ only a call, so neither has a read site, and both move only the
+ `internal/host` envelope.
- `internal/host/fleetbind.go`: `ReconcileFleetBindings` (key check,
`SetFleetBoxIf`).
- `internal/host/edgesfile.go`: `edgesFileWriteClaims` (eligibility,
diff --git a/internal/host/agent.go b/internal/host/agent.go
index 25f4c8e24..4e083405a 100644
--- a/internal/host/agent.go
+++ b/internal/host/agent.go
@@ -3838,7 +3838,7 @@ func domainsDuty(pass func(context.Context) error) housekeeperDuty {
// the loop lives on.
//
// Also runs ReconcileFleetBindings (customer-fleets plan, Task 6) on the same
-// cadence, platform boxes only: turns every fleet's published
+// cadence, on the hub only (hubArmed): turns every fleet's published
// fleets/*/bindings/*.json object into this platform box's own
// registry.Route.FleetBox — see fleetbind.go's doc comment for the
// fleet-placement/corrupt-object contract. Deliberately homed HERE rather
@@ -3857,14 +3857,12 @@ func instancesLoop(reg *registry.Registry, writes hostwrite.Config, bs *buildSta
cfg := boxProvisionConfig(judge, configure)
backfill := newClaimBackfill(writes, store, cfg.ReleasePub, os.Getenv("CARLOS_DEPLOYMENT_BUCKET"))
log.Printf("agent: instances loop armed (5min + jitter), region %q pools %v", cfg.Region, cfg.Pools)
- // Platform-only: a fleet box (CARLOS_FLEET set) never reads other
- // fleets' bindings — it only ever WRITES its own (fleetbind.go's
- // fleetBindingHook/publishResidentFleetBindings, wired in RunAgent).
- // Reusing shouldSkipPublisherElection rather than re-testing the env var
- // here: both questions are exactly "is this box a fleet box", so one
- // predicate, already covered by TestShouldSkipPublisherElection, answers
- // both.
- isFleetBox := shouldSkipPublisherElection(os.Getenv)
+ // Hub only (fleet public routes spec §4.5 step 4): a fleet box
+ // (CARLOS_FLEET set) never reads other fleets' bindings — it only ever
+ // WRITES its own (fleetbind.go's fleetBindingHook/
+ // publishResidentFleetBindings, wired in RunAgent) — and a platform box
+ // that is not the hub holds no row the edge's fleet arm serves.
+ hub := hubArmed(os.Getenv)
// An offline move's participants keep their reports current between the
// passes below (finding 7); idle, it reads nothing.
go offlineReassertLoop(ctx, store)
@@ -3891,7 +3889,7 @@ func instancesLoop(reg *registry.Registry, writes hostwrite.Config, bs *buildSta
if err := aliasPassReporting(ctx, store, reg, &aliasClaimCache, boxAssetAuthority, cfg.Region); err != nil {
log.Printf("agent: instances alias pass: %v", err)
}
- if !isFleetBox {
+ if hub {
if err := ReconcileFleetBindings(ctx, store, reg); err != nil {
log.Printf("agent: fleet bindings reconcile: %v", err)
}
diff --git a/internal/host/fleetbind.go b/internal/host/fleetbind.go
index 34e023605..924655ea8 100644
--- a/internal/host/fleetbind.go
+++ b/internal/host/fleetbind.go
@@ -175,18 +175,39 @@ func WriteFleetBinding(ctx context.Context, s release.Store, b FleetBinding, tak
return nil
}
-// ReconcileFleetBindings is the platform-side half of fleet routing: for
-// every fleets/<fleet>/bindings/<host>.json object published under any
-// fleet, if the route registered for that host is actually PLACED on that
-// SAME fleet (registry.FleetPlacement(rt.Region) == the binding's own
-// Fleet) and its FleetBox doesn't already match, stamp it via SetFleetBox.
+// bindingsAfterChecks is a test seam, nil in production: when set,
+// ReconcileFleetBindings calls it with the binding's host after the pass's
+// pre-checks and before SetFleetBoxIf, so a test can move the row in between
+// and prove the write, not the checks, decides.
+var bindingsAfterChecks func(host string)
+
+// ReconcileFleetBindings is the hub-side half of fleet routing: for every
+// fleets/<fleet>/bindings/<host>.json object published under any fleet, if
+// the object's key is fleetBindingKey(b.Fleet, b.Host) for its own body, the
+// route registered for that host is actually PLACED on that SAME fleet
+// (registry.FleetPlacement(rt.Region) == the binding's own Fleet) and its
+// FleetBox doesn't already match, stamp it via SetFleetBoxIf.
+//
+// The key check comes first because the key is the only part of a binding
+// the hub can attribute to a fleet: a fleet box writes through the store
+// door, which lets it write anything under fleets/<own>/, so the body's
+// Fleet and Host are whatever the box chose to say. A body naming another
+// fleet or host than its key is skipped and logged (fleet public routes
+// spec §4.5 step 1).
+//
+// The pre-checks below (route exists, not a sidecar, placed on the
+// binding's fleet, FleetBox differs) are a cheap filter and decide nothing:
+// SetFleetBoxIf is one conditional write that judges placement, kind and
+// membership (the label must be an ACTIVE box of the binding's fleet) at
+// the instant of the write, so a row that moves to another fleet between
+// the checks and the write is not stamped by the old fleet's box (R2-3).
//
-// The fleet-placement check is a v1 trust-boundary requirement, not a
+// The fleet-placement condition is a trust-boundary requirement, not a
// nicety: fleet boxes are outbound-only, but nothing at the bucket layer
// stops fleet A's box from publishing a binding that names a host actually
// placed on fleet B (a same-named host collision, or a stale/rewritten
-// object) — without this check that binding could silently override fleet
-// B's own routing for a host fleet A's box has no business serving. There
+// object) — without it that binding could silently override fleet B's own
+// routing for a host fleet A's box has no business serving. There
// is deliberately no "newest wins" tie-break for a cross-fleet collision:
// two bindings for the exact same (fleet, host) pair cannot exist (the key
// IS fleet+host), and a binding whose fleet doesn't match the route's own
@@ -199,14 +220,15 @@ func WriteFleetBinding(ctx context.Context, s release.Store, b FleetBinding, tak
//
// s must be an UNPREFIXED store handle (see fleetBindingKey) — this walks
// the same absolute "fleets/" keys WriteFleetBinding writes, and is only
-// ever called on platform boxes, which never set CARLOS_STATUS_PREFIX in
-// the first place.
+// ever called on the hub (hubArmed), which never sets CARLOS_STATUS_PREFIX
+// in the first place.
//
// Corrupt objects and per-key read failures are logged and skipped, never
// fatal — the loadBoxes precedent (internal/status/fleet.go:197-216): one
// bad binding must not blank out routing for every other fleet host. A
// missing route, or one not placed on the binding's own fleet, is silently
-// skipped too — neither is this binding's to stamp.
+// skipped too — neither is this binding's to stamp. A write that changes no
+// row is logged: the binding no longer applies.
func ReconcileFleetBindings(ctx context.Context, s release.Store, reg *registry.Registry) error {
fleetDirs, err := s.ListDirs(ctx, "fleets/")
if err != nil {
@@ -229,6 +251,10 @@ func ReconcileFleetBindings(ctx context.Context, s release.Store, reg *registry.
log.Printf("host: fleet bindings: skipping %s: corrupt binding: %v", key, err)
continue
}
+ if key != fleetBindingKey(b.Fleet, b.Host) {
+ log.Printf("host: fleet bindings: skipping %s: body names fleet %q host %q, not its key", key, b.Fleet, b.Host)
+ continue
+ }
rt, err := reg.Get(b.Host)
if err != nil {
log.Printf("host: fleet bindings: read route %s: %v", b.Host, err)
@@ -237,7 +263,7 @@ func ReconcileFleetBindings(ctx context.Context, s release.Store, reg *registry.
if rt == nil {
continue // no matching route on this platform box
}
- // Never stamp a sidecar. SetFleetBox on a fleet-placed route is
+ // Never stamp a sidecar. SetFleetBoxIf on a fleet-placed route is
// precisely what turns the edge's fleet dispatch arm into a live
// proxy, so this reader is the last gate on the chain and it
// refuses on kind rather than trusting its input.
@@ -261,8 +287,16 @@ func ReconcileFleetBindings(ctx context.Context, s release.Store, reg *registry.
if rt.FleetBox == b.Box {
continue
}
- if err := reg.SetFleetBox(b.Host, b.Box); err != nil {
+ if bindingsAfterChecks != nil {
+ bindingsAfterChecks(b.Host)
+ }
+ changed, err := reg.SetFleetBoxIf(b.Host, b.Fleet, b.Box)
+ if err != nil {
log.Printf("host: fleet bindings: stamp %s -> %s: %v", b.Host, b.Box, err)
+ continue
+ }
+ if !changed {
+ log.Printf("host: fleet bindings: %s -> %s/%s no longer applies (row moved, or not an active box of the fleet)", b.Host, b.Fleet, b.Box)
}
}
}
@@ -356,7 +390,7 @@ func publishResidentFleetBindings(store release.Store, fleet, box string, reg *r
//
// Sidecar routes (Kind "sidecar") are excluded. Nothing routes to a sidecar,
// so a binding claiming a box serves it is a lie the platform side then acts
-// on: ReconcileFleetBindings stamps SetFleetBox from it, and a fleet-placed
+// on: ReconcileFleetBindings stamps SetFleetBoxIf from it, and a fleet-placed
// route is exactly what the edge's fleet dispatch arm turns into a live
// internet-facing proxy. Filtered at the publisher rather than at the
// reconciler because this is the only place that decides what a box CLAIMS —
diff --git a/internal/host/fleetbind_door_test.go b/internal/host/fleetbind_door_test.go
new file mode 100644
index 000000000..fbcff8d61
--- /dev/null
+++ b/internal/host/fleetbind_door_test.go
@@ -0,0 +1,250 @@
+package host
+
+import (
+ "context"
+ "database/sql"
+ "encoding/json"
+ "net/http/httptest"
+ "net/url"
+ "path/filepath"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/domains"
+ "github.com/carlosframework/platform/internal/edge"
+ "github.com/carlosframework/platform/internal/fleetapi"
+ "github.com/carlosframework/platform/internal/registry"
+ "github.com/carlosframework/platform/internal/release"
+)
+
+// Bindings through the authenticated store door (fleet public routes,
+// Task 1; spec §8 test 9). A fleet box writes its bindings through the
+// hub's store door, which lets it write anything under fleets/<own>/. The
+// key is therefore the one part of a binding the hub can attribute to a
+// fleet; the body is whatever the box chose to say. These tests stand up
+// the real door (a real edge, the registry-backed credential table, the
+// real ACL, a DirStore behind it) as newFSKWorld does, have a box write
+// through it, and run the hub's bindings pass over the bucket.
+
+// bindDoor is the hub side: its registry, the bucket behind the door, and
+// the door's URL.
+type bindDoor struct {
+ reg *registry.Registry
+ regPath string
+ store *release.DirStore
+ srvURL string
+}
+
+// newBindDoor opens the hub's registry, lets seed register fleets, boxes
+// and rows (seedFleetRoute), then builds the edge over it, so the door's
+// credential table and fleet-to-account snapshot hold what seed wrote.
+func newBindDoor(t *testing.T, seed func(reg *registry.Registry)) *bindDoor {
+ t.Helper()
+ d := &bindDoor{
+ regPath: filepath.Join(t.TempDir(), "registry.db"),
+ store: release.NewDirStore(t.TempDir()),
+ }
+ reg, err := registry.Open(d.regPath)
+ if err != nil {
+ t.Fatalf("open registry: %v", err)
+ }
+ t.Cleanup(func() { _ = reg.Close() })
+ d.reg = reg
+ seed(reg)
+
+ _, pubB64, err := release.GenerateKey()
+ if err != nil {
+ t.Fatal(err)
+ }
+ pub, err := release.ParsePublicKey(pubB64, "test")
+ if err != nil {
+ t.Fatal(err)
+ }
+ e, err := edge.New(reg, nil)
+ if err != nil {
+ t.Fatalf("edge.New: %v", err)
+ }
+ srv := httptest.NewServer(e)
+ t.Cleanup(srv.Close)
+ d.srvURL = srv.URL
+ u, err := url.Parse(srv.URL)
+ if err != nil {
+ t.Fatal(err)
+ }
+ e.EnableStatic(d.store, pub, filepath.Join(t.TempDir(), "cache"))
+ e.EnableTunnels(edge.NewTunnelHub(u.Hostname(), nil))
+ if err := e.Reload(); err != nil {
+ t.Fatalf("Reload: %v", err)
+ }
+ return d
+}
+
+// boxStore is box-1 of fleet's deployment store: the door, dialed with the
+// box's own channel name and token, as openDeployStoreEnv builds it.
+func (d *bindDoor) boxStore(t *testing.T, fleet string) release.Store {
+ t.Helper()
+ s, err := fleetapi.New(d.srvURL, fleet+"/box-1", fleetBoxToken(fleet, "box-1"))
+ if err != nil {
+ t.Fatalf("fleetapi.New(%s/box-1): %v", fleet, err)
+ }
+ return s
+}
+
+// fleetBox reads host's FleetBox on the hub.
+func (d *bindDoor) fleetBox(t *testing.T, host string) string {
+ t.Helper()
+ rt, err := d.reg.Get(host)
+ if err != nil || rt == nil {
+ t.Fatalf("Get(%s) = %v, %v", host, rt, err)
+ }
+ return rt.FleetBox
+}
+
+// inBucket fails the test unless the bucket holds key with a binding naming
+// fleet and box, so a refusal below is a refusal of an object that arrived.
+func (d *bindDoor) inBucket(t *testing.T, key, fleet, box string) {
+ t.Helper()
+ body, _, err := d.store.Get(context.Background(), key)
+ if err != nil {
+ t.Fatalf("the box's write did not reach the bucket at %s: %v", key, err)
+ }
+ var b FleetBinding
+ if err := json.Unmarshal(body, &b); err != nil {
+ t.Fatalf("%s: %v", key, err)
+ }
+ if b.Fleet != fleet || b.Box != box {
+ t.Fatalf("%s holds fleet %q box %q, want %q %q", key, b.Fleet, b.Box, fleet, box)
+ }
+}
+
+// TestForgedBindingsChangeNothing: away's box-1 writes, through its own
+// door, a binding for home's host naming fleet home (the body lies about
+// the fleet its key is under) and a binding for away's host naming a box
+// away never registered. The pass applies neither. The positive controls,
+// run as a second pass because the box-7 binding and away's correct one
+// share a key (preflight #20): away's own correct binding stamps away's
+// row, and home's own box stamps home's, so both rows could be bound and
+// the first pass refused on the key and the membership alone.
+func TestForgedBindingsChangeNothing(t *testing.T) {
+ ctx := context.Background()
+ const homeHost, awayHost = "shop.home.example.com", "shop.away.example.com"
+ d := newBindDoor(t, func(reg *registry.Registry) {
+ seedFleetRoute(t, reg, homeHost, "home", domains.Sqid(7), "box-1")
+ seedFleetRoute(t, reg, awayHost, "away", domains.Sqid(8), "box-1")
+ })
+ away := d.boxStore(t, "away")
+
+ forgedKey := fleetBindingKey("away", homeHost)
+ forged, err := json.Marshal(FleetBinding{Host: homeHost, Fleet: "home", Box: "box-1", BoundAt: time.Now().UnixMilli()})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := away.Put(ctx, forgedKey, forged, ""); err != nil {
+ t.Fatalf("away's box writing under its own prefix: %v", err)
+ }
+ if err := WriteFleetBinding(ctx, away, FleetBinding{Host: awayHost, Fleet: "away", Box: "box-7", BoundAt: time.Now().UnixMilli()}, true); err != nil {
+ t.Fatalf("away's box writing a box-7 binding: %v", err)
+ }
+ d.inBucket(t, forgedKey, "home", "box-1")
+ d.inBucket(t, fleetBindingKey("away", awayHost), "away", "box-7")
+
+ if err := ReconcileFleetBindings(ctx, d.store, d.reg); err != nil {
+ t.Fatalf("ReconcileFleetBindings: %v", err)
+ }
+ if got := d.fleetBox(t, homeHost); got != "" {
+ t.Errorf("home's host FleetBox = %q after away's box forged a binding for it, want empty", got)
+ }
+ if got := d.fleetBox(t, awayHost); got != "" {
+ t.Errorf("away's host FleetBox = %q after a binding naming an unregistered box, want empty", got)
+ }
+
+ // Positive controls, second pass.
+ if err := WriteFleetBinding(ctx, away, FleetBinding{Host: awayHost, Fleet: "away", Box: "box-1", BoundAt: time.Now().UnixMilli() + 1}, true); err != nil {
+ t.Fatalf("away's box writing its correct binding: %v", err)
+ }
+ if err := WriteFleetBinding(ctx, d.boxStore(t, "home"), FleetBinding{Host: homeHost, Fleet: "home", Box: "box-1", BoundAt: time.Now().UnixMilli()}, true); err != nil {
+ t.Fatalf("home's box writing its correct binding: %v", err)
+ }
+ d.inBucket(t, fleetBindingKey("away", awayHost), "away", "box-1")
+ if err := ReconcileFleetBindings(ctx, d.store, d.reg); err != nil {
+ t.Fatalf("ReconcileFleetBindings (second pass): %v", err)
+ }
+ if got := d.fleetBox(t, awayHost); got != "box-1" {
+ t.Errorf("away's host FleetBox = %q after away's own correct binding, want box-1", got)
+ }
+ if got := d.fleetBox(t, homeHost); got != "box-1" {
+ t.Errorf("home's host FleetBox = %q after home's own correct binding, want box-1", got)
+ }
+}
+
+// TestStaleBindingCannotStampTheNewPlacement (R2-3): the pass validates a
+// binding against the row, then writes. A row that moves to another fleet
+// between the two must not be stamped by the old fleet's box. Deterministic
+// through bindingsAfterChecks: home's box-1 writes a correct binding; the
+// row was stamped box-2 first so the pre-checks pass (FleetBox differs);
+// the hook then moves the row to away (SetPlacement) and clears its
+// FleetBox, as PutForward does on a Region change; the pass's write must
+// then change nothing.
+func TestStaleBindingCannotStampTheNewPlacement(t *testing.T) {
+ ctx := context.Background()
+ const host = "shop.home.example.com"
+ acct := domains.Sqid(7)
+ d := newBindDoor(t, func(reg *registry.Registry) {
+ seedFleetRoute(t, reg, host, "home", acct, "box-1", "box-2")
+ seedFleetRoute(t, reg, "", "away", acct, "box-1")
+ })
+ changed, err := d.reg.SetFleetBoxIf(host, "home", "box-2")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !changed {
+ t.Fatal("seeding: SetFleetBoxIf(home, box-2) changed no row, so the fixture cannot bind")
+ }
+ if err := WriteFleetBinding(ctx, d.boxStore(t, "home"), FleetBinding{Host: host, Fleet: "home", Box: "box-1", BoundAt: time.Now().UnixMilli()}, true); err != nil {
+ t.Fatalf("home's box writing its binding: %v", err)
+ }
+ d.inBucket(t, fleetBindingKey("home", host), "home", "box-1")
+
+ moved := 0
+ bindingsAfterChecks = func(h string) {
+ if h != host {
+ return
+ }
+ moved++
+ if err := d.reg.SetPlacement(host, registry.PlacementTarget("away")); err != nil {
+ t.Errorf("SetPlacement: %v", err)
+ }
+ db, err := sql.Open("sqlite", d.regPath)
+ if err != nil {
+ t.Errorf("open registry file: %v", err)
+ return
+ }
+ defer db.Close()
+ res, err := db.Exec(`UPDATE routes SET fleet_box = '' WHERE host = ?`, host)
+ if err != nil {
+ t.Errorf("clear fleet_box: %v", err)
+ return
+ }
+ if n, _ := res.RowsAffected(); n != 1 {
+ t.Errorf("clear fleet_box affected %d rows, want 1", n)
+ }
+ }
+ t.Cleanup(func() { bindingsAfterChecks = nil })
+
+ if err := ReconcileFleetBindings(ctx, d.store, d.reg); err != nil {
+ t.Fatalf("ReconcileFleetBindings: %v", err)
+ }
+ if moved != 1 {
+ t.Fatalf("the hook ran %d times, want 1: the binding never reached the write", moved)
+ }
+ rt, err := d.reg.Get(host)
+ if err != nil || rt == nil {
+ t.Fatalf("Get: %v, %v", rt, err)
+ }
+ if rt.Region != registry.PlacementTarget("away") {
+ t.Fatalf("Region = %q, want fleet/away (the hook's move)", rt.Region)
+ }
+ if rt.FleetBox != "" {
+ t.Fatalf("FleetBox = %q: home's binding stamped a row placed on away", rt.FleetBox)
+ }
+}
diff --git a/internal/host/fleetbind_test.go b/internal/host/fleetbind_test.go
index ae54f9463..269bd4ab5 100644
--- a/internal/host/fleetbind_test.go
+++ b/internal/host/fleetbind_test.go
@@ -3,6 +3,8 @@ package host
import (
"bytes"
"context"
+ "crypto/sha256"
+ "encoding/hex"
"encoding/json"
"errors"
"log"
@@ -10,6 +12,7 @@ import (
"strings"
"testing"
+ "github.com/carlosframework/platform/internal/domains"
"github.com/carlosframework/platform/internal/registry"
"github.com/carlosframework/platform/internal/release"
)
@@ -248,13 +251,48 @@ func TestWriteFleetBindingSkipsWhenStoredIsLogicallyNewer(t *testing.T) {
// --- ReconcileFleetBindings ---------------------------------------------------
+// fleetBoxToken is the bearer token seedFleetRoute registers for a box, so a
+// door fixture can dial as that box.
+func fleetBoxToken(fleet, label string) string { return fleet + "-" + label + "-token" }
+
+// seedFleetRoute is the one fixture builder for binding tests in this package
+// (fleet public routes, Task 1; Astra plan R3 P1-1). A binding applies only
+// to a row placed on the binding's own fleet whose label is an active box of
+// that fleet (SetFleetBoxIf), so the builder seeds all three: the fleet,
+// owned by account; each label as an active box with fleetBoxToken's token;
+// and, when host is not "", an instance row placed fleet/<fleet>. A label
+// already active is kept, so one fleet can be seeded for several rows.
+//
+// It does not stamp the row: the pass under test is the stamp. Every test
+// that uses it asserts the pass's first SetFleetBoxIf changed the row (or,
+// where the row is stamped directly, that the write answered true) before
+// any refusal or preservation assertion, so a refusal can never pass
+// against a fixture in which nothing could bind.
+func seedFleetRoute(t *testing.T, reg *registry.Registry, host, fleet, account string, labels ...string) {
+ t.Helper()
+ if err := reg.UpsertFleet(registry.Fleet{Name: fleet, Account: account, Bucket: fleet + "-data"}); err != nil {
+ t.Fatalf("UpsertFleet(%s): %v", fleet, err)
+ }
+ for _, label := range labels {
+ sum := sha256.Sum256([]byte(fleetBoxToken(fleet, label)))
+ err := reg.AddFleetBox(registry.FleetBox{Fleet: fleet, Label: label, TokenHash: hex.EncodeToString(sum[:]), Status: "active"})
+ if err != nil && !errors.Is(err, registry.ErrFleetBoxActive) {
+ t.Fatalf("AddFleetBox(%s/%s): %v", fleet, label, err)
+ }
+ }
+ if host == "" {
+ return
+ }
+ if err := reg.Upsert(registry.Route{Host: host, Kind: "instance", Region: registry.PlacementTarget(fleet)}); err != nil {
+ t.Fatalf("upsert %s: %v", host, err)
+ }
+}
+
func TestReconcileFleetBindingsStampsMatchingRoute(t *testing.T) {
ctx := context.Background()
s := release.NewDirStore(t.TempDir())
reg := testRegistry(t)
- if err := reg.Upsert(registry.Route{Host: "one.example.com", Kind: "instance", Region: "fleet/pi"}); err != nil {
- t.Fatalf("upsert: %v", err)
- }
+ seedFleetRoute(t, reg, "one.example.com", "pi", domains.Sqid(7), "amber-gliding")
if err := WriteFleetBinding(ctx, s, FleetBinding{
Host: "one.example.com", Fleet: "pi", Box: "amber-gliding", BoundAt: 1000,
}, true); err != nil {
@@ -276,7 +314,7 @@ func TestReconcileFleetBindingsStampsMatchingRoute(t *testing.T) {
// A route with no published binding at all — a non-fleet route, or a fleet
// route this platform box hasn't heard from yet — must be left completely
-// alone: ReconcileFleetBindings only ever calls SetFleetBox for a host it
+// alone: ReconcileFleetBindings only ever calls SetFleetBoxIf for a host it
// found a MATCHING binding for.
func TestReconcileFleetBindingsLeavesNonFleetRoutesAlone(t *testing.T) {
ctx := context.Background()
@@ -341,9 +379,7 @@ func TestReconcileFleetBindingsAppliesMatchingFleetPlacement(t *testing.T) {
ctx := context.Background()
s := release.NewDirStore(t.TempDir())
reg := testRegistry(t)
- if err := reg.Upsert(registry.Route{Host: "shared.example.com", Kind: "instance", Region: "fleet/pi"}); err != nil {
- t.Fatalf("upsert: %v", err)
- }
+ seedFleetRoute(t, reg, "shared.example.com", "pi", domains.Sqid(7), "pi-box")
if err := WriteFleetBinding(ctx, s, FleetBinding{
Host: "shared.example.com", Fleet: "pi", Box: "pi-box", BoundAt: 1000,
}, true); err != nil {
@@ -370,12 +406,8 @@ func TestReconcileFleetBindingsSkipsCorruptJSON(t *testing.T) {
ctx := context.Background()
s := release.NewDirStore(t.TempDir())
reg := testRegistry(t)
- if err := reg.Upsert(registry.Route{Host: "good.example.com", Kind: "instance", Region: "fleet/pi"}); err != nil {
- t.Fatalf("upsert good: %v", err)
- }
- if err := reg.Upsert(registry.Route{Host: "bad.example.com", Kind: "instance", Region: "fleet/pi"}); err != nil {
- t.Fatalf("upsert bad: %v", err)
- }
+ seedFleetRoute(t, reg, "good.example.com", "pi", domains.Sqid(7), "amber-gliding")
+ seedFleetRoute(t, reg, "bad.example.com", "pi", domains.Sqid(7), "amber-gliding")
if _, err := s.Put(ctx, "fleets/pi/bindings/bad.example.com.json", []byte("{ not json"), ""); err != nil {
t.Fatalf("seed corrupt object: %v", err)
}
@@ -405,16 +437,14 @@ func TestReconcileFleetBindingsSkipsCorruptJSON(t *testing.T) {
}
}
-// Already-stamped, matching FleetBox must not trigger a needless SetFleetBox
-// call — proven indirectly by asserting the value survives a second
-// reconcile pass unchanged.
+// Already-stamped, matching FleetBox must not trigger a needless SetFleetBoxIf
+// call — proven indirectly by asserting the value the first pass stamped
+// survives a second reconcile pass unchanged.
func TestReconcileFleetBindingsIdempotent(t *testing.T) {
ctx := context.Background()
s := release.NewDirStore(t.TempDir())
reg := testRegistry(t)
- if err := reg.Upsert(registry.Route{Host: "one.example.com", Kind: "instance", Region: "fleet/pi"}); err != nil {
- t.Fatalf("upsert: %v", err)
- }
+ seedFleetRoute(t, reg, "one.example.com", "pi", domains.Sqid(7), "amber-gliding")
if err := WriteFleetBinding(ctx, s, FleetBinding{
Host: "one.example.com", Fleet: "pi", Box: "amber-gliding", BoundAt: 1000,
}, true); err != nil {
@@ -424,13 +454,13 @@ func TestReconcileFleetBindingsIdempotent(t *testing.T) {
if err := ReconcileFleetBindings(ctx, s, reg); err != nil {
t.Fatalf("ReconcileFleetBindings pass %d: %v", i, err)
}
- }
- rt, err := reg.Get("one.example.com")
- if err != nil {
- t.Fatalf("Get: %v", err)
- }
- if rt.FleetBox != "amber-gliding" {
- t.Fatalf("FleetBox = %q, want amber-gliding", rt.FleetBox)
+ rt, err := reg.Get("one.example.com")
+ if err != nil {
+ t.Fatalf("Get: %v", err)
+ }
+ if rt.FleetBox != "amber-gliding" {
+ t.Fatalf("after pass %d: FleetBox = %q, want amber-gliding", i, rt.FleetBox)
+ }
}
}
@@ -595,7 +625,7 @@ func TestFleetBindingHookTakesOverFromAnotherBox(t *testing.T) {
// TestSidecarBindingIsNeverPublished: a fleet binding says "this box serves
// this host". Nothing routes to a sidecar, so publishing one would be a lie
// the platform-side reconciler then acts on — ReconcileFleetBindings stamps
-// SetFleetBox from it, and a fleet-placed route is exactly what the edge's
+// SetFleetBoxIf from it, and a fleet-placed route is exactly what the edge's
// fleet dispatch arm binds. The filter therefore lives in the publisher's own
// host selection, not in the reconciler that reads it back.
func TestSidecarBindingIsNeverPublished(t *testing.T) {
@@ -667,7 +697,7 @@ func TestFleetBindingHookNeverPublishesSidecar(t *testing.T) {
// binding is an untrusted claim written by another machine that upgrades on
// its own schedule: through a mixed-version roll, a fleet box still on an
// older binary keeps publishing sidecar bindings, and this platform box is
-// what acts on them. SetFleetBox is the act that hands a fleet-placed route to
+// what acts on them. SetFleetBoxIf is the act that hands a fleet-placed route to
// the edge's fleet dispatch arm, so it must refuse on kind independently of
// whoever wrote the object.
//
@@ -679,9 +709,7 @@ func TestReconcileFleetBindingsNeverStampsSidecar(t *testing.T) {
s := release.NewDirStore(t.TempDir())
reg := testRegistry(t)
const sidecarHost = "bot.eleven.bdm.sidecar.internal"
- if err := reg.Upsert(registry.Route{Host: "app.example.com", Kind: "instance", Region: "fleet/pi"}); err != nil {
- t.Fatalf("upsert instance: %v", err)
- }
+ seedFleetRoute(t, reg, "app.example.com", "pi", domains.Sqid(7), "box1")
if err := reg.Upsert(registry.Route{Host: sidecarHost, Kind: "sidecar", Region: "fleet/pi"}); err != nil {
t.Fatalf("upsert sidecar: %v", err)
}
diff --git a/internal/host/hub.go b/internal/host/hub.go
new file mode 100644
index 000000000..bdc7f36cf
--- /dev/null
+++ b/internal/host/hub.go
@@ -0,0 +1,13 @@
+package host
+
+import "strings"
+
+// hubArmed reports whether this box is the hub: the box that holds the
+// tunnel's reserved hostname (CARLOS_TUNNEL_HOST set) and is not itself a
+// fleet box (CARLOS_FLEET unset). Only the hub holds the rows the edge's
+// fleet arm serves, so only the hub runs the bindings pass (fleet public
+// routes spec §4.5 step 4); every other platform box reading every fleet's
+// bindings was work with nothing to apply.
+func hubArmed(getenv func(string) string) bool {
+ return strings.TrimSpace(getenv("CARLOS_TUNNEL_HOST")) != "" && getenv("CARLOS_FLEET") == ""
+}
diff --git a/internal/host/hub_test.go b/internal/host/hub_test.go
new file mode 100644
index 000000000..c7771bbbe
--- /dev/null
+++ b/internal/host/hub_test.go
@@ -0,0 +1,20 @@
+package host
+
+import "testing"
+
+func TestHubArmed(t *testing.T) {
+ for _, c := range []struct {
+ tunnelHost, fleet string
+ want bool
+ }{
+ {"tunnel.example.com", "", true},
+ {"tunnel.example.com", "home", false},
+ {"", "", false},
+ {" ", "", false},
+ } {
+ env := map[string]string{"CARLOS_TUNNEL_HOST": c.tunnelHost, "CARLOS_FLEET": c.fleet}
+ if got := hubArmed(func(k string) string { return env[k] }); got != c.want {
+ t.Errorf("hubArmed(CARLOS_TUNNEL_HOST=%q, CARLOS_FLEET=%q) = %v, want %v", c.tunnelHost, c.fleet, got, c.want)
+ }
+ }
+}
diff --git a/internal/registry/fleetbox_if_test.go b/internal/registry/fleetbox_if_test.go
new file mode 100644
index 000000000..bf4b66023
--- /dev/null
+++ b/internal/registry/fleetbox_if_test.go
@@ -0,0 +1,134 @@
+package registry
+
+import (
+ "errors"
+ "testing"
+)
+
+// fleetBoundRow is the one fixture builder for binding tests in this package
+// (fleet public routes, Task 1; Astra plan R3 P1-1). SetFleetBoxIf acts only
+// on a row placed on the binding's own fleet whose label is an active box of
+// that fleet, so a test that skips any of the three seeds asserts nothing:
+// every refusal would pass against a write that can never change a row. The
+// builder seeds all three (the fleet, each label as an active box, the row
+// placed fleet/<fleet>), stamps the row with the FIRST label, and fails the
+// test unless that write changed the row and the row reads it back, before
+// the caller makes any preservation or refusal assertion.
+//
+// A label already active on the fleet is kept, so a test can seed a second
+// row on a fleet it seeded before.
+func fleetBoundRow(t *testing.T, reg *Registry, host, fleet string, labels ...string) Route {
+ t.Helper()
+ if len(labels) == 0 {
+ t.Fatal("fleetBoundRow: no label to bind")
+ }
+ if err := reg.UpsertFleet(Fleet{Name: fleet, Account: "bah", Bucket: fleet + "-data"}); err != nil {
+ t.Fatalf("UpsertFleet(%s): %v", fleet, err)
+ }
+ for _, label := range labels {
+ err := reg.AddFleetBox(FleetBox{Fleet: fleet, Label: label, TokenHash: tokenHashA, Status: "active"})
+ if err != nil && !errors.Is(err, ErrFleetBoxActive) {
+ t.Fatalf("AddFleetBox(%s/%s): %v", fleet, label, err)
+ }
+ }
+ if err := reg.Upsert(Route{Host: host, Kind: "instance", Status: "ready", Region: PlacementTarget(fleet)}); err != nil {
+ t.Fatalf("Upsert(%s): %v", host, err)
+ }
+ changed, err := reg.SetFleetBoxIf(host, fleet, labels[0])
+ if err != nil {
+ t.Fatalf("SetFleetBoxIf(%s, %s, %s): %v", host, fleet, labels[0], err)
+ }
+ if !changed {
+ t.Fatalf("SetFleetBoxIf(%s, %s, %s) changed no row: the fixture cannot bind, so nothing after it would prove anything", host, fleet, labels[0])
+ }
+ got, err := reg.Get(host)
+ if err != nil || got == nil {
+ t.Fatalf("Get(%s) = %v, %v", host, got, err)
+ }
+ if got.FleetBox != labels[0] {
+ t.Fatalf("FleetBox = %q after a changed SetFleetBoxIf, want %q", got.FleetBox, labels[0])
+ }
+ return *got
+}
+
+// TestSetFleetBoxIfBindsPlacementKindAndMembership: the one statement judges
+// placement, kind and membership together (spec §4.5 step 2). A label of
+// another fleet, a detached label, an unregistered label and a sidecar row
+// change nothing, and an unknown host is no change rather than an error.
+func TestSetFleetBoxIfBindsPlacementKindAndMembership(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-1", TokenHash: tokenHashC, Status: "active"}); err != nil {
+ t.Fatal(err)
+ }
+
+ for _, c := range []struct{ fleet, label, why string }{
+ {"away", "box-1", "an active box of another fleet"},
+ {"home", "box-2", "a detached box of the row's own fleet"},
+ {"home", "box-9", "a label no fleet registered"},
+ } {
+ changed, err := reg.SetFleetBoxIf(host, c.fleet, c.label)
+ if err != nil {
+ t.Fatalf("SetFleetBoxIf(%s, %s): %v", c.fleet, c.label, err)
+ }
+ if changed {
+ t.Errorf("SetFleetBoxIf(%s, %s) changed the row: %s must not bind it", c.fleet, c.label, c.why)
+ }
+ got, err := reg.Get(host)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if got.FleetBox != "box-1" {
+ t.Errorf("after SetFleetBoxIf(%s, %s): FleetBox = %q, want box-1 kept", c.fleet, c.label, got.FleetBox)
+ }
+ }
+
+ const sidecar = "bot.example.com"
+ if err := reg.Upsert(Route{Host: sidecar, Kind: "sidecar", Region: PlacementTarget("home")}); err != nil {
+ t.Fatal(err)
+ }
+ changed, err := reg.SetFleetBoxIf(sidecar, "home", "box-1")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if changed {
+ t.Error("SetFleetBoxIf bound a sidecar row: stamping one hands it to the edge's fleet arm")
+ }
+ if got, err := reg.Get(sidecar); err != nil || got.FleetBox != "" {
+ t.Errorf("sidecar FleetBox = %q (err %v), want empty", got.FleetBox, err)
+ }
+
+ changed, err = reg.SetFleetBoxIf("nope.example.com", "home", "box-1")
+ if err != nil || changed {
+ t.Errorf("SetFleetBoxIf on an unknown host = %v, %v; want false, nil", changed, 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.
+func TestSetFleetBoxIfOverRemote(t *testing.T) {
+ reg, _ := remoteTestRegistry(t)
+ const host = "shop.example.com"
+ fleetBoundRow(t, reg, host, "home", "box-1")
+ 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-1", TokenHash: tokenHashC, Status: "active"}); err != nil {
+ t.Fatal(err)
+ }
+ changed, err := reg.SetFleetBoxIf(host, "away", "box-1")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if changed {
+ t.Error("remote SetFleetBoxIf bound a row to another fleet's box")
+ }
+}
diff --git a/internal/registry/fleets_test.go b/internal/registry/fleets_test.go
index ca052b334..39ccc134c 100644
--- a/internal/registry/fleets_test.go
+++ b/internal/registry/fleets_test.go
@@ -387,7 +387,7 @@ func TestFingerprintChangesOnTokenRotation(t *testing.T) {
// TestFingerprintChangesOnFleetBoxRestamp is the Task 10 regression pin —
// the defect the two-box e2e (internal/edge/fleet_e2e_test.go) surfaced. A
-// failover restamps routes.fleet_box (ReconcileFleetBindings -> SetFleetBox)
+// failover restamps routes.fleet_box (ReconcileFleetBindings -> SetFleetBoxIf)
// between two labels of the SAME length, which is the common case for fleet
// box labels ("box-a"/"box-b", "pi-1"/"pi-2"). Before the fleet-placement
// projection was added to Fingerprint, that write changed nothing the
@@ -398,16 +398,18 @@ func TestFingerprintChangesOnTokenRotation(t *testing.T) {
// there to SIGHUP.
func TestFingerprintChangesOnFleetBoxRestamp(t *testing.T) {
reg := openTestRegistry(t)
- if err := reg.Upsert(Route{Host: "app.example", Kind: "instance", Region: PlacementTarget("pi"), FleetBox: "box-a"}); err != nil {
- t.Fatal(err)
- }
+ fleetBoundRow(t, reg, "app.example", "pi", "box-a", "box-b")
before, err := reg.Fingerprint()
if err != nil {
t.Fatal(err)
}
- if err := reg.SetFleetBox("app.example", "box-b"); err != nil {
+ changed, err := reg.SetFleetBoxIf("app.example", "pi", "box-b")
+ if err != nil {
t.Fatal(err)
}
+ if !changed {
+ t.Fatal("SetFleetBoxIf restamp to box-b changed no row")
+ }
after, err := reg.Fingerprint()
if err != nil {
t.Fatal(err)
diff --git a/internal/registry/forward.go b/internal/registry/forward.go
new file mode 100644
index 000000000..4d8838fa3
--- /dev/null
+++ b/internal/registry/forward.go
@@ -0,0 +1,40 @@
+package registry
+
+// SetFleetBoxIf stamps label as the fleet box CURRENTLY serving host, in one
+// conditional statement (fleet public routes spec §4.5 step 2): the row
+// changes only while it is placed on fleet ("fleet/<fleet>" in its Region
+// column), is not a sidecar, and label is an ACTIVE box of that same fleet.
+// It answers whether a row changed.
+//
+// A binding is a claim another machine wrote, so the check and the write
+// cannot be two statements: a row validated for one fleet could move to
+// another fleet between them, and the old fleet's box would then steer it.
+// The fleets and fleet_boxes tables live in this same file, so SQLite judges
+// placement, kind and membership in the same write.
+//
+// No row affected is not an error: an unknown host, a row placed elsewhere,
+// a sidecar and a label that is not an active box of the fleet all mean the
+// binding does not apply. This is the only door that writes fleet_box; no
+// door clears a hand row's (Upsert keeps a non-empty value). It is distinct
+// from SetPlacement, which writes the placement TARGET, not the box
+// currently fulfilling it.
+func (r *Registry) SetFleetBoxIf(host, fleet, label string) (bool, error) {
+ if r.remote != nil {
+ out, err := r.remote.call(nil, remoteRequest{Method: "SetFleetBoxIf", Host: host, Fleet: fleet, Label: label}, nil)
+ return out.Changed, err
+ }
+
+ res, err := r.sql.Exec(`
+UPDATE routes SET fleet_box = ?
+ WHERE host = ?
+ AND region = 'fleet/' || ?
+ AND kind <> 'sidecar'
+ AND EXISTS (SELECT 1 FROM fleet_boxes
+ WHERE fleet = ? AND label = ? AND status = 'active')`,
+ label, host, fleet, fleet, label)
+ if err != nil {
+ return false, err
+ }
+ n, err := res.RowsAffected()
+ return n > 0, err
+}
diff --git a/internal/registry/registry.go b/internal/registry/registry.go
index e4a374d29..443045b59 100644
--- a/internal/registry/registry.go
+++ b/internal/registry/registry.go
@@ -181,8 +181,8 @@ type Route struct {
// route ("" = no binding) — distinct from Region, which carries the
// placement TARGET (see FleetPlacement/PlacementTarget, fleets.go); a
// route can want "fleet/pi" and not yet have a box assigned. Written only
- // by SetFleetBox; Upsert preserves non-empty values — see Environment's
- // comment for why.
+ // by SetFleetBoxIf (forward.go); Upsert preserves non-empty values — see
+ // Environment's comment for why.
FleetBox string
// Caps is the OPERATOR-granted capability tokens for this route ON THIS
@@ -1296,8 +1296,9 @@ func (r *Registry) Delete(host string) error {
// SetEnvironment (`carlos route -environment -`), SetCaps (`carlos route
// -revoke`), SetTunnel (`carlos route -tunnel -`), SetUnit (`carlos route
// -unit -`), SetReplication (`carlos route -replication -`), SetSeed,
-// SetFleetBox, SetArgs, SetWorkerLimits, SetUpdateSettings, SetBuildState, and for
-// `provisioned` the row's own deletion.
+// SetArgs, SetWorkerLimits, SetUpdateSettings, SetBuildState, and for
+// `provisioned` the row's own deletion. `fleet_box` has no clearing door:
+// SetFleetBoxIf only stamps it.
//
// `replication` is the one column with a SECOND clearing door, and it is not
// an operator's: SetHibernate clears it when a route stops hibernating,
@@ -2747,31 +2748,6 @@ func (r *Registry) SetTunnel(host, tunnel string) error {
return nil
}
-// SetFleetBox stamps the label of the fleet box CURRENTLY serving this
-// route as a narrow UPDATE — same rationale and same "error on an unmatched
-// host" contract as SetTunnel. label == "" clears the binding; this is a
-// placement pass's door, distinct from SetPlacement (which writes the
-// placement TARGET, not the box currently fulfilling it).
-func (r *Registry) SetFleetBox(host, label string) error {
- if r.remote != nil {
- _, err := r.remote.call(nil, remoteRequest{Method: "SetFleetBox", Host: host, Label: label}, nil)
- return err
- }
-
- res, err := r.sql.Exec(`UPDATE routes SET fleet_box = ? WHERE host = ?`, label, host)
- if err != nil {
- return err
- }
- n, err := res.RowsAffected()
- if err != nil {
- return err
- }
- if n == 0 {
- return fmt.Errorf("no route for host %q", host)
- }
- return nil
-}
-
// SetPlacement repoints a route's placement TARGET — stored in the Region
// column, which already carries a route's residency constraint and, as of
// this task, doubles as where a fleet-bound route wants to run (see
@@ -2782,7 +2758,7 @@ func (r *Registry) SetFleetBox(host, label string) error {
// FleetPlacement to tell the two apart; it simply answers ("", false) for a
// bare code, same as for anything else this setter refuses).
//
-// Same "error on an unmatched host" contract as SetTunnel/SetFleetBox: a
+// Same "error on an unmatched host" contract as SetTunnel: a
// human or a placement pass typing a hostname here should get a refusal on a
// typo, not a silent no-op.
func (r *Registry) SetPlacement(host, target string) error {
@@ -3693,7 +3669,7 @@ func (r *Registry) DeletePath(host, prefix string) error {
//
// `region` and `fleet_box` are hashed for the customer-fleets placement path,
// and the two-box e2e (internal/edge/fleet_e2e_test.go) is what proved they
-// have to be: a failover restamp (ReconcileFleetBindings -> SetFleetBox,
+// have to be: a failover restamp (ReconcileFleetBindings -> SetFleetBoxIf,
// box-a -> box-b) left the old aggregate byte-identical and the edge kept
// dispatching to the box that had died — rule 1 pointing at a corpse the
// moment it re-dialed, with no operator around to SIGHUP, because a restamp
diff --git a/internal/registry/registry_test.go b/internal/registry/registry_test.go
index 049c2ea34..03540d320 100644
--- a/internal/registry/registry_test.go
+++ b/internal/registry/registry_test.go
@@ -2061,43 +2061,41 @@ func TestSetStatusNamed(t *testing.T) {
}
}
-// TestSetFleetBoxRoundTrips mirrors TestSetTunnel's shape: SetFleetBox is a
-// narrow UPDATE on the new fleet_box column, which records which fleet box
-// is CURRENTLY serving a placed route (distinct from Region/placement
-// target, which says where the route WANTS to run).
-func TestSetFleetBoxRoundTrips(t *testing.T) {
+// TestSetFleetBoxIfRoundTrips: SetFleetBoxIf is a narrow conditional UPDATE
+// on the fleet_box column, which records which fleet box is CURRENTLY
+// serving a placed route (distinct from Region/placement target, which says
+// where the route WANTS to run). The fixture stamps it and reads it back;
+// a second stamp to another active box of the same fleet moves it. Clearing
+// is not this door's (fleet public routes, Task 1): no production caller
+// ever cleared a hand row's binding.
+func TestSetFleetBoxIfRoundTrips(t *testing.T) {
reg := openTestRegistry(t)
- if err := reg.Upsert(Route{Host: "demo.example", Kind: "instance", Status: "ready"}); err != nil {
- t.Fatal(err)
- }
- if err := reg.SetFleetBox("demo.example", "pi-1"); err != nil {
- t.Fatal(err)
- }
- got, err := reg.Get("demo.example")
+ fleetBoundRow(t, reg, "demo.example", "home", "box-1", "box-2")
+ changed, err := reg.SetFleetBoxIf("demo.example", "home", "box-2")
if err != nil {
t.Fatal(err)
}
- if got.FleetBox != "pi-1" {
- t.Fatalf("FleetBox = %q, want pi-1", got.FleetBox)
+ if !changed {
+ t.Fatal("SetFleetBoxIf to another active box of the row's fleet changed nothing")
}
- if err := reg.SetFleetBox("demo.example", ""); err != nil {
- t.Fatal(err)
- }
- got, err = reg.Get("demo.example")
+ got, err := reg.Get("demo.example")
if err != nil {
t.Fatal(err)
}
- if got.FleetBox != "" {
- t.Fatalf("SetFleetBox clear failed: %q", got.FleetBox)
+ if got.FleetBox != "box-2" {
+ t.Fatalf("FleetBox = %q, want box-2", got.FleetBox)
}
}
-// Same contract as TestSetTunnelUnknownHostErrors: a human/reconciler typo'd
-// host must get a refusal, not a silent no-op.
-func TestSetFleetBoxUnknownHostErrors(t *testing.T) {
+// A binding whose row is gone simply no longer applies (spec §4.5): an
+// unknown host is no change, not an error. This retires SetFleetBox's
+// "error on an unmatched host" contract, which only a typing human needed,
+// and no human types this one.
+func TestSetFleetBoxIfUnknownHostIsNoChange(t *testing.T) {
reg := openTestRegistry(t)
- if err := reg.SetFleetBox("nope.example.com", "pi-1"); err == nil {
- t.Fatal("SetFleetBox on an unknown host: got nil error, want one")
+ changed, err := reg.SetFleetBoxIf("nope.example.com", "home", "box-1")
+ if err != nil || changed {
+ t.Fatalf("SetFleetBoxIf on an unknown host = %v, %v; want false, nil", changed, err)
}
}
@@ -2106,14 +2104,9 @@ func TestSetFleetBoxUnknownHostErrors(t *testing.T) {
// pass stamped.
func TestUpsertPreservesFleetBox(t *testing.T) {
reg := openTestRegistry(t)
- base := Route{Host: "demo.example", Kind: "instance", Status: "ready"}
- if err := reg.Upsert(base); err != nil {
- t.Fatal(err)
- }
- if err := reg.SetFleetBox("demo.example", "pi-1"); err != nil {
- t.Fatal(err)
- }
+ base := fleetBoundRow(t, reg, "demo.example", "home", "box-1")
// A full-row re-Upsert with zero-value FleetBox must not unbind.
+ base.FleetBox = ""
if err := reg.Upsert(base); err != nil {
t.Fatal(err)
}
@@ -2121,11 +2114,11 @@ func TestUpsertPreservesFleetBox(t *testing.T) {
if err != nil {
t.Fatal(err)
}
- if got.FleetBox != "pi-1" {
+ if got.FleetBox != "box-1" {
t.Fatalf("Upsert clobbered FleetBox: %q", got.FleetBox)
}
// An explicit non-empty value still wins.
- base.FleetBox = "pi-2"
+ base.FleetBox = "box-2"
if err := reg.Upsert(base); err != nil {
t.Fatal(err)
}
@@ -2133,20 +2126,9 @@ func TestUpsertPreservesFleetBox(t *testing.T) {
if err != nil {
t.Fatal(err)
}
- if got.FleetBox != "pi-2" {
+ if got.FleetBox != "box-2" {
t.Fatalf("FleetBox = %q, want an explicit Upsert value to win", got.FleetBox)
}
- // Clearing has exactly one door: SetFleetBox(host, "").
- if err := reg.SetFleetBox("demo.example", ""); err != nil {
- t.Fatal(err)
- }
- got, err = reg.Get("demo.example")
- if err != nil {
- t.Fatal(err)
- }
- if got.FleetBox != "" {
- t.Fatalf("SetFleetBox clear failed: %q", got.FleetBox)
- }
}
// A registry file written BEFORE the fleet_box column existed must still
diff --git a/internal/registry/remote_dispatch.go b/internal/registry/remote_dispatch.go
index 13383e99a..39ad6b00c 100644
--- a/internal/registry/remote_dispatch.go
+++ b/internal/registry/remote_dispatch.go
@@ -290,8 +290,8 @@ func (r *Registry) dispatchRemote(ctx context.Context, q remoteRequest, callback
err = r.SetEnvironment(q.Host, q.Env)
case "SetTunnel":
err = r.SetTunnel(q.Host, q.Tunnel)
- case "SetFleetBox":
- err = r.SetFleetBox(q.Host, q.Label)
+ case "SetFleetBoxIf":
+ out.Changed, err = r.SetFleetBoxIf(q.Host, q.Fleet, q.Label)
case "SetPlacement":
err = r.SetPlacement(q.Host, q.Target)
case "SetEnvironments":