carlos / platform Public

fleet-routes-followups: registry deferred minors (#457 1a, Tasks 1 and 2)

- SetFleetBoxIf: an isolated witness for the membership subquery's fleet
  condition (a label detached on the row's fleet and active on another
  fleet must not bind). Mutation dropping `fleet = ?` is caught.
- PutForward's conflict arm is now built from one production list,
  forwardKept, which TestForwardForbiddenMatchesTheTable checks with
  ForwardForbidden against PRAGMA table_info(routes); a new test reads the
  arm back and checks it assigns every column but host once, each by its
  class. Mutations dropping a kept entry or taking dns_checked_at from the
  call are caught.
- dns_checked_at is now asserted to survive PutForward.
- PutForward refuses, with the new sentinel ErrNotForward (one of
  remoteErrors), a row that is not a forward row, has no host, or whose
  Region is not a fleet placement. Mutations admitting an empty host or a
  non-fleet region are caught.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev e25a0b37216f185be3442762f334fb35d5b94341 parent 65fd806
4 files changed, +227 −39
  • internal/registry/fleetbox_if_test.go +32 −0
  • internal/registry/forward.go +54 −15
  • internal/registry/forward_test.go +140 −23
  • internal/registry/remote.go +1 −1
diff --git a/internal/registry/fleetbox_if_test.go b/internal/registry/fleetbox_if_test.go
index bf4b66023..94c0bd2ac 100644
--- a/internal/registry/fleetbox_if_test.go
+++ b/internal/registry/fleetbox_if_test.go
@@ -111,6 +111,38 @@ func TestSetFleetBoxIfBindsPlacementKindAndMembership(t *testing.T) {
}
}
+// TestSetFleetBoxIfMembershipIsTheRowsOwnFleet isolates the membership
+// subquery's fleet condition (deferred minor, Task 1). The label box-2 is
+// detached on the row's own fleet and active on another fleet, and the call
+// names the row's own fleet, so placement and kind both match: only the
+// subquery's `fleet = ?` stands between the call and a binding. Without it,
+// another fleet's active box would vouch for a label this fleet detached.
+func TestSetFleetBoxIfMembershipIsTheRowsOwnFleet(t *testing.T) {
+ reg := openTestRegistry(t)
+ const host = "shop.example.com"
+ fleetBoundRow(t, reg, host, "home", "box-1")
+ if err := reg.AddFleetBox(FleetBox{Fleet: "home", Label: "box-2", TokenHash: tokenHashB, Status: "detached"}); err != nil {
+ t.Fatal(err)
+ }
+ if err := reg.UpsertFleet(Fleet{Name: "away", Account: "baj", Bucket: "away-data"}); err != nil {
+ t.Fatal(err)
+ }
+ if err := reg.AddFleetBox(FleetBox{Fleet: "away", Label: "box-2", TokenHash: tokenHashC, Status: "active"}); err != nil {
+ t.Fatal(err)
+ }
+
+ changed, err := reg.SetFleetBoxIf(host, "home", "box-2")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if changed {
+ t.Error("SetFleetBoxIf(home, box-2) bound the row: box-2 is detached on home and active only on away")
+ }
+ if got, err := reg.Get(host); err != nil || got.FleetBox != "box-1" {
+ t.Errorf("FleetBox = %q (err %v), want box-1 kept", got.FleetBox, err)
+ }
+}
+
// TestSetFleetBoxIfOverRemote: the remote case answers the same as the local
// statement, the bool included, so an agent on the remote registry sees the
// same refusal.
diff --git a/internal/registry/forward.go b/internal/registry/forward.go
index b10fe4f1f..e14c18096 100644
--- a/internal/registry/forward.go
+++ b/internal/registry/forward.go
@@ -64,6 +64,11 @@ func (t Route) IsForward() bool { return t.Kind == KindForward }
// §4.2, the writer rule). One of remoteErrors.
var ErrForwardRow = errors.New("registry: the host is a forward row")
+// ErrNotForward is PutForward's answer when the row it is handed is not a
+// forward row it may write: another kind, no host, or a Region that is not
+// a fleet placement. Nothing is read or written. One of remoteErrors.
+var ErrNotForward = errors.New("registry: not a forward row")
+
// ErrHostHeld is PutForward's answer when a row that is not a forward row
// already holds the host: that row is another writer's, and PutForward
// writes nothing. One of remoteErrors.
@@ -252,23 +257,50 @@ var fingerprintForwardInert = func() string {
return "CASE WHEN kind <> 'forward' OR (" + strings.Join(zero, " AND ") + ") THEN 1 ELSE 0 END"
}()
+// forwardKeptColumn is one routes column of a forward row that is not
+// ForwardForbidden: its Route field, its column, and the value PutForward's
+// conflict arm writes to it (empty for host, the conflict target).
+type forwardKeptColumn struct{ Field, Column, OnConflict string }
+
+// forwardKept is every routes column that is not ForwardForbidden, with the
+// value PutForward's conflict arm gives it when a forward row is already
+// stored: declared columns from the call (excluded.*), CreatedAt and the
+// observational ones kept (routes.*), FleetBox kept only while the region is
+// unchanged. putForwardSQL is built from this list and ForwardForbidden, and
+// TestForwardForbiddenMatchesTheTable checks the two together against
+// PRAGMA table_info(routes), so a column a migration adds is either classed
+// here or fails that test.
+var forwardKept = []forwardKeptColumn{
+ {"Host", "host", ""},
+ {"Kind", "kind", "excluded.kind"},
+ {"Slug", "slug", "excluded.slug"},
+ {"App", "app", "excluded.app"},
+ {"Account", "account", "excluded.account"},
+ {"Region", "region", "excluded.region"},
+ {"Channel", "channel", "excluded.channel"},
+ {"RateLimit", "rate_limit", "excluded.rate_limit"},
+ {"Status", "status", "excluded.status"},
+ {"Provisioned", "provisioned", "excluded.provisioned"},
+ {"CreatedAt", "created_at", "routes.created_at"},
+ {"FleetBox", "fleet_box", "CASE WHEN routes.region = excluded.region THEN routes.fleet_box ELSE '' END"},
+ {"DNSStatus", "dns_status", "routes.dns_status"},
+ {"DNSCheckedAt", "dns_checked_at", "routes.dns_checked_at"},
+ {"CertExpiresAt", "cert_expires_at", "routes.cert_expires_at"},
+}
+
// putForwardSQL is PutForward's one statement. The INSERT binds every column
-// through routeArgs (the forbidden ones zero). The conflict arm names every
-// column too: declared ones from the call, CreatedAt and the observational
-// ones kept, FleetBox kept only while the region is unchanged, and every
-// ForwardForbidden column set to zero, so a stray value on a stored forward
+// through routeArgs (the forbidden ones zero). The conflict arm assigns
+// every column but host: each forwardKept column its OnConflict value, and
+// every ForwardForbidden column zero, so a stray value on a stored forward
// row does not survive a put. Its WHERE matches only a forward row: a row of
// another kind is never overwritten, even if the transaction's own check
// were bypassed.
var putForwardSQL = func() string {
- set := []string{
- "slug = excluded.slug", "kind = excluded.kind", "app = excluded.app",
- "account = excluded.account", "region = excluded.region", "channel = excluded.channel",
- "rate_limit = excluded.rate_limit", "status = excluded.status",
- "provisioned = excluded.provisioned", "created_at = routes.created_at",
- "fleet_box = CASE WHEN routes.region = excluded.region THEN routes.fleet_box ELSE '' END",
- "dns_status = routes.dns_status", "dns_checked_at = routes.dns_checked_at",
- "cert_expires_at = routes.cert_expires_at",
+ set := make([]string, 0, len(forwardKept)+len(ForwardForbidden))
+ for _, k := range forwardKept {
+ if k.OnConflict != "" {
+ set = append(set, k.Column+" = "+k.OnConflict)
+ }
}
for _, c := range ForwardForbidden {
zero := "''"
@@ -285,7 +317,9 @@ WHERE routes.kind = 'forward'`
}()
// PutForward writes rt as a forward row (spec §4.2), in one transaction. It
-// refuses an rt that is not a forward row. A row at the host that is not a
+// refuses, with ErrNotForward and before any read, an rt that is not a
+// forward row, has no Host, or whose Region is not a fleet placement
+// (FleetPlacement). A row at the host that is not a
// forward row is another writer's: ErrHostHeld, nothing written. Otherwise
// it writes the declared columns from rt (Host, Kind, Slug, App, Account,
// Region, Channel, RateLimit; Status "ready" and Provisioned true whatever rt
@@ -295,8 +329,13 @@ WHERE routes.kind = 'forward'`
// or the stored row carries. Never Upsert, which keeps non-empty stored
// values.
func (r *Registry) PutForward(rt Route) error {
- if !rt.IsForward() {
- return fmt.Errorf("registry: PutForward(%q): kind %q is not %q", rt.Host, rt.Kind, KindForward)
+ switch _, placed := FleetPlacement(rt.Region); {
+ case !rt.IsForward():
+ return fmt.Errorf("%w: PutForward(%q): kind %q is not %q", ErrNotForward, rt.Host, rt.Kind, KindForward)
+ case rt.Host == "":
+ return fmt.Errorf("%w: PutForward: no host", ErrNotForward)
+ case !placed:
+ return fmt.Errorf("%w: PutForward(%q): region %q is not a fleet placement", ErrNotForward, rt.Host, rt.Region)
}
if r.remote != nil {
_, err := r.remote.call(nil, remoteRequest{Method: "PutForward", TValue: rt}, nil)
diff --git a/internal/registry/forward_test.go b/internal/registry/forward_test.go
index 20d17656a..233a34631 100644
--- a/internal/registry/forward_test.go
+++ b/internal/registry/forward_test.go
@@ -97,21 +97,12 @@ func TestForwardShapeClassesEveryField(t *testing.T) {
}
}
-// forwardKeptColumns is the SQL column of every field that is not
-// forbidden. With ForwardForbidden it must name every column of routes once.
-var forwardKeptColumns = map[string]string{
- "Host": "host", "Kind": "kind", "Slug": "slug", "App": "app",
- "Account": "account", "Region": "region", "Channel": "channel",
- "RateLimit": "rate_limit", "Status": "status", "Provisioned": "provisioned",
- "CreatedAt": "created_at", "FleetBox": "fleet_box", "DNSStatus": "dns_status",
- "DNSCheckedAt": "dns_checked_at", "CertExpiresAt": "cert_expires_at",
-}
-
// TestForwardForbiddenMatchesTheTable: ForwardForbidden is the forbidden
// class exactly, each field once, and each entry's Column and Type are the
-// routes table's own (PRAGMA table_info). With the kept columns it covers
-// every column of routes, the ClaimOwnership ones included, so a column a
-// migration adds later fails here until it is classed.
+// routes table's own (PRAGMA table_info). With the kept columns
+// (forwardKept, the production list PutForward's conflict arm is built from)
+// it covers every column of routes, the ClaimOwnership ones included, so a
+// column a migration adds later fails here until it is classed.
func TestForwardForbiddenMatchesTheTable(t *testing.T) {
reg := openTestRegistry(t)
rows, err := reg.sql.Query(`SELECT name, type FROM pragma_table_info('routes')`)
@@ -175,18 +166,24 @@ func TestForwardForbiddenMatchesTheTable(t *testing.T) {
t.Errorf("ForwardForbidden fields = %v\nforbidden class = %v", listed, forbidden)
}
- for f, col := range forwardKeptColumns {
+ kept := map[string]bool{}
+ for _, k := range forwardKept {
+ f, col := k.Field, k.Column
+ if kept[f] {
+ t.Errorf("forwardKept lists %s twice", f)
+ }
+ kept[f] = true
if forwardShape[f] == "forbidden" || forwardShape[f] == "" {
t.Errorf("kept column %s: field %s has class %q", col, f, forwardShape[f])
}
if prev, ok := columns[col]; ok {
- t.Errorf("column %s is both kept (%s) and forbidden (%s)", col, f, prev)
+ t.Errorf("column %s is both kept (%s) and forbidden or kept again (%s)", col, f, prev)
}
columns[col] = f
}
for f, class := range forwardShape {
- if _, ok := forwardKeptColumns[f]; class != "forbidden" && !ok {
- t.Errorf("field %s (%s) has no column in this test's kept list", f, class)
+ if class != "forbidden" && !kept[f] {
+ t.Errorf("field %s (%s) has no entry in forwardKept", f, class)
}
}
for col := range table {
@@ -201,6 +198,126 @@ func TestForwardForbiddenMatchesTheTable(t *testing.T) {
}
}
+// TestPutForwardSetsEveryColumnButHost reads putForwardSQL's conflict arm
+// back against PRAGMA table_info(routes) (deferred minor, Task 2): it
+// assigns every column except host (the conflict target) exactly once, so
+// a column the arm forgets cannot keep a stale value through a put. Each
+// kept column's value follows its class: declared ones from the call
+// (excluded.*) except created_at, observational ones and created_at from
+// the stored row (routes.*), fleet_box cleared when the region moves.
+func TestPutForwardSetsEveryColumnButHost(t *testing.T) {
+ reg := openTestRegistry(t)
+ rows, err := reg.sql.Query(`SELECT name FROM pragma_table_info('routes')`)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var table []string
+ for rows.Next() {
+ var name string
+ if err := rows.Scan(&name); err != nil {
+ t.Fatal(err)
+ }
+ if name != "host" {
+ table = append(table, name)
+ }
+ }
+ if err := rows.Err(); err != nil {
+ t.Fatal(err)
+ }
+ rows.Close()
+ sort.Strings(table)
+
+ _, arm, ok := strings.Cut(putForwardSQL, "DO UPDATE SET")
+ if !ok {
+ t.Fatalf("putForwardSQL has no conflict arm:\n%s", putForwardSQL)
+ }
+ arm, _, ok = strings.Cut(arm, "\nWHERE ")
+ if !ok {
+ t.Fatalf("putForwardSQL's conflict arm has no WHERE:\n%s", putForwardSQL)
+ }
+ set := map[string]string{}
+ var assigned []string
+ for _, a := range strings.Split(arm, ",\n") {
+ col, val, ok := strings.Cut(strings.TrimSpace(a), " = ")
+ if !ok {
+ t.Fatalf("conflict-arm assignment %q has no ' = '", a)
+ }
+ if _, dup := set[col]; dup {
+ t.Errorf("the conflict arm assigns %s twice", col)
+ }
+ set[col] = val
+ assigned = append(assigned, col)
+ }
+ sort.Strings(assigned)
+ if !reflect.DeepEqual(assigned, table) {
+ t.Errorf("conflict arm assigns %v\nroutes columns but host %v", assigned, table)
+ }
+
+ for _, k := range forwardKept {
+ want := ""
+ switch {
+ case k.Column == "host":
+ if _, ok := set["host"]; ok {
+ t.Error("the conflict arm assigns host, the conflict target")
+ }
+ continue
+ case k.Column == "created_at", forwardShape[k.Field] == "observational":
+ want = "routes." + k.Column
+ case forwardShape[k.Field] == "declared":
+ want = "excluded." + k.Column
+ case k.Column == "fleet_box":
+ want = "CASE WHEN routes.region = excluded.region THEN routes.fleet_box ELSE '' END"
+ }
+ if set[k.Column] != want {
+ t.Errorf("conflict arm sets %s = %q, want %q (class %s)", k.Column, set[k.Column], want, forwardShape[k.Field])
+ }
+ }
+ for _, c := range ForwardForbidden {
+ want := "''"
+ if c.Type == "INTEGER" {
+ want = "0"
+ }
+ if set[c.Column] != want {
+ t.Errorf("conflict arm sets forbidden %s = %q, want %s", c.Column, set[c.Column], want)
+ }
+ }
+}
+
+// TestPutForwardRefusesWhatIsNotAForwardRow: a call that is not a forward
+// row, has no host, or is not placed on a fleet is ErrNotForward and writes
+// nothing (deferred minor, Task 2; spec §4.4 refuses serving such a row, so
+// this is defence in depth). Over the remote transport too.
+func TestPutForwardRefusesWhatIsNotAForwardRow(t *testing.T) {
+ local := openTestRegistry(t)
+ remote, _ := remoteTestRegistry(t)
+ for _, reg := range []*Registry{local, remote} {
+ for _, c := range []struct {
+ why string
+ edit func(*Route)
+ }{
+ {"an instance row", func(rt *Route) { rt.Kind = "instance" }},
+ {"no host", func(rt *Route) { rt.Host = "" }},
+ {"no placement", func(rt *Route) { rt.Region = "" }},
+ {"a residency code", func(rt *Route) { rt.Region = "eu" }},
+ {"an empty fleet name", func(rt *Route) { rt.Region = "fleet/" }},
+ {"a fleet name ValidTunnelName refuses", func(rt *Route) { rt.Region = "fleet/Not A Fleet" }},
+ } {
+ rt := validForward("shop.example.com", "home")
+ c.edit(&rt)
+ if err := reg.PutForward(rt); !errors.Is(err, ErrNotForward) {
+ t.Errorf("PutForward(%s) = %v, want ErrNotForward", c.why, err)
+ }
+ all, err := reg.List()
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(all) != 0 {
+ t.Fatalf("PutForward(%s) wrote %+v", c.why, all)
+ }
+ }
+ }
+}
+
// TestInertForwardChecksEachForbiddenField: one forbidden field set, and
// only that one, makes a forward row not inert.
func TestInertForwardChecksEachForbiddenField(t *testing.T) {
@@ -249,12 +366,12 @@ func TestPutForwardWritesTheExactShape(t *testing.T) {
t.Fatal("a minted forward row has no CreatedAt")
}
if _, err := reg.sql.Exec(`UPDATE routes SET tunnel = 't1', caps = 'x', unit = 'u.service', seed = 's',
-dns_status = 'pointing', cert_expires_at = 5, fleet_box = 'box-1', created_at = 1000 WHERE host = ?`, host); err != nil {
+dns_status = 'pointing', dns_checked_at = 7, cert_expires_at = 5, fleet_box = 'box-1', created_at = 1000 WHERE host = ?`, host); err != nil {
t.Fatal(err)
}
stored, err := reg.Get(host)
if err != nil || stored.Tunnel != "t1" || stored.Caps != "x" || stored.Unit != "u.service" || stored.Seed != "s" ||
- stored.DNSStatus != "pointing" || stored.CertExpiresAt != 5 || stored.FleetBox != "box-1" || stored.CreatedAt != 1000 {
+ stored.DNSStatus != "pointing" || stored.DNSCheckedAt != 7 || stored.CertExpiresAt != 5 || stored.FleetBox != "box-1" || stored.CreatedAt != 1000 {
t.Fatalf("raw SQL did not persist: %+v, %v", stored, err)
}
@@ -278,7 +395,7 @@ dns_status = 'pointing', cert_expires_at = 5, fleet_box = 'box-1', created_at =
Host: host, Kind: KindForward, Slug: "shop2", App: "shop", Account: "bah",
Region: PlacementTarget("home"), Channel: "stable", RateLimit: `{"rps":9}`,
Status: "ready", Provisioned: true, CreatedAt: 1000,
- FleetBox: "box-1", DNSStatus: "pointing", CertExpiresAt: 5,
+ FleetBox: "box-1", DNSStatus: "pointing", DNSCheckedAt: 7, CertExpiresAt: 5,
}
if *got != want {
t.Fatalf("after PutForward:\n got %+v\nwant %+v", *got, want)
@@ -298,7 +415,7 @@ dns_status = 'pointing', cert_expires_at = 5, fleet_box = 'box-1', created_at =
if got.FleetBox != "" {
t.Fatalf("FleetBox = %q after Region moved home -> away, want empty", got.FleetBox)
}
- if got.Region != PlacementTarget("away") || got.DNSStatus != "pointing" || got.CertExpiresAt != 5 || got.CreatedAt != 1000 {
+ if got.Region != PlacementTarget("away") || got.DNSStatus != "pointing" || got.DNSCheckedAt != 7 || got.CertExpiresAt != 5 || got.CreatedAt != 1000 {
t.Fatalf("after the move: %+v", *got)
}
}
@@ -372,8 +489,8 @@ func TestPutForwardRefusesAHeldHost(t *testing.T) {
notForward := validForward("other.example.com", "home")
notForward.Kind = "instance"
- if err := reg.PutForward(notForward); err == nil {
- t.Fatal("PutForward accepted an instance row")
+ if err := reg.PutForward(notForward); !errors.Is(err, ErrNotForward) {
+ t.Fatalf("PutForward(instance row) = %v, want ErrNotForward", err)
}
if got, err := reg.Get("other.example.com"); err != nil || got != nil {
t.Fatalf("a refused PutForward wrote a row: %+v, %v", got, err)
diff --git a/internal/registry/remote.go b/internal/registry/remote.go
index 380b91071..481c1e2c8 100644
--- a/internal/registry/remote.go
+++ b/internal/registry/remote.go
@@ -14,7 +14,7 @@ import (
var errRemoteMethod = errors.New("registry: unsupported remote operation")
-var remoteErrors = []error{os.ErrNotExist, os.ErrPermission, sql.ErrNoRows, ErrClaimOwnership, ErrTimerChanged, ErrTimerKind, ErrPathsChanged, ErrFleetBoxActive, context.Canceled, context.DeadlineExceeded, ErrGoodBuildChanged, ErrRuntimeFixed, ErrRootfsRow, ErrRuntimePlacement, ErrFleetKeyInUse, ErrForwardRow, ErrHostHeld}
+var remoteErrors = []error{os.ErrNotExist, os.ErrPermission, sql.ErrNoRows, ErrClaimOwnership, ErrTimerChanged, ErrTimerKind, ErrPathsChanged, ErrFleetBoxActive, context.Canceled, context.DeadlineExceeded, ErrGoodBuildChanged, ErrRuntimeFixed, ErrRootfsRow, ErrRuntimePlacement, ErrFleetKeyInUse, ErrForwardRow, ErrHostHeld, ErrNotForward}
func responseError(out remoteResponse) error {
if !out.Failed {