carlos / platform Public

Managed fleets 1b task 5: the forward row's box is authoritative when labelled (rule 3)

The hub's forward row now carries the record's box label: Route.FleetLabel,
column fleet_label (added after fleet_assigned and fleet_moved, forward rows
only; normalizeRoute clears it, so Upsert never writes one). forwardRowFor
sets FleetLabel and FleetBox from the record's FleetBox; PutForward writes
the label and fleet_box = fleet_label when it is set, never the call's own
FleetBox, and keeps today's rule (kept while the region is unchanged) for
an unlabelled row. SetFleetBoxIf changes nothing on a labelled row
(AND fleet_label = ''), so a binding cannot override the label.

forwardCurrent compares FleetLabel, and FleetBox only when the wanted row
is labelled, so a bound unlabelled row and a labelled row are both quiet:
no write after the first pass.

fleetChannelFor(fleet, boxLabel, authoritative, hub): authoritative drops
the fallback to the first connected box. The edge learns it from a
non-empty FleetLabel (fleetBoxOf, which also dials the label itself); with
the labelled box not connected the hub answers 503 with Retry-After
(errFleetDark). Fingerprint hashes fleet_label when set, so a label set over
a binding naming the same box still reloads the edge; the snapshot digest
folds it only when set.

FleetLabel is classed declared in forwardShape; FleetBox stays binding.

Tests: TestForwardRowCarriesTheLabel,
TestQuietPassWritesNothingForABoundUnlabelledRow,
TestPutForwardWritesTheLabelAsFleetBox, TestBindingDoesNotOverrideALabel,
TestBindingStillBindsUnlabelledRows, TestFingerprintSeesALabel,
TestLabelledForwardDoesNotFallBack, TestUnlabelledForwardStillFallsBack,
TestFleetChannelForAuthoritative; TestForwardShapeClassesEveryField
updated. TestPlan14RootReadCensus drift left for Task 8.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev 1c1b3cae26d7fb441af0542b07f0e8a552baee42 parent 815890a
8 files changed, +549 −38
  • internal/edge/edge.go +33 −7
  • internal/edge/fleet_route_test.go +117 −0
  • internal/provision/forward.go +15 −5
  • internal/provision/forward_test.go +138 −2
  • internal/registry/fleetbox_if_test.go +111 −0
  • internal/registry/forward.go +32 −16
  • internal/registry/forward_test.go +72 −0
  • internal/registry/registry.go +31 −8

CI failed — run details

diff --git a/internal/edge/edge.go b/internal/edge/edge.go
index a953c2455..273d4dec2 100644
--- a/internal/edge/edge.go
+++ b/internal/edge/edge.go
@@ -850,7 +850,8 @@ func (e *Edge) Reload() error {
// table, its raw account the fleet's owner. An admitted forward row
// is always in Arm; one that is not is ArmNone, never another arm.
case ArmForward:
- p := fleetProxy(served.Fleet, t.FleetBox, e.tunnels)
+ box, authoritative := fleetBoxOf(t)
+ p := fleetProxy(served.Fleet, box, authoritative, e.tunnels)
p.ModifyResponse = e.responseModifier(t)
proxy = p
viaTunnel = true
@@ -920,7 +921,8 @@ func (e *Edge) Reload() error {
if why, noted := verdict.Noted[t.Host]; noted {
e.logThrottled("fleet-accountless "+t.Host, fmt.Sprintf("route %s: %s", t.Host, why))
}
- p := fleetProxy(served.Fleet, t.FleetBox, e.tunnels)
+ box, authoritative := fleetBoxOf(t)
+ p := fleetProxy(served.Fleet, box, authoritative, e.tunnels)
p.ModifyResponse = e.responseModifier(t)
proxy = p
viaTunnel = true
@@ -3201,8 +3203,10 @@ func tunnelProxy(name string, hub *TunnelHub) *httputil.ReverseProxy {
// errFleetDark is the sentinel fleetProxy's Transport returns when fleet has
// no connected channel at all — neither the route's bound box nor any
-// fallback. fleetProxy's ErrorHandler recognizes it and answers a clean 503
-// with Retry-After: 2 instead of the ReverseProxy default (a 502 with a
+// fallback — or, for a labelled forward row, when its labelled box is not
+// connected (fleetChannelFor's authoritative case). fleetProxy's
+// ErrorHandler recognizes it and answers a clean 503 with Retry-After: 2
+// instead of the ReverseProxy default (a 502 with a
// "context deadline exceeded"-flavored body that reads like a broken backend
// rather than "no box is home right now, try again shortly").
var errFleetDark = errors.New("edge: fleet has no connected channel")
@@ -3220,18 +3224,38 @@ var errFleetDark = errors.New("edge: fleet has no connected channel")
//
// boxLabel may be "" (a route that wants a fleet but has no box assigned
// yet), which just skips straight to the fallback step.
-func fleetChannelFor(fleet, boxLabel string, hub *TunnelHub) string {
+//
+// authoritative (managed fleets 1b, rule 3: a forward row whose FleetLabel
+// is set) drops step 2: the labelled box is the only one that runs the
+// instance, so another box's channel would start a second copy. Its channel
+// or "", and "" answers 503 with Retry-After (errFleetDark) until the box
+// reconnects or the console relabels the record.
+func fleetChannelFor(fleet, boxLabel string, authoritative bool, hub *TunnelHub) string {
if boxLabel != "" {
if bound := fleet + "/" + boxLabel; hub.State(bound) == "connected" {
return bound
}
}
+ if authoritative {
+ return ""
+ }
if names := hub.ConnectedOfFleet(fleet); len(names) > 0 {
return names[0]
}
return ""
}
+// fleetBoxOf is the box fleetProxy dials for t first, and whether that box
+// is authoritative: a labelled forward row's FleetLabel (managed fleets 1b,
+// rule 3), which no fallback replaces, else its FleetBox binding, which the
+// fallback may.
+func fleetBoxOf(t registry.Route) (string, bool) {
+ if t.FleetLabel != "" {
+ return t.FleetLabel, true
+ }
+ return t.FleetBox, false
+}
+
// fleetProxy reverse-proxies a fleet-placed route (Region == "fleet/<fleet>",
// registry.FleetPlacement) over whichever channel fleetChannelFor picks —
// resolved PER REQUEST, mirroring tunnelProxy/transportFor above, so a bound
@@ -3240,7 +3264,9 @@ func fleetChannelFor(fleet, boxLabel string, hub *TunnelHub) string {
// and purge-header discipline as tunnelProxy; the only difference is the
// no-channel-at-all case, which answers 503 + Retry-After via ErrorHandler
// instead of falling into ReverseProxy's default 502 (see errFleetDark).
-func fleetProxy(fleet, boxLabel string, hub *TunnelHub) *httputil.ReverseProxy {
+// authoritative is fleetChannelFor's: the route's FleetLabel is set, and
+// boxLabel is that label (fleetBoxOf).
+func fleetProxy(fleet, boxLabel string, authoritative bool, hub *TunnelHub) *httputil.ReverseProxy {
return &httputil.ReverseProxy{
Rewrite: func(pr *httputil.ProxyRequest) {
setForwarded(pr)
@@ -3251,7 +3277,7 @@ func fleetProxy(fleet, boxLabel string, hub *TunnelHub) *httputil.ReverseProxy {
scrubInboundPurgeHeader(pr)
},
Transport: roundTripperFunc(func(req *http.Request) (*http.Response, error) {
- name := fleetChannelFor(fleet, boxLabel, hub)
+ name := fleetChannelFor(fleet, boxLabel, authoritative, hub)
if name == "" {
return nil, errFleetDark
}
diff --git a/internal/edge/fleet_route_test.go b/internal/edge/fleet_route_test.go
index a1764b490..a00277a4c 100644
--- a/internal/edge/fleet_route_test.go
+++ b/internal/edge/fleet_route_test.go
@@ -296,3 +296,120 @@ func TestConnectedOfFleetSortedAndFiltered(t *testing.T) {
t.Fatalf("ConnectedOfFleet(acme) = %v, want %v", got, want)
}
}
+
+// forwardFleetEdge is the hub for managed fleets 1b's rule 3: fleet pi
+// (owned by fwdOwner) with active boxes pi-1 and pi-2, and one forward row
+// for shop.example.com written by PutForward with label ("" = unlabelled),
+// then bound to bind by SetFleetBoxIf when bind is not "". The process
+// environment says this box is the hub, as forwardHubAndBox arranges.
+func forwardFleetEdge(t *testing.T, label, bind string) (string, *TunnelHub) {
+ t.Helper()
+ reg := openReg(t)
+ if err := reg.UpsertFleet(registry.Fleet{Name: "pi", Account: fwdOwner, Bucket: "pi-data"}); err != nil {
+ t.Fatal(err)
+ }
+ for box, token := range map[string]string{"pi-1": "tok1", "pi-2": "tok2"} {
+ if err := reg.AddFleetBox(registry.FleetBox{Fleet: "pi", Label: box, TokenHash: sha256Hex(token), Status: "active"}); err != nil {
+ t.Fatal(err)
+ }
+ }
+ rt := forwardRow("shop.example.com", "pi", fwdOwner)
+ rt.FleetLabel = label
+ if err := reg.PutForward(rt); err != nil {
+ t.Fatal(err)
+ }
+ if bind != "" {
+ if changed, err := reg.SetFleetBoxIf(rt.Host, "pi", bind); err != nil || !changed {
+ t.Fatalf("SetFleetBoxIf(%s) = %v, %v; want the row bound", bind, changed, err)
+ }
+ }
+ e, err := New(reg, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(e.probers.Stop)
+ srv := httptest.NewServer(e)
+ t.Cleanup(srv.Close)
+ u, err := url.Parse(srv.URL)
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Setenv("CARLOS_TUNNEL_HOST", u.Hostname())
+ t.Setenv("CARLOS_FLEET", "")
+ hub := NewTunnelHub(u.Hostname(), nil)
+ e.EnableTunnels(hub)
+ if err := e.Reload(); err != nil {
+ t.Fatal(err)
+ }
+ if !e.Allowed("shop.example.com") {
+ t.Fatal("fixture: the hub does not serve the forward row")
+ }
+ return srv.URL, hub
+}
+
+// TestLabelledForwardDoesNotFallBack (managed fleets 1b, rule 3): a forward
+// row labelled pi-2 goes only to pi-2. With only pi-1 connected the hub
+// answers 503 with Retry-After, never pi-1: pi-1 does not run the instance,
+// and a fallback there would start a second copy.
+func TestLabelledForwardDoesNotFallBack(t *testing.T) {
+ edgeURL, hub := forwardFleetEdge(t, "pi-2", "")
+ stop1 := startFakeRemoteHost(t, edgeURL, "pi/pi-1", "tok1", namedHandler("pi-1"))
+ defer stop1()
+ waitForTunnelState(t, hub, "pi/pi-1", "connected", e2eReconnectBound)
+ if hub.State("pi/pi-2") == "connected" {
+ t.Fatal("test setup: pi-2 must not be connected")
+ }
+ resp := getHostFull(t, edgeURL, "shop.example.com")
+ defer resp.Body.Close()
+ if resp.StatusCode != http.StatusServiceUnavailable {
+ t.Fatalf("got %d, want 503 (no fallback to pi-1 for a labelled row)", resp.StatusCode)
+ }
+ if got := resp.Header.Get("Retry-After"); got != "2" {
+ t.Fatalf("Retry-After = %q, want %q", got, "2")
+ }
+
+ stop2 := startFakeRemoteHost(t, edgeURL, "pi/pi-2", "tok2", namedHandler("pi-2"))
+ defer stop2()
+ waitForTunnelState(t, hub, "pi/pi-2", "connected", e2eReconnectBound)
+ if code, body := getHost(t, edgeURL, "shop.example.com"); code != http.StatusOK || body != "pi-2" {
+ t.Fatalf("with pi-2 connected: got %d %q, want 200 pi-2", code, body)
+ }
+}
+
+// TestUnlabelledForwardStillFallsBack: an unlabelled forward row keeps
+// today's rule. Bound to pi-2 by a binding, with only pi-1 connected, the
+// hub falls back to pi-1.
+func TestUnlabelledForwardStillFallsBack(t *testing.T) {
+ edgeURL, hub := forwardFleetEdge(t, "", "pi-2")
+ stop1 := startFakeRemoteHost(t, edgeURL, "pi/pi-1", "tok1", namedHandler("pi-1"))
+ defer stop1()
+ waitForTunnelState(t, hub, "pi/pi-1", "connected", e2eReconnectBound)
+ if code, body := getHost(t, edgeURL, "shop.example.com"); code != http.StatusOK || body != "pi-1" {
+ t.Fatalf("got %d %q, want 200 pi-1 (fallback for an unlabelled row)", code, body)
+ }
+}
+
+// TestFleetChannelForAuthoritative: the pick itself. Authoritative names
+// only the label's channel; not authoritative keeps the bound-then-first
+// fallback.
+func TestFleetChannelForAuthoritative(t *testing.T) {
+ edgeURL, hub := forwardFleetEdge(t, "", "")
+ stop1 := startFakeRemoteHost(t, edgeURL, "pi/pi-1", "tok1", namedHandler("pi-1"))
+ defer stop1()
+ waitForTunnelState(t, hub, "pi/pi-1", "connected", e2eReconnectBound)
+ for _, c := range []struct {
+ box string
+ auth bool
+ want string
+ }{
+ {"pi-2", true, ""},
+ {"pi-1", true, "pi/pi-1"},
+ {"pi-2", false, "pi/pi-1"},
+ {"", false, "pi/pi-1"},
+ {"", true, ""},
+ } {
+ if got := fleetChannelFor("pi", c.box, c.auth, hub); got != c.want {
+ t.Errorf("fleetChannelFor(pi, %q, %v) = %q, want %q", c.box, c.auth, got, c.want)
+ }
+ }
+}
diff --git a/internal/provision/forward.go b/internal/provision/forward.go
index 382826ecc..4740de4f4 100644
--- a/internal/provision/forward.go
+++ b/internal/provision/forward.go
@@ -20,8 +20,11 @@ import (
// forwardRowFor is the forward row a fleet-placed record describes: the
// declared columns of spec §4.2 and nothing else. CreatedAt is PutForward's
-// (kept from the existing row, else now), FleetBox the bindings pass's, and
-// every forbidden column is zero, so the row is InertForward by construction.
+// (kept from the existing row, else now), and every forbidden column is
+// zero, so the row is InertForward by construction. FleetLabel is the
+// record's box label (managed fleets 1b, rule 3), and a labelled row's
+// FleetBox is that label, which is what PutForward stores; an unlabelled
+// row's FleetBox is the bindings pass's.
func forwardRowFor(rec Record) registry.Route {
return registry.Route{
Host: rec.Host,
@@ -34,12 +37,17 @@ func forwardRowFor(rec Record) registry.Route {
RateLimit: rec.RateLimitColumn(),
Status: "ready",
Provisioned: true,
+ FleetLabel: rec.FleetBox,
+ FleetBox: rec.FleetBox,
}
}
// forwardCurrent reports whether existing already is want: an inert forward
-// row with want's declared columns. Such a row is not written again, so a
-// pass with nothing changing writes nothing (and wakes no registry watcher).
+// row with want's declared columns, its label included. FleetBox counts only
+// when want is labelled (it must then be the label); on an unlabelled row it
+// is the binding's, which this pass does not undo. Such a row is not written
+// again, so a pass with nothing changing writes nothing (and wakes no
+// registry watcher).
func forwardCurrent(existing, want registry.Route) bool {
return existing.InertForward() &&
existing.Status == want.Status &&
@@ -49,7 +57,9 @@ func forwardCurrent(existing, want registry.Route) bool {
existing.Account == want.Account &&
existing.Region == want.Region &&
existing.Channel == want.Channel &&
- existing.RateLimit == want.RateLimit
+ existing.RateLimit == want.RateLimit &&
+ existing.FleetLabel == want.FleetLabel &&
+ (want.FleetLabel == "" || existing.FleetBox == want.FleetBox)
}
// forwardDecision is step 3's answer for one fleet-placed record.
diff --git a/internal/provision/forward_test.go b/internal/provision/forward_test.go
index 2af7b4e7a..a68e4c3db 100644
--- a/internal/provision/forward_test.go
+++ b/internal/provision/forward_test.go
@@ -3,11 +3,13 @@ package provision
import (
"bytes"
"context"
+ "database/sql"
"errors"
"fmt"
"io"
"log"
"os"
+ "path/filepath"
"reflect"
"strings"
"sync"
@@ -101,8 +103,11 @@ func wantForward(t *testing.T, reg *registry.Registry, rec Record) registry.Rout
}
got := *rt
got.CreatedAt = 0
- got.FleetBox = ""
- if want := forwardRowFor(rec); !reflect.DeepEqual(got, want) {
+ want := forwardRowFor(rec)
+ if want.FleetLabel == "" {
+ got.FleetBox = "" // the binding's, not the record's
+ }
+ if !reflect.DeepEqual(got, want) {
t.Fatalf("forward row at %s:\n got %+v\nwant %+v", rec.Host, got, want)
}
return *rt
@@ -872,3 +877,134 @@ func TestForwardCollisionKeepsTheRowOfATrashedApp(t *testing.T) {
})
}
}
+
+// TestForwardRowCarriesTheLabel (managed fleets 1b, rule 3): a labelled
+// record's forward row carries its box as FleetLabel and as FleetBox from
+// the first mint, so the first request goes to the right box; a relabel
+// rewrites the row on the next pass. An unlabelled record's row carries
+// neither.
+func TestForwardRowCarriesTheLabel(t *testing.T) {
+ plain := fwdRecord("bah", "shop", "shop.example.com", "fleet/pi")
+ if rt := forwardRowFor(plain); rt.FleetLabel != "" || rt.FleetBox != "" {
+ t.Fatalf("unlabelled record: label %q box %q, want both empty", rt.FleetLabel, rt.FleetBox)
+ }
+ labelled := plain
+ labelled.FleetBox = "pi-2"
+ if rt := forwardRowFor(labelled); rt.FleetLabel != "pi-2" || rt.FleetBox != "pi-2" {
+ t.Fatalf("labelled record: label %q box %q, want pi-2 pi-2", rt.FleetLabel, rt.FleetBox)
+ }
+
+ s := dirStore(t)
+ bah, _ := fwdSetup(t, s)
+ rec := fwdRecord(bah, "shop", "shop.example.com", "fleet/pi")
+ rec.FleetBox, rec.FleetBoxAt = "pi-2", "2026-10-30T09:00:00Z"
+ mustCreate(t, s, rec)
+ reg := regWith(t)
+ cfg := hubCfg(map[string]string{"pi": bah})
+ mustPass(t, s, reg, cfg)
+ if got := wantForward(t, reg, rec); got.FleetLabel != "pi-2" || got.FleetBox != "pi-2" {
+ t.Fatalf("minted: label %q box %q, want pi-2 pi-2", got.FleetLabel, got.FleetBox)
+ }
+
+ cur, err := GetRecord(ctx, s, bah, rec.App, rec.Host)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := SetRecordFleetBox(ctx, s, bah, rec.App, rec.Host,
+ FleetBoxExpect{Region: "fleet/pi", Label: "pi-2", CreatedAt: cur.CreatedAt}, "pi-1", time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ mustPass(t, s, reg, cfg)
+ if got := getRow(t, reg, rec.Host); got == nil || got.FleetLabel != "pi-1" || got.FleetBox != "pi-1" {
+ t.Fatalf("after the relabel: %+v, want label and box pi-1", got)
+ }
+}
+
+// TestQuietPassWritesNothingForABoundUnlabelledRow: a forward row a binding
+// has bound, its record unlabelled, is current as it is: the binding is not
+// the record's to undo, so the next passes write nothing. A labelled row is
+// as quiet once minted. The witness is a trigger counting every insert and
+// update on routes, over three passes.
+func TestQuietPassWritesNothingForABoundUnlabelledRow(t *testing.T) {
+ s := dirStore(t)
+ bah, _ := fwdSetup(t, s)
+ plain := fwdRecord(bah, "shop", "shop.example.com", "fleet/pi")
+ labelled := fwdRecord(bah, "shop2", "shop2.example.com", "fleet/pi")
+ labelled.FleetBox, labelled.FleetBoxAt = "pi-2", "2026-10-30T09:00:00Z"
+ mustCreate(t, s, plain, labelled)
+
+ path := filepath.Join(t.TempDir(), "registry.db")
+ reg, err := registry.Open(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := reg.UpsertFleet(registry.Fleet{Name: "pi", Account: bah, Bucket: "pi-data"}); err != nil {
+ t.Fatal(err)
+ }
+ for _, label := range []string{"pi-1", "pi-2"} {
+ if err := reg.AddFleetBox(registry.FleetBox{Fleet: "pi", Label: label, TokenHash: strings.Repeat("a", 64), Status: "active"}); err != nil {
+ t.Fatal(err)
+ }
+ }
+ db, err := sql.Open("sqlite", path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer db.Close()
+ for _, stmt := range []string{
+ `CREATE TABLE t5_writes (host TEXT)`,
+ `CREATE TRIGGER t5_i AFTER INSERT ON routes BEGIN INSERT INTO t5_writes VALUES (new.host); END`,
+ `CREATE TRIGGER t5_u AFTER UPDATE ON routes BEGIN INSERT INTO t5_writes VALUES (new.host); END`,
+ } {
+ if _, err := db.Exec(stmt); err != nil {
+ t.Fatal(err)
+ }
+ }
+ writes := func() map[string]int {
+ t.Helper()
+ rows, err := db.Query(`SELECT host, COUNT(*) FROM t5_writes GROUP BY host`)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer rows.Close()
+ out := map[string]int{}
+ for rows.Next() {
+ var h string
+ var n int
+ if err := rows.Scan(&h, &n); err != nil {
+ t.Fatal(err)
+ }
+ out[h] = n
+ }
+ if _, err := db.Exec(`DELETE FROM t5_writes`); err != nil {
+ t.Fatal(err)
+ }
+ return out
+ }
+
+ cfg := hubCfg(map[string]string{"pi": bah})
+ for pass := 1; pass <= 3; pass++ {
+ mustPass(t, s, reg, cfg)
+ got := writes()
+ if pass == 1 {
+ if got[plain.Host] != 1 || got[labelled.Host] != 1 {
+ t.Fatalf("pass 1 writes %v, want one mint each", got)
+ }
+ // The binding the plain row's box publishes after a wake.
+ if changed, err := reg.SetFleetBoxIf(plain.Host, "pi", "pi-1"); err != nil || !changed {
+ t.Fatalf("SetFleetBoxIf = %v, %v; want the unlabelled row bound", changed, err)
+ }
+ writes()
+ continue
+ }
+ if len(got) != 0 {
+ t.Errorf("pass %d wrote %v, want nothing", pass, got)
+ }
+ if rt := getRow(t, reg, plain.Host); rt == nil || rt.FleetBox != "pi-1" || rt.FleetLabel != "" {
+ t.Errorf("pass %d: the bound unlabelled row is %+v, want box pi-1 kept, no label", pass, rt)
+ }
+ if rt := getRow(t, reg, labelled.Host); rt == nil || rt.FleetBox != "pi-2" || rt.FleetLabel != "pi-2" {
+ t.Errorf("pass %d: the labelled row is %+v, want box and label pi-2", pass, rt)
+ }
+ }
+}
diff --git a/internal/registry/fleetbox_if_test.go b/internal/registry/fleetbox_if_test.go
index bf4b66023..29c669460 100644
--- a/internal/registry/fleetbox_if_test.go
+++ b/internal/registry/fleetbox_if_test.go
@@ -111,6 +111,83 @@ func TestSetFleetBoxIfBindsPlacementKindAndMembership(t *testing.T) {
}
}
+// labelFleet seeds fleet pi with active boxes pi-1 and pi-2 and puts host's
+// forward row on it with label ("" for an unlabelled row).
+func labelFleet(t *testing.T, reg *Registry, host, label string) {
+ t.Helper()
+ if err := reg.UpsertFleet(Fleet{Name: "pi", Account: "bah", Bucket: "pi-data"}); err != nil {
+ t.Fatal(err)
+ }
+ for _, b := range []FleetBox{
+ {Fleet: "pi", Label: "pi-1", TokenHash: tokenHashA, Status: "active"},
+ {Fleet: "pi", Label: "pi-2", TokenHash: tokenHashB, Status: "active"},
+ } {
+ if err := reg.AddFleetBox(b); err != nil && !errors.Is(err, ErrFleetBoxActive) {
+ t.Fatal(err)
+ }
+ }
+ rt := Route{Host: host, Kind: KindForward, Slug: "shop", App: "shop", Account: "bah",
+ Region: PlacementTarget("pi"), Channel: "stable", FleetLabel: label}
+ if err := reg.PutForward(rt); err != nil {
+ t.Fatal(err)
+ }
+}
+
+// TestBindingDoesNotOverrideALabel (managed fleets 1b, rule 3): on a forward
+// row the record labelled, the label is the box. A binding from another
+// active box of the same fleet, or from the labelled box itself, changes
+// nothing.
+func TestBindingDoesNotOverrideALabel(t *testing.T) {
+ reg := openTestRegistry(t)
+ const host = "shop.example.com"
+ labelFleet(t, reg, host, "pi-2")
+ for _, label := range []string{"pi-1", "pi-2"} {
+ changed, err := reg.SetFleetBoxIf(host, "pi", label)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if changed {
+ t.Errorf("SetFleetBoxIf(%s) changed a labelled row", label)
+ }
+ got, err := reg.Get(host)
+ if err != nil || got == nil {
+ t.Fatal(got, err)
+ }
+ if got.FleetBox != "pi-2" || got.FleetLabel != "pi-2" {
+ t.Errorf("after SetFleetBoxIf(%s): box %q label %q, want pi-2 pi-2", label, got.FleetBox, got.FleetLabel)
+ }
+ }
+}
+
+// TestBindingStillBindsUnlabelledRows: an unlabelled forward row, and an
+// instance row (which never carries a label), are bound as today, and a row
+// whose label was dropped is bound again.
+func TestBindingStillBindsUnlabelledRows(t *testing.T) {
+ reg := openTestRegistry(t)
+ const host, inst, dropped = "shop.example.com", "inst.example.com", "dropped.example.com"
+ labelFleet(t, reg, host, "")
+ for _, label := range []string{"pi-1", "pi-2"} {
+ changed, err := reg.SetFleetBoxIf(host, "pi", label)
+ if err != nil || !changed {
+ t.Fatalf("SetFleetBoxIf(%s) on an unlabelled row = %v, %v; want true, nil", label, changed, err)
+ }
+ if got, err := reg.Get(host); err != nil || got.FleetBox != label {
+ t.Fatalf("after SetFleetBoxIf(%s): %+v, %v", label, got, err)
+ }
+ }
+ fleetBoundRow(t, reg, inst, "pi", "pi-1")
+
+ labelFleet(t, reg, dropped, "pi-2")
+ labelFleet(t, reg, dropped, "")
+ changed, err := reg.SetFleetBoxIf(dropped, "pi", "pi-1")
+ if err != nil || !changed {
+ t.Fatalf("SetFleetBoxIf on a row whose label was dropped = %v, %v; want true, nil", changed, err)
+ }
+ if got, err := reg.Get(dropped); err != nil || got.FleetBox != "pi-1" {
+ t.Fatalf("dropped-label row after binding: %+v, %v", got, 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.
@@ -132,3 +209,37 @@ func TestSetFleetBoxIfOverRemote(t *testing.T) {
t.Error("remote SetFleetBoxIf bound a row to another fleet's box")
}
}
+
+// TestFingerprintSeesALabel: a label set over a binding that already named
+// the same box changes no other hashed column, yet it makes that box
+// authoritative at the edge (no fallback), so it must move the digest the
+// edge reloads on.
+func TestFingerprintSeesALabel(t *testing.T) {
+ reg := openTestRegistry(t)
+ const host = "shop.example.com"
+ labelFleet(t, reg, host, "")
+ if changed, err := reg.SetFleetBoxIf(host, "pi", "pi-2"); err != nil || !changed {
+ t.Fatalf("SetFleetBoxIf = %v, %v", changed, err)
+ }
+ before, err := reg.Fingerprint()
+ if err != nil {
+ t.Fatal(err)
+ }
+ // PutForward alone: labelFleet would rewrite the fleet too, which moves
+ // the digest by itself.
+ rt := Route{Host: host, Kind: KindForward, Slug: "shop", App: "shop", Account: "bah",
+ Region: PlacementTarget("pi"), Channel: "stable", FleetLabel: "pi-2"}
+ if err := reg.PutForward(rt); err != nil {
+ t.Fatal(err)
+ }
+ if got, err := reg.Get(host); err != nil || got.FleetBox != "pi-2" || got.FleetLabel != "pi-2" {
+ t.Fatalf("labelled row: %+v, %v", got, err)
+ }
+ after, err := reg.Fingerprint()
+ if err != nil {
+ t.Fatal(err)
+ }
+ if before == after {
+ t.Fatal("labelling a row bound to the same box did not move Fingerprint: the edge would keep falling back")
+ }
+}
diff --git a/internal/registry/forward.go b/internal/registry/forward.go
index 39030e5ae..7df788902 100644
--- a/internal/registry/forward.go
+++ b/internal/registry/forward.go
@@ -11,8 +11,12 @@ import (
// 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.
+// column), is not a sidecar, carries no fleet label, and label is an ACTIVE
+// box of that same fleet. It answers whether a row changed.
+//
+// A labelled row (Route.FleetLabel, managed fleets 1b rule 3) is never
+// changed: its box is the record's, written by PutForward, and a binding,
+// a box's own claim, cannot override it.
//
// 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
@@ -22,8 +26,9 @@ import (
//
// 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
+// binding does not apply. This is the only door that writes fleet_box
+// besides PutForward's copy of a label; 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) {
@@ -37,6 +42,7 @@ UPDATE routes SET fleet_box = ?
WHERE host = ?
AND region = 'fleet/' || ?
AND kind <> 'sidecar'
+ AND fleet_label = ''
AND EXISTS (SELECT 1 FROM fleet_boxes
WHERE fleet = ? AND label = ? AND status = 'active')`,
label, host, fleet, fleet, label)
@@ -76,8 +82,11 @@ var ErrHostHeld = errors.New("registry: another row holds the host")
// - declared: written only by PutForward, from its argument (Status and
// Provisioned are fixed, "ready" and true; CreatedAt is kept from the
// existing row, else now);
-// - binding: FleetBox, written only by SetFleetBoxIf; PutForward keeps it
-// while Region is unchanged and clears it when Region changes;
+// - binding: FleetBox. On a labelled row (FleetLabel set, managed fleets
+// 1b rule 3) PutForward writes it equal to the label and SetFleetBoxIf
+// never changes it. On an unlabelled row it is written only by
+// SetFleetBoxIf; PutForward keeps it while Region is unchanged and
+// clears it when Region changes;
// - observational: written by the domains health pass, kept by PutForward,
// read by no dispatch, publication or eligibility decision;
// - forbidden: zero on every forward row (ForwardForbidden, InertForward).
@@ -88,7 +97,7 @@ var forwardShape = map[string]string{
"Host": "declared", "Kind": "declared", "Slug": "declared", "App": "declared",
"Account": "declared", "Region": "declared", "Channel": "declared",
"RateLimit": "declared", "Status": "declared", "Provisioned": "declared",
- "CreatedAt": "declared",
+ "CreatedAt": "declared", "FleetLabel": "declared",
"FleetBox": "binding",
@@ -258,8 +267,9 @@ var fingerprintForwardInert = func() string {
// 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
+// column too: declared ones from the call (the label included), CreatedAt
+// and the observational ones kept, FleetBox the label when the call carries
+// one and otherwise kept only while the region is unchanged, and every
// ForwardForbidden column set to 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
@@ -270,7 +280,9 @@ var putForwardSQL = func() string {
"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",
+ "fleet_label = excluded.fleet_label",
+ "fleet_box = CASE WHEN excluded.fleet_label <> '' THEN excluded.fleet_label" +
+ " 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",
}
@@ -292,12 +304,14 @@ WHERE routes.kind = 'forward'`
// refuses an rt that is not a forward row. 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
-// says), keeps CreatedAt (now on a new row) and the observational columns
-// (zero on a new row), keeps FleetBox only while Region is unchanged (empty
-// on a new row), and writes zero to every ForwardForbidden column whatever rt
-// or the stored row carries. Never Upsert, which keeps non-empty stored
-// values.
+// Region, Channel, RateLimit, FleetLabel; Status "ready" and Provisioned
+// true whatever rt says), keeps CreatedAt (now on a new row) and the
+// observational columns (zero on a new row), and writes zero to every
+// ForwardForbidden column whatever rt or the stored row carries. FleetBox is
+// never rt's: with a label it is the label (managed fleets 1b, rule 3: the
+// record's box is authoritative), without one it is kept only while Region
+// is unchanged (empty on a new row). 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)
@@ -319,6 +333,8 @@ func (r *Registry) PutForward(rt Route) error {
Status: "ready",
Provisioned: true,
CreatedAt: time.Now().Unix(),
+ FleetLabel: rt.FleetLabel,
+ FleetBox: rt.FleetLabel,
}
return r.inImmediateTx(func(tx txer) error {
var kind string
diff --git a/internal/registry/forward_test.go b/internal/registry/forward_test.go
index 20d17656a..6d9168987 100644
--- a/internal/registry/forward_test.go
+++ b/internal/registry/forward_test.go
@@ -95,6 +95,15 @@ func TestForwardShapeClassesEveryField(t *testing.T) {
if _, ok := forwardShape["WakeIncarnation"]; ok {
t.Error("forwardShape lists WakeIncarnation, which is not persisted")
}
+ // Managed fleets 1b, rule 3: the label is the record's, declared by
+ // PutForward; FleetBox stays the binding class (the label's copy on a
+ // labelled row, SetFleetBoxIf's on an unlabelled one).
+ if c := forwardShape["FleetLabel"]; c != "declared" {
+ t.Errorf("forwardShape[FleetLabel] = %q, want declared", c)
+ }
+ if c := forwardShape["FleetBox"]; c != "binding" {
+ t.Errorf("forwardShape[FleetBox] = %q, want binding", c)
+ }
}
// forwardKeptColumns is the SQL column of every field that is not
@@ -105,6 +114,7 @@ var forwardKeptColumns = map[string]string{
"RateLimit": "rate_limit", "Status": "status", "Provisioned": "provisioned",
"CreatedAt": "created_at", "FleetBox": "fleet_box", "DNSStatus": "dns_status",
"DNSCheckedAt": "dns_checked_at", "CertExpiresAt": "cert_expires_at",
+ "FleetLabel": "fleet_label",
}
// TestForwardForbiddenMatchesTheTable: ForwardForbidden is the forbidden
@@ -303,6 +313,68 @@ dns_status = 'pointing', cert_expires_at = 5, fleet_box = 'box-1', created_at =
}
}
+// TestPutForwardWritesTheLabelAsFleetBox (managed fleets 1b, rule 3): a
+// labelled forward row stores its label and carries it as FleetBox, whatever
+// the call's FleetBox or the stored binding says; a relabel, a move to
+// another fleet and a stray fleet_box are all put right by the next put. A
+// put that drops the label goes back to today's rule: FleetBox kept while
+// the region is unchanged.
+func TestPutForwardWritesTheLabelAsFleetBox(t *testing.T) {
+ reg := openTestRegistry(t)
+ const host = "shop.example.com"
+ read := func(why string) Route {
+ t.Helper()
+ got, err := reg.Get(host)
+ if err != nil || got == nil {
+ t.Fatalf("%s: Get = %v, %v", why, got, err)
+ }
+ if !got.InertForward() {
+ t.Fatalf("%s: not inert: %+v", why, *got)
+ }
+ return *got
+ }
+ put := func(fleet, label, box string) {
+ t.Helper()
+ in := validForward(host, fleet)
+ in.FleetLabel, in.FleetBox = label, box
+ if err := reg.PutForward(in); err != nil {
+ t.Fatal(err)
+ }
+ }
+
+ put("pi", "pi-2", "pi-9") // the call's own FleetBox is never written
+ if got := read("minted"); got.FleetLabel != "pi-2" || got.FleetBox != "pi-2" {
+ t.Fatalf("minted labelled row: label %q box %q, want pi-2 pi-2", got.FleetLabel, got.FleetBox)
+ }
+
+ if _, err := reg.sql.Exec(`UPDATE routes SET fleet_box = 'pi-1' WHERE host = ?`, host); err != nil {
+ t.Fatal(err)
+ }
+ put("pi", "pi-2", "")
+ if got := read("stray box"); got.FleetLabel != "pi-2" || got.FleetBox != "pi-2" {
+ t.Fatalf("after a stray fleet_box: label %q box %q, want pi-2 pi-2", got.FleetLabel, got.FleetBox)
+ }
+
+ put("pi", "pi-1", "")
+ if got := read("relabelled"); got.FleetLabel != "pi-1" || got.FleetBox != "pi-1" {
+ t.Fatalf("relabelled: label %q box %q, want pi-1 pi-1", got.FleetLabel, got.FleetBox)
+ }
+
+ put("away", "away-1", "")
+ if got := read("moved"); got.Region != PlacementTarget("away") || got.FleetLabel != "away-1" || got.FleetBox != "away-1" {
+ t.Fatalf("moved to another fleet: region %q label %q box %q", got.Region, got.FleetLabel, got.FleetBox)
+ }
+
+ put("away", "", "")
+ if got := read("unlabelled"); got.FleetLabel != "" || got.FleetBox != "away-1" {
+ t.Fatalf("label dropped, region unchanged: label %q box %q, want \"\" away-1 (kept, today's rule)", got.FleetLabel, got.FleetBox)
+ }
+ put("pi", "", "")
+ if got := read("unlabelled move"); got.FleetLabel != "" || got.FleetBox != "" {
+ t.Fatalf("unlabelled move: label %q box %q, want both empty", got.FleetLabel, got.FleetBox)
+ }
+}
+
// TestPutForwardSanitisesEachForbiddenColumn: each forbidden column, set on
// a stored forward row by raw SQL, reads back zero after PutForward. This
// also proves each entry's Column is its Field's column. Each column gets a
diff --git a/internal/registry/registry.go b/internal/registry/registry.go
index 86b858a39..d21f3a407 100644
--- a/internal/registry/registry.go
+++ b/internal/registry/registry.go
@@ -181,9 +181,18 @@ 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 SetFleetBoxIf (forward.go); Upsert preserves non-empty values — see
+ // by SetFleetBoxIf (forward.go) and, on a labelled forward row, by
+ // PutForward from FleetLabel; Upsert preserves non-empty values — see
// Environment's comment for why.
FleetBox string
+ // FleetLabel is the fleet box the instance record is assigned to
+ // (managed fleets 1b, rule 3: the record's FleetBox), on a forward row
+ // only: PutForward writes it from the record, and writes FleetBox equal
+ // to it when it is set. A labelled row's box is authoritative: no
+ // binding overrides it (SetFleetBoxIf) and the edge never falls back to
+ // another box for it. "" = unlabelled, today's bindings and fallback.
+ // Upsert never writes one (normalizeRoute clears it).
+ FleetLabel 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
@@ -730,6 +739,9 @@ var routeAddedColumns = []addedColumn{
// Route.Moved).
{Name: "fleet_assigned", Type: "TEXT", Default: "''"},
{Name: "fleet_moved", Type: "INTEGER", Default: "0"},
+ // Managed fleets 1b, rule 3: a forward row's record label
+ // (Route.FleetLabel).
+ {Name: "fleet_label", Type: "TEXT", Default: "''"},
// Host claims' ownership (migrateClaimOwnership, routes and timers).
{Name: "claim_incarnation", Type: "TEXT", Default: "''", Claim: true},
{Name: "claim_stamp", Type: "INTEGER", Default: "0", Claim: true},
@@ -1072,10 +1084,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, fleet_assigned, fleet_moved`
+egress_allow, size, policy_expires_at, ha, fleet_assigned, fleet_moved, fleet_label`
// routeColCount is the number of names in routeCols.
-const routeColCount = 67
+const routeColCount = 68
// placeholders is n comma-joined bind parameters.
func placeholders(n int) string {
@@ -1094,7 +1106,7 @@ 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.Assigned, &moved)
+ &t.EgressAllow, &t.Size, &t.PolicyExpiresAt, &ha, &t.Assigned, &moved, &t.FleetLabel)
t.HA = ha != 0
t.Moved = moved != 0
t.AssetsOff = assetsOff != 0
@@ -1642,6 +1654,9 @@ func normalizeRoute(t Route) Route {
if t.Replica {
t.Replicas = ""
}
+ // A fleet label is a forward row's alone (PutForward, managed fleets
+ // 1b rule 3); no row this function normalizes is one.
+ t.FleetLabel = ""
return t
}
@@ -1659,7 +1674,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.Assigned, b2iDB(t.Moved),
+ t.EgressAllow, t.Size, t.PolicyExpiresAt, b2iDB(t.HA), t.Assigned, b2iDB(t.Moved), t.FleetLabel,
}
}
@@ -3879,7 +3894,7 @@ SELECT rowid, status, socket, addr, version, hibernate, channel, backing, tunnel
db_path, region, fleet_box, addrs, health, gate, hold_op, import_gate, rate_limit,
claim_incarnation, claim_stamp, claim_owner, claim_row_id,
assets_off, asset_gen, incarnation, serving_seq,
- host, kind, account, app, platform,
+ host, kind, account, app, platform, fleet_label,
` + fingerprintForwardInert + `
FROM routes ORDER BY rowid`)
if err != nil {
@@ -3894,12 +3909,12 @@ FROM routes ORDER BY rowid`)
var claim ClaimOwnership
var assetGen string
var status, socket, addr, version, channel, backing, tunnel, dbPath, region, fleetBox, addrs, health, gate, holdOp, importGate, rateLimit string
- var host, kind, account, app string
+ var host, kind, account, app, fleetLabel string
if err := rows.Scan(&rowid, &status, &socket, &addr, &version, &hibernate,
&channel, &backing, &tunnel, &dbPath, &region, &fleetBox, &addrs, &health, &gate, &holdOp, &importGate, &rateLimit,
&claim.ClaimIncarnation, &claim.ClaimStamp, &claim.ClaimOwner, &claim.ClaimRowID,
&assetsOff, &assetGen, &pair.Incarnation, &pair.ServingSeq,
- &host, &kind, &account, &app, &platform, &forwardInert); err != nil {
+ &host, &kind, &account, &app, &platform, &fleetLabel, &forwardInert); err != nil {
return "", err
}
fmt.Fprintf(h, "%d\x1f%s\x1f%s\x1f%s\x1f%s\x1f%d\x1f%s\x1f%s\x1f%s\x1f%s\x1f%s\x1f%s\x1f%s\x1f%s\x1f%s",
@@ -3923,6 +3938,13 @@ FROM routes ORDER BY rowid`)
if forwardInert == 0 {
fmt.Fprint(h, "\x1fforward_inert=0")
}
+ // A forward row's label makes its box authoritative at the edge
+ // (managed fleets 1b, rule 3: no fallback); a label set over a
+ // binding that already named the same box changes nothing else, so
+ // it is hashed itself. Folded only when set.
+ if fleetLabel != "" {
+ fmt.Fprintf(h, "\x1ffleet_label=%q", fleetLabel)
+ }
// Only a held row carries the extra field: an unheld registry's digest
// is byte-identical to the pre-hold_op encoding (switch-off contract),
// while a hold handed to another op with the status unchanged still
@@ -4204,6 +4226,7 @@ var snapshotWhenSetCols = map[string]bool{
"size": true,
"policy_expires_at": true,
"fleet_assigned": true,
+ "fleet_label": true,
}
// snapshotPairCols are the lifetime pair's columns (self-serve moves plan 1