carlos / platform Public

Managed fleets 1b task 3: a fleet box mints only its own records

ReconcileConfig.FleetBox is this box's label, from resolveFleetIdentity, set
only when the identity's fleet is the one CARLOS_REGION places the box on.
ownsRecord (true off a fleet, for an unlabelled record, or for the box's own
label) is asked after inScope in the record scan, so another box's record is
skipped like an out-of-scope one, and in the removal phase's judged
observation, so a row whose record now names another box is removed rather
than kept on region alone (rule 9). retireAbortedSeedRow asks it too.

The registry gains fleet_assigned and fleet_moved (Route.Assigned,
Route.Moved): minted from the record's FleetBoxAt and FleetBoxMoved, converged
both ways by SetFleetAssignment only when either differs, kept by Upsert
against a writer that carries none (except on a re-tenanted host), forbidden
on forward rows, hashed in the snapshot only when set.

Census: Reconcile re-pinned; Task 2's console inventory reads
(fleetInventory.readRecords/readSidecars) classified key-site.
TestPlan14RootReadCensus drift left for Task 8.

Tests: TestFleetBoxMintsOnlyItsOwnRecords, TestRelabelledRowIsRemovedNotKept,
TestRelabelledSeedIsNotAdopted, TestMintedRowCarriesTheAssignment,
TestFleetAssignmentColumns, TestProvisionTickConfigCarriesTheFleetBox,
TestRetiredRowStopsItsWorkers.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev ba9e680bea87d6ad40e6c233f1154cf16e2216fe parent 45f8ff5
15 files changed, +535 −14
  • internal/activator/rootfsworkers_test.go +19 −0
  • internal/host/agent.go +9 −0
  • internal/host/host_test.go +26 −0
  • internal/provision/managed_fleets_1b_census_test.go +22 −0
  • internal/provision/reconcile.go +59 −2
  • internal/provision/reconcile_lifetime_test.go +45 −0
  • internal/provision/reconcile_test.go +133 −0
  • internal/provision/seedreconcile.go +5 −1
  • internal/provision/seedreconcile_test.go +66 −0
  • internal/registry/fleetassigned_test.go +75 −0
  • internal/registry/forward.go +6 −2
  • internal/registry/forward_writers_test.go +3 −0
  • internal/registry/registry.go +59 −9
  • internal/registry/registry_test.go +2 −0
  • internal/registry/remote_dispatch.go +6 −0
diff --git a/internal/activator/rootfsworkers_test.go b/internal/activator/rootfsworkers_test.go
index 4116ebf49..30bd37871 100644
--- a/internal/activator/rootfsworkers_test.go
+++ b/internal/activator/rootfsworkers_test.go
@@ -808,6 +808,25 @@ func TestRootfsWorkersStopFirstAndProven(t *testing.T) {
}
}
+// Managed fleets 1b, rule 9: a row the provision pass removed (its record
+// now names another fleet box) is retired by the edge reload's
+// RetireExcept. A rootfs instance's workers stop with it, proven gone before
+// web stops and the lease is released, as on any other stop.
+func TestRetiredRowStopsItsWorkers(t *testing.T) {
+ r := newWorkerRig(t, workerHost(), "jobs")
+ r.wake(t)
+ r.a.RetireExcept(map[string]bool{})
+ waitFor(t, "the retirement's stop", func() bool { return !r.a.hasEntry(r.host) })
+ ev := r.b.events()
+ gone, web, closed := index(ev, "gone jobs", 0), index(ev, "stop:instance", 0), index(ev, "close", 0)
+ if gone < 0 || web < gone || closed < web {
+ t.Fatalf("order %v: want the worker proven gone, then web stopped, then the lease released", ev)
+ }
+ if r.b.releaseCount() == 0 {
+ t.Fatal("the retired instance's lease was not released")
+ }
+}
+
// [pf 2.4] The Service half: a worker stop root answers unproven, or a
// 502, leaves a stray that keeps the stop; the next proof forgets it.
func TestRootfsWorkerStopAnswersInTheService(t *testing.T) {
diff --git a/internal/host/agent.go b/internal/host/agent.go
index 8d2a63fb4..a70819f03 100644
--- a/internal/host/agent.go
+++ b/internal/host/agent.go
@@ -3531,6 +3531,15 @@ func provisionTickConfig(getenv func(string) string) provision.ReconcileConfig {
// when none is armed (every test that does not arm one).
ConfigGate: configGate(),
}
+ // This box's own label in its fleet (managed fleets 1b, rule 2), from
+ // the one identity every fleet loop resolves, and only when that
+ // identity's fleet is the one this box's region places it on. An
+ // identity that does not resolve, or names another fleet, leaves it
+ // empty: a fleet box that cannot say which box it is admits only
+ // unlabelled records, never another box's.
+ if identity, err := resolveFleetIdentity(getenv); err == nil && region == registry.PlacementTarget(identity.Fleet) {
+ cfg.FleetBox = identity.Label
+ }
// The root release public key, same source and same parser as adoptLoop's
// and domainsTickConfig's. It guards ONE decision in this pass: whether a
// trash marker may retire a production-flagged app's routes (#340).
diff --git a/internal/host/host_test.go b/internal/host/host_test.go
index c23acbca4..5dcd3a1cb 100644
--- a/internal/host/host_test.go
+++ b/internal/host/host_test.go
@@ -955,6 +955,32 @@ func TestProvisionTickConfig(t *testing.T) {
// CARLOS_POOLS already use — a legal "no constraint" state, never a
// "feature not configured" one — so it must read back as "" (today's
// behaviour, byte for byte), and only an explicit "none" changes Config.
+// Managed fleets 1b, rule 2: the pass knows this box's own fleet label, by
+// the identity every other fleet loop resolves (resolveFleetIdentity), and
+// only on the fleet its region names. Off a fleet, or with an identity that
+// does not resolve or names another fleet, it carries none, and a fleet box
+// with none admits only unlabelled records.
+func TestProvisionTickConfigCarriesTheFleetBox(t *testing.T) {
+ t.Parallel()
+ for _, c := range []struct {
+ name string
+ env map[string]string
+ want string
+ }{
+ {"CARLOS_FLEET_BOX", map[string]string{"CARLOS_REGION": "fleet/pi", "CARLOS_FLEET": "pi", "CARLOS_FLEET_BOX": "pi-1"}, "pi-1"},
+ {"the tunnel name's label", map[string]string{"CARLOS_REGION": "fleet/pi", "CARLOS_FLEET": "pi", "CARLOS_TUNNEL_NAME": "pi/pi-2"}, "pi-2"},
+ {"a platform box", map[string]string{"CARLOS_REGION": "ie"}, ""},
+ {"a fleet region with no fleet identity", map[string]string{"CARLOS_REGION": "fleet/pi"}, ""},
+ {"an identity that does not resolve", map[string]string{"CARLOS_REGION": "fleet/pi", "CARLOS_FLEET": "pi", "CARLOS_TUNNEL_NAME": "pi-1"}, ""},
+ {"another fleet's identity", map[string]string{"CARLOS_REGION": "fleet/pi", "CARLOS_FLEET": "other", "CARLOS_FLEET_BOX": "pi-1"}, ""},
+ } {
+ env := c.env
+ if got := provisionTickConfig(func(k string) string { return env[k] }).FleetBox; got != c.want {
+ t.Errorf("%s: FleetBox = %q, want %q", c.name, got, c.want)
+ }
+ }
+}
+
func TestProvisionTickConfigReadsInbound(t *testing.T) {
env := func(m map[string]string) func(string) string {
return func(k string) string { return m[k] }
diff --git a/internal/provision/managed_fleets_1b_census_test.go b/internal/provision/managed_fleets_1b_census_test.go
index c9b61129f..ba6e759cf 100644
--- a/internal/provision/managed_fleets_1b_census_test.go
+++ b/internal/provision/managed_fleets_1b_census_test.go
@@ -16,6 +16,23 @@ package provision
// FleetBox and CreatedAt equal the caller's expectation (checked inside
// the updateRecord mutation, so inside each retry); otherwise
// ErrFleetBoxMoved. It reaches the store through updateRecord only.
+//
+// Task 2, two new units the Task 2 commits left unlisted (classified in
+// Task 3, read against the source at 45f8ff5a):
+// - internal/console/fleetbox.go fleetInventory.readRecords (key-site): lists
+// RecordsPrefix with ETags and reads each changed record through the
+// lifetime judge (Observe / ObserveWith). No Put, no Delete.
+// - internal/console/fleetbox.go fleetInventory.readSidecars (key-site):
+// lists SidecarsPrefix with ETags and reads each changed record through
+// GetSidecarRecord. No Put, no Delete.
+//
+// Task 3, one re-pin:
+// - internal/provision/reconcile.go Reconcile (key-site): the record scan
+// skips a record labelled for another fleet box (ownsRecord) after the
+// scope check, and the removal phase's judged observation keeps a row
+// only when its record is in scope AND this box's. Same keys, no new
+// write: fewer records admitted, and a row of another box's record goes
+// through the existing removal (claimRetire / DeleteIfHold).
func managedFleets1bWriteCensusInventory() []censusEntry {
entries := append([]censusEntry(nil), fleetPublicRoutesWriteCensusInventory()...)
replacements := []censusEntry{
@@ -23,6 +40,11 @@ func managedFleets1bWriteCensusInventory() []censusEntry {
{"internal/provision/provision.go", "SetRecordRegion", "record-writer", "key:SetRecordRegion,key:updateRecord", "f9daa5f51657cedf65d654f2c9386c240e6cd4ef1f5072a0a854da3bf437efad"},
// Task 1: the conditional box setter.
{"internal/provision/fleetbox.go", "SetRecordFleetBox", "record-writer", "key:SetRecordFleetBox,key:updateRecord", "f2617c61887a841e7a1de2bafdbd1927f368b7451f2da349030ed98d0313906e"},
+ // Task 2: the console's fleet inventory reads (classified in Task 3).
+ {"internal/console/fleetbox.go", "fleetInventory.readRecords", "key-site", "key:RecordsPrefix", "708adbede017825865e2306f0380d5d6494f7e7c88dbf4f18627caf46356b8ed"},
+ {"internal/console/fleetbox.go", "fleetInventory.readSidecars", "key-site", "key:SidecarsPrefix", "45585354225333e57e9e8bdea495528000bbfed60758fe54a78ac0d63f7cd90c"},
+ // Task 3: a fleet box admits only its own records.
+ {"internal/provision/reconcile.go", "Reconcile", "key-site", "key:ParseRecordKey,key:RecordKey,lit:instances", "ae12f8f6b360ea5015ea05fcffad003a8f01ec8939f5df6c6b0548e17a558325"},
}
for _, r := range replacements {
found := false
diff --git a/internal/provision/reconcile.go b/internal/provision/reconcile.go
index 6840c3cd6..5c6390ebb 100644
--- a/internal/provision/reconcile.go
+++ b/internal/provision/reconcile.go
@@ -42,6 +42,14 @@ type ReconcileConfig struct {
// a box that hasn't been told its place serves only region-less
// records, never someone else's residency promise.
Region string
+ // FleetBox is this box's own label in its fleet (managed fleets 1b,
+ // rule 2): the label resolveFleetIdentity names, set only on a box whose
+ // Region is that fleet's placement. On a fleet, a record labelled for
+ // another box is not this pass's (ownsRecord): it is not minted, and a
+ // row of it is removed. "" on a fleet box is a box that does not know
+ // its label: it admits only unlabelled records. Off a fleet it decides
+ // nothing.
+ FleetBox string
// Pools are the pools this box serves. Empty means the shared "" pool
// only — NOT "every pool" (poolServed below).
Pools []string
@@ -510,6 +518,23 @@ func (cfg ReconcileConfig) inScope(region, pool string, everywhere bool) bool {
return !recordOnFleet && !boxOnFleet
}
+// ownsRecord answers managed fleets 1b's rule 2 for a record inScope has
+// admitted: on a fleet box, a record labelled for a box is this box's only
+// when the label is cfg.FleetBox. An unlabelled record is every box's, as
+// on main, so a fleet the console never labels behaves exactly as before.
+// Off a fleet (the box's Region is no fleet placement) the label decides
+// nothing: a platform box's scope is its region and pool alone.
+//
+// The record scan and the removal phase both ask it after inScope, so a
+// record this box no longer owns is never minted here and its row is
+// removed, not kept on region alone (rule 9).
+func (cfg ReconcileConfig) ownsRecord(rec Record) bool {
+ if _, onFleet := registry.FleetPlacement(cfg.Region); !onFleet {
+ return true
+ }
+ return rec.FleetBox == "" || rec.FleetBox == cfg.FleetBox
+}
+
// RouteFor is the one answer to "what route does this record describe". The
// mint path builds from it and the adoption match test (design §4.2)
// compares against it — one function, so a shape the reconciler would mint
@@ -559,6 +584,10 @@ func RouteFor(rec Record, dataDir, seed string, nested bool, policy *UpdatePolic
Runtime: rec.Runtime,
// Born HA (region HA P1a): sticky on the row (registry.Route.HA).
HA: rec.HA,
+ // The fleet assignment (managed fleets 1b, rule 6), converged by
+ // convergeOwned when either changes.
+ Assigned: rec.FleetBoxAt,
+ Moved: rec.FleetBoxMoved,
}
if rec.DerivesPaths() {
rt.Socket = DefaultSocket(rec.Host)
@@ -963,6 +992,21 @@ func convergeOwned(reg *registry.Registry, existing registry.Route, rec Record,
log.Printf("provision: marked %s high availability", rec.Host)
}
}
+ // The fleet assignment (managed fleets 1b, rule 6) converges both ways,
+ // both columns in one UPDATE, and only when either differs: the start
+ // rule reads them, and an unchanged pass writes nothing.
+ if existing.Assigned != rec.FleetBoxAt || existing.Moved != rec.FleetBoxMoved {
+ if dryRun {
+ log.Printf("provision: dry-run: would converge %s fleet assignment %q moved %v -> %q moved %v",
+ rec.Host, existing.Assigned, existing.Moved, rec.FleetBoxAt, rec.FleetBoxMoved)
+ } else if err := reg.SetFleetAssignment(rec.Host, rec.FleetBoxAt, rec.FleetBoxMoved); err != nil {
+ log.Printf("provision: converge fleet assignment on %s: %v", rec.Host, err)
+ errs = append(errs, fmt.Errorf("converge fleet assignment on %s: %w", rec.Host, err))
+ } else {
+ log.Printf("provision: converged %s fleet assignment %q moved %v -> %q moved %v",
+ rec.Host, existing.Assigned, existing.Moved, rec.FleetBoxAt, rec.FleetBoxMoved)
+ }
+ }
// Update settings (settings spec §4): the record over the app policy,
// both directions, including back to "". Left alone when the policy
// could not be read this pass.
@@ -1265,6 +1309,15 @@ func Reconcile(ctx context.Context, s release.Store, reg *registry.Registry, cfg
}
continue // another agent's jurisdiction, not this pass's business
}
+ // On a fleet box, a record labelled for another box is that
+ // box's alone (managed fleets 1b, rule 2): skipped exactly as an
+ // out-of-scope record is, so it is never minted, staged or
+ // started here, and the removal phase removes this box's row of
+ // it as record gone. Not kept for the forward phase: the
+ // record's region is this box's own.
+ if !cfg.ownsRecord(rec) {
+ continue
+ }
// Two accounts writing the same host is a collision this pass
// cannot arbitrate silently: whichever record this listing reaches
// FIRST wins the host, and the loser is skipped loudly rather than
@@ -2260,7 +2313,10 @@ func Reconcile(ctx context.Context, s release.Store, reg *registry.Registry, cfg
pr.fail(rt.Account, rt.App)
continue
case obs.Present && obs.Verdict == LifetimeValid && !obs.Rec.Retired:
- if cfg.inScope(obs.Rec.Region, obs.Rec.Pool, everywhereClass(*obs.Rec)) {
+ // A record labelled for another fleet box is out of
+ // this box's scope (managed fleets 1b, rule 9): its
+ // region alone does not keep the row.
+ if cfg.inScope(obs.Rec.Region, obs.Rec.Pool, everywhereClass(*obs.Rec)) && cfg.ownsRecord(*obs.Rec) {
// A valid record in this pass's scope defeats the
// record-gone reason only: the row still meets the
// app-trash rule and every exemption below. A row
@@ -2274,7 +2330,8 @@ func Reconcile(ctx context.Context, s release.Store, reg *registry.Registry, cfg
why = "app in the trash"
}
// Out of scope (another region after a flip, another
- // pool): today's rules exactly, the keep view included.
+ // pool, another fleet box's label): today's rules
+ // exactly, the keep view included.
default:
gone = true
if stale[rt.Host] || obs.Present {
diff --git a/internal/provision/reconcile_lifetime_test.go b/internal/provision/reconcile_lifetime_test.go
index 2dce21778..8fd1fecd3 100644
--- a/internal/provision/reconcile_lifetime_test.go
+++ b/internal/provision/reconcile_lifetime_test.go
@@ -553,6 +553,51 @@ func TestOutOfScopeValidRecordFollowsTodaysRemoval(t *testing.T) {
}
}
+// Managed fleets 1b, rule 9: a fleet box's row whose record is now labelled
+// for another box is removed, as a record moved to another region is, with
+// the lifetime judge on and off. The judge's observation finds the record
+// valid and in this box's region: the label alone must decide. A record left
+// on this box, or unlabelled, keeps its row; a running operation's
+// participant keeps it too, today's rule for an out-of-scope record.
+func TestRelabelledRowIsRemovedNotKept(t *testing.T) {
+ for _, c := range []struct {
+ name string
+ label string
+ keep bool
+ kept bool
+ }{
+ {name: "relabelled to another box", label: "pi-2"},
+ {name: "relabelled to another box, kept by the view", label: "pi-2", keep: true, kept: true},
+ {name: "still this box's", label: "pi-1", kept: true},
+ {name: "unlabelled", label: "", kept: true},
+ } {
+ for _, judged := range []bool{false, true} {
+ t.Run(fmt.Sprintf("%s, judged %v", c.name, judged), func(t *testing.T) {
+ x := newLifeScene(t)
+ x.cfg.Region, x.cfg.FleetBox = "fleet/pi", "pi-1"
+ rec := x.record("shop", 1)
+ rec.Region, rec.FleetBox, rec.FleetBoxAt = "fleet/pi", "pi-1", "2026-10-30T09:00:00Z"
+ x.putRecord(t, rec)
+ x.putSlot(t, "shop", 1, SlotLive)
+ x.minted(t, "shop")
+ rec.FleetBox, rec.FleetBoxAt = c.label, "2026-10-30T10:00:00Z"
+ rec.FleetBoxMoved = c.label == "pi-2"
+ x.putRecord(t, rec)
+ if !judged {
+ x.cfg.Judge = nil
+ }
+ if c.keep {
+ x.cfg.KeepParticipant = func(string) bool { return true }
+ }
+ x.pass(t)
+ if got := x.row(t) != nil; got != c.kept {
+ t.Fatalf("row kept = %v, want %v", got, c.kept)
+ }
+ })
+ }
+ }
+}
+
// A record under a retired account is never in the pass's set (the listing
// trusts only known accounts), so its row has always been removed as record
// gone. A judge observing the row's own key must not bring it back.
diff --git a/internal/provision/reconcile_test.go b/internal/provision/reconcile_test.go
index 49a36bbad..d65c43786 100644
--- a/internal/provision/reconcile_test.go
+++ b/internal/provision/reconcile_test.go
@@ -4,6 +4,7 @@ import (
"bytes"
"context"
"crypto/ed25519"
+ "database/sql"
"encoding/json"
"errors"
"fmt"
@@ -3802,3 +3803,135 @@ func TestRouteForBornHAIsAlwaysNested(t *testing.T) {
t.Fatalf("legacy row on a box not yet nested minted at db %q socket %q; want flat", lt.DBPath, lt.Socket)
}
}
+
+// fleetRecord is a shop record placed on fleet pi, labelled for box ("" for
+// an unlabelled record, today's every record).
+func fleetRecord(sqid, host, box string) Record {
+ rec := shopRecord(sqid)
+ rec.Host, rec.Slug, rec.Region, rec.FleetBox = host, strings.SplitN(host, ".", 2)[0], "fleet/pi", box
+ if box != "" {
+ rec.FleetBoxAt = "2026-10-30T09:00:00.000000001Z"
+ }
+ return rec
+}
+
+// Managed fleets 1b, rule 2: a fleet box admits a labelled record only when
+// the label is its own. An unlabelled record is every box's, as on main; a
+// box whose own label is unknown admits only unlabelled records; and off a
+// fleet the label decides nothing (a platform box's scope is its region).
+func TestFleetBoxMintsOnlyItsOwnRecords(t *testing.T) {
+ s, sqid := shopSetup(t)
+ for _, rec := range []Record{
+ fleetRecord(sqid, "a.shop.example.com", ""),
+ fleetRecord(sqid, "b.shop.example.com", "pi-1"),
+ fleetRecord(sqid, "c.shop.example.com", "pi-2"),
+ } {
+ if err := CreateRecord(ctx, s, rec); err != nil {
+ t.Fatal(err)
+ }
+ }
+ // A record in a platform region carrying a label (a bucket write no
+ // console door makes: SetRecordRegion clears it) is still its region's.
+ stale := shopRecord(sqid)
+ stale.Host, stale.Slug, stale.FleetBox = "d.shop.example.com", "d", "pi-2"
+ if err := CreateRecord(ctx, s, stale); err != nil {
+ t.Fatal(err)
+ }
+ for _, c := range []struct {
+ name, region, box string
+ want []string
+ }{
+ {"box pi-1", "fleet/pi", "pi-1", []string{"a.shop.example.com", "b.shop.example.com"}},
+ {"box pi-2", "fleet/pi", "pi-2", []string{"a.shop.example.com", "c.shop.example.com"}},
+ {"a fleet box with no label", "fleet/pi", "", []string{"a.shop.example.com"}},
+ {"a platform box", "ie", "", []string{"d.shop.example.com"}},
+ {"a platform box given a label", "ie", "pi-1", []string{"d.shop.example.com"}},
+ } {
+ t.Run(c.name, func(t *testing.T) {
+ reg := regWith(t)
+ if err := Reconcile(ctx, s, reg, ReconcileConfig{Region: c.region, FleetBox: c.box, DataDir: "/data"}); err != nil {
+ t.Fatal(err)
+ }
+ rows, err := reg.List()
+ if err != nil {
+ t.Fatal(err)
+ }
+ var got []string
+ for _, rt := range rows {
+ got = append(got, rt.Host)
+ }
+ if !reflect.DeepEqual(got, c.want) {
+ t.Fatalf("minted %v, want %v", got, c.want)
+ }
+ })
+ }
+}
+
+// Managed fleets 1b, rules 2 and 6: the box's own row carries its record's
+// assignment time and moved flag from the mint, is rewritten when either
+// changes, and is not written at all on a pass where neither did.
+func TestMintedRowCarriesTheAssignment(t *testing.T) {
+ s, sqid := shopSetup(t)
+ rec := fleetRecord(sqid, "a.shop.example.com", "pi-1")
+ if err := CreateRecord(ctx, s, rec); err != nil {
+ t.Fatal(err)
+ }
+ path := filepath.Join(t.TempDir(), "registry.db")
+ reg, err := registry.Open(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ cfg := ReconcileConfig{Region: "fleet/pi", FleetBox: "pi-1", DataDir: "/data"}
+ pass := func() *registry.Route {
+ t.Helper()
+ if err := Reconcile(ctx, s, reg, cfg); err != nil {
+ t.Fatal(err)
+ }
+ return mustGet(t, reg, rec.Host)
+ }
+ if rt := pass(); rt.Assigned != rec.FleetBoxAt || rt.Moved {
+ t.Fatalf("minted row assigned %q moved %v, want %q false", rt.Assigned, rt.Moved, rec.FleetBoxAt)
+ }
+
+ // A relabel away and back before this box's next pass: a newer
+ // assignment, moved.
+ got, err := GetRecord(ctx, s, sqid, rec.App, rec.Host)
+ if err != nil {
+ t.Fatal(err)
+ }
+ t1 := time.Date(2026, 10, 30, 10, 0, 0, 0, time.UTC)
+ if err := SetRecordFleetBox(ctx, s, sqid, rec.App, rec.Host, FleetBoxExpect{Region: "fleet/pi", Label: "pi-1", CreatedAt: got.CreatedAt}, "pi-2", t1); err != nil {
+ t.Fatal(err)
+ }
+ t2 := t1.Add(time.Minute)
+ if err := SetRecordFleetBox(ctx, s, sqid, rec.App, rec.Host, FleetBoxExpect{Region: "fleet/pi", Label: "pi-2", CreatedAt: got.CreatedAt}, "pi-1", t2); err != nil {
+ t.Fatal(err)
+ }
+ want := t2.Format(time.RFC3339Nano)
+ if rt := pass(); rt.Assigned != want || !rt.Moved {
+ t.Fatalf("converged row assigned %q moved %v, want %q true", rt.Assigned, rt.Moved, want)
+ }
+
+ // Nothing changed: no write reaches the row.
+ db, err := sql.Open("sqlite", path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer db.Close()
+ for _, stmt := range []string{
+ `CREATE TABLE t3_writes (host TEXT)`,
+ `CREATE TRIGGER t3_u AFTER UPDATE ON routes BEGIN INSERT INTO t3_writes VALUES (new.host); END`,
+ } {
+ if _, err := db.Exec(stmt); err != nil {
+ t.Fatal(err)
+ }
+ }
+ pass()
+ var n int
+ if err := db.QueryRow(`SELECT COUNT(*) FROM t3_writes`).Scan(&n); err != nil {
+ t.Fatal(err)
+ }
+ if n != 0 {
+ t.Fatalf("an unchanged pass wrote the row %d times", n)
+ }
+}
diff --git a/internal/provision/seedreconcile.go b/internal/provision/seedreconcile.go
index e49e896ba..7862b2fd0 100644
--- a/internal/provision/seedreconcile.go
+++ b/internal/provision/seedreconcile.go
@@ -173,9 +173,13 @@ func seedAction(rec Record, row *registry.Route, cfg ReconcileConfig, nested fun
//
// Only --from seeds: an import's row is the instance the import replaces,
// which its rollback restores (Plan 7) and never removes.
+//
+// The record must be this box's too (ownsRecord, managed fleets 1b): the
+// scan admits no other, and a seed another fleet box owns is that box's to
+// abort; this box's row of it goes through the removal phase, as record gone.
func retireAbortedSeedRow(ctx context.Context, reg *registry.Registry, cfg ReconcileConfig, rec Record, rt registry.Route) {
if rt.Kind == SidecarKind || rt.IsForward() || !rt.Provisioned || !cfg.inScope(rt.Region, rt.Pool, everywhereRoute(rt)) ||
- rt.Account != rec.Account || rt.App != rec.App {
+ !cfg.ownsRecord(rec) || rt.Account != rec.Account || rt.App != rec.App {
log.Printf("provision: %s: aborted seed %s has a row this pass may not remove; leaving the seed aborted", rec.Host, rec.Seed.ID)
return
}
diff --git a/internal/provision/seedreconcile_test.go b/internal/provision/seedreconcile_test.go
index afeddd5f3..f22399a2a 100644
--- a/internal/provision/seedreconcile_test.go
+++ b/internal/provision/seedreconcile_test.go
@@ -490,3 +490,69 @@ func TestReconcileAbortedFromSeedDecidesItsLocalDataFromTheMarker(t *testing.T)
})
}
}
+
+// Managed fleets 1b, rule 2: a seeded record labelled for another fleet box
+// is not this box's. A ready --from seed is not minted here, and an aborted
+// one is not finished here: its snapshot is not deleted and its record is not
+// rolled back, which only the box it names may do. Labelled for this box,
+// the ready seed mints as on main.
+func TestRelabelledSeedIsNotAdopted(t *testing.T) {
+ fleetSeed := func(t *testing.T, s release.Store, sqid, state, box string) Record {
+ t.Helper()
+ rec := acmeRecord(sqid)
+ rec.Region, rec.FleetBox, rec.FleetBoxAt = "fleet/pi", box, "2026-10-30T09:00:00Z"
+ id, _ := seeds.NewID()
+ rec.Seed = &SeedSource{ID: id, Kind: seeds.KindReplica, State: state, SHA256: "a", Bytes: 1, By: "t", At: time.Now()}
+ if err := CreateRecord(ctx, s, rec); err != nil {
+ t.Fatal(err)
+ }
+ return rec
+ }
+ pi1 := func(data release.Store) ReconcileConfig {
+ cfg := nestedSeedCfg(data)
+ cfg.Region, cfg.FleetBox = "fleet/pi", "pi-1"
+ return cfg
+ }
+ t.Run("ready, another box's", func(t *testing.T) {
+ s, sqid := setup(t)
+ rec := fleetSeed(t, s, sqid, seeds.StateReady, "pi-2")
+ reg := regWith(t)
+ if err := Reconcile(ctx, s, reg, pi1(dirStore(t))); err != nil {
+ t.Fatal(err)
+ }
+ if rt, _ := reg.Get(rec.Host); rt != nil {
+ t.Fatalf("minted another box's seeded record: %+v", rt)
+ }
+ })
+ t.Run("ready, this box's", func(t *testing.T) {
+ s, sqid := setup(t)
+ rec := fleetSeed(t, s, sqid, seeds.StateReady, "pi-1")
+ reg := regWith(t)
+ if err := Reconcile(ctx, s, reg, pi1(dirStore(t))); err != nil {
+ t.Fatal(err)
+ }
+ if got := mustGet(t, reg, rec.Host); got.SeedSource != SeedColumn(rec) {
+ t.Fatalf("row seed source %q, want %q", got.SeedSource, SeedColumn(rec))
+ }
+ })
+ t.Run("aborted, another box's", func(t *testing.T) {
+ s, sqid := setup(t)
+ data := dirStore(t)
+ rec := fleetSeed(t, s, sqid, seeds.StateAborted, "pi-2")
+ snap := seeds.SnapshotKey(rec.Host, rec.Seed.ID)
+ if _, err := data.Put(ctx, snap, []byte("db"), ""); err != nil {
+ t.Fatal(err)
+ }
+ reg := regWith(t)
+ if err := Reconcile(ctx, s, reg, pi1(data)); err != nil {
+ t.Fatal(err)
+ }
+ if _, _, err := data.Get(ctx, snap); err != nil {
+ t.Fatalf("another box's aborted seed lost its snapshot: %v", err)
+ }
+ got, err := GetRecord(ctx, s, rec.Account, rec.App, rec.Host)
+ if err != nil || got.Seed.State != seeds.StateAborted {
+ t.Fatalf("record = %+v, %v; want still aborted", got.Seed, err)
+ }
+ })
+}
diff --git a/internal/registry/fleetassigned_test.go b/internal/registry/fleetassigned_test.go
new file mode 100644
index 000000000..1a622006b
--- /dev/null
+++ b/internal/registry/fleetassigned_test.go
@@ -0,0 +1,75 @@
+package registry
+
+import (
+ "errors"
+ "path/filepath"
+ "testing"
+)
+
+// Managed fleets 1b, rule 6: a fleet box's own row carries its record's
+// assignment time and moved flag. A mint carries them; SetFleetAssignment
+// rewrites both, both ways, on an existing row only and never on a forward
+// row; a full-row Upsert that knows nothing of them keeps them, and a new
+// tenant on the hostname takes the incoming values.
+func TestFleetAssignmentColumns(t *testing.T) {
+ reg, err := Open(filepath.Join(t.TempDir(), "registry.db"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ const at = "2026-10-30T09:00:00.000000001Z"
+ base := Route{Host: "shop.example.com", Kind: "instance", Status: "ready", App: "shop", Account: "acct", Channel: "stable", Region: "fleet/pi"}
+ minted := base
+ minted.Assigned, minted.Moved = at, true
+ if err := reg.Upsert(minted); err != nil {
+ t.Fatal(err)
+ }
+ if got, _ := reg.Get(base.Host); got == nil || got.Assigned != at || !got.Moved {
+ t.Fatalf("minted row: %+v", got)
+ }
+ if err := reg.Upsert(base); err != nil { // neither column on the incoming row
+ t.Fatal(err)
+ }
+ if got, _ := reg.Get(base.Host); got == nil || got.Assigned != at || !got.Moved {
+ t.Fatalf("a full-row Upsert dropped the assignment: %+v", got)
+ }
+ const later = "2026-10-30T10:00:00Z"
+ if err := reg.SetFleetAssignment(base.Host, later, false); err != nil {
+ t.Fatal(err)
+ }
+ if got, _ := reg.Get(base.Host); got == nil || got.Assigned != later || got.Moved {
+ t.Fatalf("after SetFleetAssignment(%q, false): %+v", later, got)
+ }
+ if err := reg.SetFleetAssignment(base.Host, "", false); err != nil {
+ t.Fatal(err)
+ }
+ if got, _ := reg.Get(base.Host); got == nil || got.Assigned != "" || got.Moved {
+ t.Fatalf("SetFleetAssignment did not clear: %+v", got)
+ }
+
+ // A new tenant on the hostname is a new life: its values, not the old.
+ if err := reg.SetFleetAssignment(base.Host, at, true); err != nil {
+ t.Fatal(err)
+ }
+ other := base
+ other.App = "cart"
+ if err := reg.Upsert(other); err != nil {
+ t.Fatal(err)
+ }
+ if got, _ := reg.Get(base.Host); got == nil || got.Assigned != "" || got.Moved {
+ t.Fatalf("a re-tenanted row kept the old life's assignment: %+v", got)
+ }
+
+ if err := reg.SetFleetAssignment("nope.example.com", at, false); err == nil {
+ t.Fatal("SetFleetAssignment on an unknown host: want an error")
+ }
+ fwd := Route{Host: "fwd.example.com", Kind: KindForward, App: "shop", Account: "acct", Channel: "stable", Region: "fleet/pi"}
+ if err := reg.PutForward(fwd); err != nil {
+ t.Fatal(err)
+ }
+ if err := reg.SetFleetAssignment(fwd.Host, at, true); !errors.Is(err, ErrForwardRow) {
+ t.Fatalf("SetFleetAssignment on a forward row: %v, want ErrForwardRow", err)
+ }
+ if got, _ := reg.Get(fwd.Host); got == nil || got.Assigned != "" || got.Moved {
+ t.Fatalf("forward row after a refused SetFleetAssignment: %+v", got)
+ }
+}
diff --git a/internal/registry/forward.go b/internal/registry/forward.go
index b10fe4f1f..39030e5ae 100644
--- a/internal/registry/forward.go
+++ b/internal/registry/forward.go
@@ -110,7 +110,7 @@ var forwardShape = map[string]string{
"EgressAllow": "forbidden", "Size": "forbidden", "PolicyExpiresAt": "forbidden",
"BuildState": "forbidden", "Replicas": "forbidden", "Replica": "forbidden",
"ClaimIncarnation": "forbidden", "ClaimStamp": "forbidden", "ClaimOwner": "forbidden",
- "ClaimRowID": "forbidden",
+ "ClaimRowID": "forbidden", "Assigned": "forbidden", "Moved": "forbidden",
}
// ForwardColumn is one forbidden field of a forward row: the Route field, its
@@ -176,6 +176,8 @@ var ForwardForbidden = []ForwardColumn{
{"ClaimStamp", "claim_stamp", "INTEGER"},
{"ClaimOwner", "claim_owner", "TEXT"},
{"ClaimRowID", "claim_row_id", "TEXT"},
+ {"Assigned", "fleet_assigned", "TEXT"},
+ {"Moved", "fleet_moved", "INTEGER"},
}
// InertForward reports whether t is a forward row with every forbidden field
@@ -233,7 +235,9 @@ func (t Route) InertForward() bool {
t.ClaimIncarnation == "" &&
t.ClaimStamp == 0 &&
t.ClaimOwner == "" &&
- t.ClaimRowID == ""
+ t.ClaimRowID == "" &&
+ t.Assigned == "" &&
+ !t.Moved
}
// fingerprintForwardInert is InertForward as a column of Fingerprint's
diff --git a/internal/registry/forward_writers_test.go b/internal/registry/forward_writers_test.go
index cbd78ca13..461657e3f 100644
--- a/internal/registry/forward_writers_test.go
+++ b/internal/registry/forward_writers_test.go
@@ -362,6 +362,9 @@ func routeWriterCases() []writerCase {
errCase("SetReplicas", true, nil, func(r *Registry, h string) error { return r.SetReplicas(h, "away") }),
errCase("SetReplica", true, nil, func(r *Registry, h string) error { return r.SetReplica(h, true) }),
errCase("SetHA", true, nil, func(r *Registry, h string) error { return r.SetHA(h) }),
+ errCase("SetFleetAssignment", true, nil, func(r *Registry, h string) error {
+ return r.SetFleetAssignment(h, "2026-10-30T09:00:00Z", true)
+ }),
errCase("SetGate", true, nil, func(r *Registry, h string) error { return r.SetGate(h, "hash") }),
errCase("SetRateLimit", true, nil, func(r *Registry, h string) error { return r.SetRateLimit(h, `{"rps":5}`) }),
errCase("SetChannels", true, nil, func(r *Registry, h string) error { return r.SetChannels([]string{h}, "beta") }),
diff --git a/internal/registry/registry.go b/internal/registry/registry.go
index 22484b87d..86b858a39 100644
--- a/internal/registry/registry.go
+++ b/internal/registry/registry.go
@@ -184,6 +184,19 @@ type Route struct {
// by SetFleetBoxIf (forward.go); Upsert preserves non-empty values — see
// Environment's comment for why.
FleetBox string
+ // Assigned and Moved are this box's copy of its instance record's
+ // fleet assignment (managed fleets 1b, rule 6): Assigned is the
+ // record's FleetBoxAt, the time it was assigned to its box (RFC 3339
+ // nanoseconds, UTC; "" = never assigned), and Moved its FleetBoxMoved,
+ // set by the first relabel from one box to another. Minted from the
+ // record and converged both ways by the provision pass, through
+ // SetFleetAssignment, only when either differs. The activator's start
+ // rule reads them; nothing serves by them, so they are not in
+ // Fingerprint. Upsert keeps a stored value against a writer that
+ // carries none (the gate idiom), except on a re-tenanted host. Never on
+ // a forward row (ForwardForbidden).
+ Assigned string
+ Moved bool
// Caps is the OPERATOR-granted capability tokens for this route ON THIS
// BOX: comma-separated and canonically sorted, so "port:25,host-role"
@@ -713,6 +726,10 @@ var routeAddedColumns = []addedColumn{
{Name: "policy_expires_at", Type: "TEXT", Default: "''"},
// Region HA P1a: the born-HA mark (Route.HA), sticky.
{Name: "ha", Type: "INTEGER", Default: "0"},
+ // Managed fleets 1b: the record's fleet assignment (Route.Assigned,
+ // Route.Moved).
+ {Name: "fleet_assigned", Type: "TEXT", Default: "''"},
+ {Name: "fleet_moved", Type: "INTEGER", Default: "0"},
// Host claims' ownership (migrateClaimOwnership, routes and timers).
{Name: "claim_incarnation", Type: "TEXT", Default: "''", Claim: true},
{Name: "claim_stamp", Type: "INTEGER", Default: "0", Claim: true},
@@ -1055,10 +1072,10 @@ provisioned, seed, unit, fleet_box, addrs, health, steering, gate, created_at,
args, idle_seconds, max_run_seconds, replicas, replica, claim_incarnation, claim_stamp, claim_owner, claim_row_id, hold_op,
good_version, good_digest, good_demand, serving_version, update_settings, build_state,
seed_source, import_gate, runtime, rate_limit, assets_off, asset_gen, incarnation, serving_seq,
-egress_allow, size, policy_expires_at, ha`
+egress_allow, size, policy_expires_at, ha, fleet_assigned, fleet_moved`
// routeColCount is the number of names in routeCols.
-const routeColCount = 65
+const routeColCount = 67
// placeholders is n comma-joined bind parameters.
func placeholders(n int) string {
@@ -1067,7 +1084,7 @@ func placeholders(n int) string {
func scanRoute(scan func(...any) error) (Route, error) {
var t Route
- var hib, can, sn, plat, prov, rep, assetsOff, ha int
+ var hib, can, sn, plat, prov, rep, assetsOff, ha, moved int
err := scan(&t.Host, &t.Slug, &t.Kind, &t.Socket, &t.Addr, &t.Status,
&t.LastError, &t.DBPath, &t.Version, &t.PrevVersion, &t.App, &t.Pool,
&t.Region, &t.Channel, &hib, &can, &t.Replication, &t.NextDue, &t.Backing,
@@ -1077,8 +1094,9 @@ func scanRoute(scan func(...any) error) (Route, error) {
&t.Args, &t.IdleSeconds, &t.MaxRunSeconds, &t.Replicas, &rep, &t.ClaimIncarnation, &t.ClaimStamp, &t.ClaimOwner, &t.ClaimRowID, &t.HoldOp,
&t.GoodVersion, &t.GoodDigest, &t.GoodDemand, &t.ServingVersion, &t.UpdateSettings, &t.BuildState,
&t.SeedSource, &t.ImportGate, &t.Runtime, &t.RateLimit, &assetsOff, &t.AssetGen, &t.Incarnation, &t.ServingSeq,
- &t.EgressAllow, &t.Size, &t.PolicyExpiresAt, &ha)
+ &t.EgressAllow, &t.Size, &t.PolicyExpiresAt, &ha, &t.Assigned, &moved)
t.HA = ha != 0
+ t.Moved = moved != 0
t.AssetsOff = assetsOff != 0
t.Hibernate = hib != 0
t.Canary = can != 0
@@ -1566,7 +1584,11 @@ ON CONFLICT(host) DO UPDATE SET
WHEN excluded.size = '' THEN routes.size ELSE excluded.size END,
policy_expires_at=CASE WHEN `+tenantChangedSQL+` THEN excluded.policy_expires_at
WHEN excluded.policy_expires_at = '' THEN routes.policy_expires_at ELSE excluded.policy_expires_at END,
- ha=MAX(routes.ha, excluded.ha)
+ ha=MAX(routes.ha, excluded.ha),
+ fleet_assigned=CASE WHEN `+tenantChangedSQL+` THEN excluded.fleet_assigned
+ WHEN excluded.fleet_assigned = '' THEN routes.fleet_assigned ELSE excluded.fleet_assigned END,
+ fleet_moved=CASE WHEN `+tenantChangedSQL+` THEN excluded.fleet_moved
+ ELSE MAX(routes.fleet_moved, excluded.fleet_moved) END
WHERE routes.claim_incarnation=excluded.claim_incarnation AND routes.claim_stamp=excluded.claim_stamp
AND routes.claim_owner=excluded.claim_owner AND routes.claim_row_id=excluded.claim_row_id
AND routes.kind <> 'forward'`+guard,
@@ -1637,7 +1659,7 @@ func routeArgs(t Route) []any {
t.Replicas, b2iDB(t.Replica), t.ClaimIncarnation, t.ClaimStamp, t.ClaimOwner, t.ClaimRowID, t.HoldOp,
t.GoodVersion, t.GoodDigest, t.GoodDemand, t.ServingVersion, t.UpdateSettings, t.BuildState,
t.SeedSource, t.ImportGate, t.Runtime, t.RateLimit, b2iDB(t.AssetsOff), t.AssetGen, t.Incarnation, t.ServingSeq,
- t.EgressAllow, t.Size, t.PolicyExpiresAt, b2iDB(t.HA),
+ t.EgressAllow, t.Size, t.PolicyExpiresAt, b2iDB(t.HA), t.Assigned, b2iDB(t.Moved),
}
}
@@ -2621,6 +2643,32 @@ func (r *Registry) SetHA(host string) error {
return nil
}
+// SetFleetAssignment converges a row's fleet assignment (Route.Assigned,
+// Route.Moved) from its instance record, both columns in one narrow UPDATE
+// and both ways, including back to "" and false: the record decides, and
+// Upsert, which keeps a stored value, could not clear one. The provision
+// pass calls it only when either column differs, so an unchanged pass
+// writes nothing. Errors on an unmatched host, SetGate's contract; a
+// forward row is never written (ErrForwardRow).
+func (r *Registry) SetFleetAssignment(host, assigned string, moved bool) error {
+ if r.remote != nil {
+ _, err := r.remote.call(nil, remoteRequest{Method: "SetFleetAssignment", Host: host, Assigned: assigned, Moved: moved}, nil)
+ return err
+ }
+ res, err := r.sql.Exec(`UPDATE routes SET fleet_assigned = ?, fleet_moved = ? WHERE host = ? AND kind <> 'forward'`, assigned, b2iDB(moved), host)
+ if err != nil {
+ return err
+ }
+ n, err := res.RowsAffected()
+ if err != nil {
+ return err
+ }
+ if n == 0 {
+ return noRoute(r.sql, host)
+ }
+ return nil
+}
+
// b2iDB is Upsert's b2i for the narrow setters, which sit outside that
// function's closure.
func b2iDB(b bool) int {
@@ -4155,6 +4203,7 @@ var snapshotWhenSetCols = map[string]bool{
"egress_allow": true,
"size": true,
"policy_expires_at": true,
+ "fleet_assigned": true,
}
// snapshotPairCols are the lifetime pair's columns (self-serve moves plan 1
@@ -4237,10 +4286,11 @@ func (r *Registry) SnapshotFingerprint() (string, error) {
}
continue
}
- // ha too (region HA P1a): only a born-HA row hashes it.
- if cols[i] == "ha" {
+ // ha too (region HA P1a): only a born-HA row hashes it. And
+ // fleet_moved (managed fleets 1b): only a moved row's.
+ if cols[i] == "ha" || cols[i] == "fleet_moved" {
if v.Valid && v.String != "" && v.String != "0" {
- fmt.Fprintf(h, "ha=%s\x1f", v.String)
+ fmt.Fprintf(h, "%s=%s\x1f", cols[i], v.String)
}
continue
}
diff --git a/internal/registry/registry_test.go b/internal/registry/registry_test.go
index 03540d320..336f6ffd2 100644
--- a/internal/registry/registry_test.go
+++ b/internal/registry/registry_test.go
@@ -96,6 +96,8 @@ func TestUpsertRoundTripsAllColumns(t *testing.T) {
Size: "large",
PolicyExpiresAt: "1900000000",
HA: true,
+ Assigned: "2026-10-30T09:00:00.000000001Z",
+ Moved: true,
}
if err := reg.Upsert(want); err != nil {
t.Fatal(err)
diff --git a/internal/registry/remote_dispatch.go b/internal/registry/remote_dispatch.go
index 50cf3cebe..c5b26c31f 100644
--- a/internal/registry/remote_dispatch.go
+++ b/internal/registry/remote_dispatch.go
@@ -106,6 +106,10 @@ type remoteRequest struct {
EgressAllow string
Size string
PolicyExpiresAt string
+
+ // SetFleetAssignment's two columns (managed fleets 1b).
+ Assigned string
+ Moved bool
}
type remoteResponse struct {
@@ -280,6 +284,8 @@ func (r *Registry) dispatchRemote(ctx context.Context, q remoteRequest, callback
err = r.SetReplica(q.Host, q.Replica)
case "SetHA":
err = r.SetHA(q.Host)
+ case "SetFleetAssignment":
+ err = r.SetFleetAssignment(q.Host, q.Assigned, q.Moved)
case "SetGate":
err = r.SetGate(q.Host, q.Hash)
case "SetRateLimit":