carlos / platform Public

Fleet public routes Task 2: the forward kind and its exact persisted shape

A forward row is the hub's row for an app placed on a fleet (spec §4.2):
it runs nothing on the hub, so every column that describes a process,
upstream or lifecycle must be zero, and the registry has to enforce that
where the row is written.

- registry (forward.go): KindForward, Route.IsForward, Route.InertForward
  (each of the 50 forbidden fields compared one by one); ErrForwardRow and
  ErrHostHeld, appended to remoteErrors.
- forwardShape classes every persisted Route and ClaimOwnership field as
  declared, binding, observational or forbidden (the Global Constraints
  table verbatim). ForwardForbidden is an explicit {Field, Column, Type}
  literal (preflight 1.5), not derived: Route has no column tag and the
  base columns are in no list.
- PutForward: refuses a non-forward argument; one BEGIN IMMEDIATE
  transaction, SELECT kind (ErrHostHeld for a non-forward row, nothing
  written), then one INSERT ... ON CONFLICT DO UPDATE ... WHERE
  routes.kind = 'forward' naming every column. Declared columns from the
  call (Status "ready", Provisioned true), CreatedAt and the observational
  columns kept, FleetBox kept only while Region is unchanged, every
  ForwardForbidden column written zero.
- DeleteForward: DELETE ... WHERE host = ? AND kind = 'forward'.
- remote_dispatch.go: cases PutForward and DeleteForward.
- tests (forward_test.go): shape covers every field; ForwardForbidden
  matches PRAGMA table_info(routes) column by column and, with the kept
  columns, covers the whole table (claim columns included); InertForward
  per field; the exact shape; per-column sanitising; held host; delete
  leaves other rows; both calls over the remote transport.
- spec §7: Task 2's census card recorded (units in forward.go, the new
  var putForwardSQL unit, dispatchRemote sites, the registry schema
  change from ForwardColumn's field names).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev 62b93aafe51cfc598897c53d4ead18c81b512111 parent 08d71e3
5 files changed, +782 −9
  • docs/superpowers/specs/2026-10-29-fleet-public-routes-design.md +34 −8
  • internal/registry/forward.go +303 −0
  • internal/registry/forward_test.go +440 −0
  • internal/registry/remote.go +1 −1
  • internal/registry/remote_dispatch.go +4 −0

Intent

Human

<task-notification> <task-id>ab623264e419ef03a</task-id> <tool-use-id>toolu_01HrDd2D45wcqUjjhHHTE7Bc</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/ba9fa944-a429-4788-9b3c-f2b2f42617f3/tasks/ab623264e419ef03a.output</output-file> <status>completed</status> <summary>Agent "Implement Task 1: binding hole" finished</summary> <note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note> <result>**Status: DONE_WITH_CONCERNS** A fleet box can no longer write a binding that steers another fleet's host. The bindings pass now checks that a binding's key matches its body, and stamps a route with one conditional write (`SetFleetBoxIf`) that checks placement, kind and box membership together. The pass runs only on the hub. **Commit:** 08d71e39 on design-fleet-public-routes, from base 057cf7b6. Not pushed. Git printed the usual packed-refs.lock error, but the commit landed. **Tests:** Before the code existed, both packages failed to compile on `SetFleetBoxIf`, `hubArmed` and `bindingsAfterChecks` (preflight #18). All the brief's Step 3 tests now pass, as do the two edge e2e tests and the whole `internal/registry` package. Six mutations were each caught: - removing the key check - the old hostname-only UPDATE - removing the region clause - removing the active-box (EXISTS) clause - removing the sidecar clause - `hubArmed` without TrimSpace Build, vet, gofmt and the darwin/windows/linux-arm64 cross-builds are clean. `TestPlan14RootReadCensus` fails, which is expected until the overlay is proposed in Task 14. **Census card:** - `ReconcileFleetBindings`: body changed. - `dispatchRemote`: sites changed. - `SetFleetBox`: removed. - `SetFleetBoxIf`: new, in the new file `forward.go`. - Envelopes re-pinned: `internal/host` and `internal/registry`. The brief expected `instancesLoop` and `hubArmed` on the card too. Neither has a read site, so they only move the `internal/host` envelope. I wrote that into spec §7 along with the new file locations (preflight 4.8). **Concerns:** 1. The brief called `TestReconcileFleetBindingsNeverStampsSidecar` (`:677`) a negative case that needs no fleet membership. It also checks that the instance route gets stamped `box1`, and that part fails without a registered fleet and box. It now uses the fixture builder. 2. There are two fixture builders, one per package (`fleetBoundRow`, `seedFleetRoute`). Go can't share test helpers across packages without exporting them from production code. The host builder doesn't stamp the row, because the pass under test is the stamp. Each test asserts that stamp before any refusal check, and the stale test stamps box-2 first and asserts true. 3. `TestHubArmed` is in a new `internal/host/hub_test.go`, which wasn't in the brief's file list. 4. Test accounts are `domains.Sqid(7)` = `bah` and `Sqid(8)` = `baj` (preflight #1). The comment in `fleet_secrets_key_test.go` saying Sqid(7) is "bab" is wrong; I left that file alone. 5. Platform boxes that aren't the hub no longer run the bindings pass. This is what spec §4.5 asks for. 6. The end of spec §8 test 9 ("a request goes to B's box") is not covered here; preflight 4.6 puts it in Task 4. The full report, with the failing and passing output, the mutation table and the file list, is at /home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-fleet-public-routes/.superpowers/sdd/2026-10-30-fleet-public-routes/task-1-report.md</result> <usage><subagent_tokens>183107</subagent_tokens><tool_uses>67</tool_uses><duration_ms>922585</duration_ms></usage> </task-notification>

Human

<task-notification> <task-id>bmwwsbtsr</task-id> <tool-use-id>toolu_01QadTFCkVubkMZdGjKYF8Vk</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/ba9fa944-a429-4788-9b3c-f2b2f42617f3/tasks/bmwwsbtsr.output</output-file> <status>completed</status> <summary>Background command "Run the Astra task review for Task 1" completed (exit code 0)</summary> </task-notification>

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

diff --git a/docs/superpowers/specs/2026-10-29-fleet-public-routes-design.md b/docs/superpowers/specs/2026-10-29-fleet-public-routes-design.md
index 57c192302..5c9c531d7 100644
--- a/docs/superpowers/specs/2026-10-29-fleet-public-routes-design.md
+++ b/docs/superpowers/specs/2026-10-29-fleet-public-routes-design.md
@@ -811,15 +811,13 @@ Envelopes re-pinned (seven): the root package `.`, `internal/registry`,
Units, by file (N = new, R = removed, otherwise a changed body or sites):
-- `internal/registry/registry.go`: `Route.IsForward` (N, reads `Kind`);
- `Route.InertForward` (N, reads every forbidden column of §4.2);
- `Registry.PutForward` (N); `Registry.DeleteForward` (N);
- `Registry.SetFleetBox` (R); and every
+- `internal/registry/registry.go`: `Registry.SetFleetBox` (R); and every
writer that gains `kind <> 'forward'` and reads a `Route` field in its
body: `Upsert`, `UpsertUnlessRootfs`, `DeleteIfUnchanged`, and those of
the §4.2 setter list whose bodies select a `Route` field. A setter whose
- body has no read site changes only the envelope. `KindForward` (a
- constant) is envelope-only.
+ body has no read site changes only the envelope. (`Route.IsForward`,
+ `Route.InertForward`, `Registry.PutForward` and `Registry.DeleteForward`
+ are in `forward.go`, below.)
- The writer guard's other files **(R3-3)**, each declaration below
changed: `internal/registry/registry.go` also `upsertRoute`, `Delete`,
`InstallLifetimeIf`, `SetHold`, `SetHoldIf`, `SetHoldIfSeq`, `HandHold`,
@@ -843,11 +841,39 @@ Units, by file (N = new, R = removed, otherwise a changed body or sites):
(N, Task 1). Task 1's card shows it with `+file:Exec`,
`+registry:Changed`, `+registry:remote` x2, `+registry:sql`,
`+whole:remoteClient` x2: the remote-or-local shape every narrow setter
- has.
+ has. Task 2 adds, all N:
+ - `Route.IsForward` (`+registry:Kind`);
+ - `Route.InertForward` (one `+registry:<field>` site for each of the 50
+ forbidden fields of §4.2, nothing else);
+ - `Registry.PutForward` (`+file:Exec`, `+file:QueryRow`, the declared
+ fields it copies from its argument: `+registry:Account`, `App`,
+ `Channel`, `RateLimit`, `Region`, `Slug`; `+registry:Host` x3,
+ `+registry:Kind`, `+registry:remote` x2, `+whole:Route` x3,
+ `+whole:remoteClient` x2; no `+registry:sql`, as it writes through
+ `inImmediateTx`'s transaction);
+ - `Registry.DeleteForward` (`+file:Exec`, `+registry:Changed`,
+ `+registry:remote` x2, `+registry:sql`, `+whole:remoteClient` x2);
+ - `var putForwardSQL` (`+registry:Column`, `+registry:Type`,
+ `+whole:ForwardColumn`): PutForward's statement, whose conflict arm is
+ built once from `ForwardForbidden`, so it reads that literal's fields.
+ Not foreseen by rev 4; a unit because it is a top-level declaration
+ with read sites. It reads only a package literal.
+
+ `KindForward`, `ErrForwardRow`, `ErrHostHeld`, `forwardShape`,
+ `ForwardForbidden` and `remote.go`'s `remoteErrors` (the two new
+ sentinels appended) have no read site and move only the
+ `internal/registry` envelope. The new struct `ForwardColumn{Field,
+ Column, Type}` (preflight 1.5: an explicit literal, not derived) adds
+ struct field names to the registry package, so Task 2's card also shows
+ `changed registry schema`, closed by re-pinning the schema at Task 14.
- `internal/registry/remote_dispatch.go`: `Registry.dispatchRemote` (the
three new cases, `SetFleetBox` gone). Task 1's card shows it as `sites`
(`+registry:Changed`, `+registry:Fleet`: the `SetFleetBoxIf` case reads
- the request's `Fleet` and answers `Changed`).
+ the request's `Fleet` and answers `Changed`). Task 2's two cases bring the
+ card to `+registry:Changed` x2, `+registry:Fleet`, `+registry:Host`,
+ `+registry:TValue`, `+whole:Route`: `PutForward` reads the request's
+ `TValue` (a whole `Route`), `DeleteForward` reads its `Host` and answers
+ `Changed`.
- `internal/provision/reconcile.go`: `Reconcile` (forward phase, trash-only
prefetch, `retirable` guard); the forward phase's own helpers (N), named
by the plan; `ReconcileConfig` (the `FleetOwners` field; envelope unless
diff --git a/internal/registry/forward.go b/internal/registry/forward.go
index 4d8838fa3..b83e85f0d 100644
--- a/internal/registry/forward.go
+++ b/internal/registry/forward.go
@@ -1,5 +1,13 @@
package registry
+import (
+ "database/sql"
+ "errors"
+ "fmt"
+ "strings"
+ "time"
+)
+
// 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
@@ -38,3 +46,298 @@ UPDATE routes SET fleet_box = ?
n, err := res.RowsAffected()
return n > 0, err
}
+
+// KindForward is the kind of a forward row (fleet public routes spec §4.2):
+// the hub's row for an app placed on a fleet, which the hub serves only by
+// forwarding over the fleet's tunnel. It runs nothing on the hub, so every
+// column that describes a process, an upstream or a lifecycle is zero
+// (ForwardForbidden). A selector that names a kind positively skips it.
+const KindForward = "forward"
+
+// IsForward reports whether t is a forward row (Kind KindForward). A method,
+// as IsSidecar is, so a typo cannot quietly admit or skip one.
+func (t Route) IsForward() bool { return t.Kind == KindForward }
+
+// ErrForwardRow is the answer of every routes writer other than the forward
+// row's own (PutForward, DeleteForward, SetFleetBoxIf, SetDNSStatus,
+// SetCertExpiresAt) when it is handed a forward row or reaches one (spec
+// §4.2, the writer rule). One of remoteErrors.
+var ErrForwardRow = errors.New("registry: the host is 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.
+var ErrHostHeld = errors.New("registry: another row holds the host")
+
+// forwardShape classes every persisted field of Route, the embedded
+// ClaimOwnership's included, for a forward row (spec §4.2; the plan's Global
+// Constraints table verbatim):
+//
+// - 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;
+// - 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).
+//
+// WakeIncarnation is not persisted and is not listed. A field added to Route
+// fails TestForwardShapeClassesEveryField until it is classed here.
+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",
+
+ "FleetBox": "binding",
+
+ "DNSStatus": "observational", "DNSCheckedAt": "observational", "CertExpiresAt": "observational",
+
+ "Socket": "forbidden", "Addr": "forbidden", "Addrs": "forbidden", "Health": "forbidden",
+ "HoldOp": "forbidden", "Incarnation": "forbidden", "ServingSeq": "forbidden",
+ "SeedSource": "forbidden", "ImportGate": "forbidden", "AssetsOff": "forbidden",
+ "AssetGen": "forbidden", "LastError": "forbidden", "DBPath": "forbidden",
+ "Version": "forbidden", "PrevVersion": "forbidden", "GoodVersion": "forbidden",
+ "GoodDigest": "forbidden", "GoodDemand": "forbidden", "ServingVersion": "forbidden",
+ "Pool": "forbidden", "Environment": "forbidden", "Tunnel": "forbidden",
+ "Caps": "forbidden", "Hibernate": "forbidden", "HA": "forbidden",
+ "Runtime": "forbidden", "Gate": "forbidden", "Canary": "forbidden",
+ "Replication": "forbidden", "NextDue": "forbidden", "StatusNamed": "forbidden",
+ "Backing": "forbidden", "Unit": "forbidden", "Platform": "forbidden",
+ "Seed": "forbidden", "Args": "forbidden", "IdleSeconds": "forbidden",
+ "MaxRunSeconds": "forbidden", "Steering": "forbidden", "UpdateSettings": "forbidden",
+ "EgressAllow": "forbidden", "Size": "forbidden", "PolicyExpiresAt": "forbidden",
+ "BuildState": "forbidden", "Replicas": "forbidden", "Replica": "forbidden",
+ "ClaimIncarnation": "forbidden", "ClaimStamp": "forbidden", "ClaimOwner": "forbidden",
+ "ClaimRowID": "forbidden",
+}
+
+// ForwardColumn is one forbidden field of a forward row: the Route field, its
+// routes column and that column's SQL type ("TEXT" or "INTEGER").
+type ForwardColumn struct{ Field, Column, Type string }
+
+// ForwardForbidden is the forbidden class of forwardShape with each field's
+// column and type, written out rather than derived: Route carries no
+// field-to-column tag, and the base columns (socket, version, db_path...) are
+// in no list a derivation could read. TestForwardForbiddenMatchesTheTable
+// checks every entry against PRAGMA table_info(routes) and checks that the
+// entries and the kept columns cover the whole table. PutForward writes zero
+// to exactly these columns; tests elsewhere corrupt a forward row through
+// them ('x' for TEXT, 1 for INTEGER).
+var ForwardForbidden = []ForwardColumn{
+ {"Socket", "socket", "TEXT"},
+ {"Addr", "addr", "TEXT"},
+ {"Addrs", "addrs", "TEXT"},
+ {"Health", "health", "TEXT"},
+ {"HoldOp", "hold_op", "TEXT"},
+ {"Incarnation", "incarnation", "INTEGER"},
+ {"ServingSeq", "serving_seq", "INTEGER"},
+ {"SeedSource", "seed_source", "TEXT"},
+ {"ImportGate", "import_gate", "TEXT"},
+ {"AssetsOff", "assets_off", "INTEGER"},
+ {"AssetGen", "asset_gen", "TEXT"},
+ {"LastError", "last_error", "TEXT"},
+ {"DBPath", "db_path", "TEXT"},
+ {"Version", "version", "TEXT"},
+ {"PrevVersion", "prev_version", "TEXT"},
+ {"GoodVersion", "good_version", "TEXT"},
+ {"GoodDigest", "good_digest", "TEXT"},
+ {"GoodDemand", "good_demand", "TEXT"},
+ {"ServingVersion", "serving_version", "TEXT"},
+ {"Pool", "pool", "TEXT"},
+ {"Environment", "environment", "TEXT"},
+ {"Tunnel", "tunnel", "TEXT"},
+ {"Caps", "caps", "TEXT"},
+ {"Hibernate", "hibernate", "INTEGER"},
+ {"HA", "ha", "INTEGER"},
+ {"Runtime", "runtime", "TEXT"},
+ {"Gate", "gate", "TEXT"},
+ {"Canary", "canary", "INTEGER"},
+ {"Replication", "replication", "TEXT"},
+ {"NextDue", "next_due", "INTEGER"},
+ {"StatusNamed", "status_named", "INTEGER"},
+ {"Backing", "backing", "TEXT"},
+ {"Unit", "unit", "TEXT"},
+ {"Platform", "platform", "INTEGER"},
+ {"Seed", "seed", "TEXT"},
+ {"Args", "args", "TEXT"},
+ {"IdleSeconds", "idle_seconds", "INTEGER"},
+ {"MaxRunSeconds", "max_run_seconds", "INTEGER"},
+ {"Steering", "steering", "TEXT"},
+ {"UpdateSettings", "update_settings", "TEXT"},
+ {"EgressAllow", "egress_allow", "TEXT"},
+ {"Size", "size", "TEXT"},
+ {"PolicyExpiresAt", "policy_expires_at", "TEXT"},
+ {"BuildState", "build_state", "TEXT"},
+ {"Replicas", "replicas", "TEXT"},
+ {"Replica", "replica", "INTEGER"},
+ {"ClaimIncarnation", "claim_incarnation", "TEXT"},
+ {"ClaimStamp", "claim_stamp", "INTEGER"},
+ {"ClaimOwner", "claim_owner", "TEXT"},
+ {"ClaimRowID", "claim_row_id", "TEXT"},
+}
+
+// InertForward reports whether t is a forward row with every forbidden field
+// zero, each compared one by one (spec §4.2). Every reader that admits a
+// forward row admits only an inert one; one that is not inert is served by
+// nobody and published by nobody.
+func (t Route) InertForward() bool {
+ return t.IsForward() &&
+ t.Socket == "" &&
+ t.Addr == "" &&
+ t.Addrs == "" &&
+ t.Health == "" &&
+ t.HoldOp == "" &&
+ t.Incarnation == 0 &&
+ t.ServingSeq == 0 &&
+ t.SeedSource == "" &&
+ t.ImportGate == "" &&
+ !t.AssetsOff &&
+ t.AssetGen == "" &&
+ t.LastError == "" &&
+ t.DBPath == "" &&
+ t.Version == "" &&
+ t.PrevVersion == "" &&
+ t.GoodVersion == "" &&
+ t.GoodDigest == "" &&
+ t.GoodDemand == "" &&
+ t.ServingVersion == "" &&
+ t.Pool == "" &&
+ t.Environment == "" &&
+ t.Tunnel == "" &&
+ t.Caps == "" &&
+ !t.Hibernate &&
+ !t.HA &&
+ t.Runtime == "" &&
+ t.Gate == "" &&
+ !t.Canary &&
+ t.Replication == "" &&
+ t.NextDue == 0 &&
+ !t.StatusNamed &&
+ t.Backing == "" &&
+ t.Unit == "" &&
+ !t.Platform &&
+ t.Seed == "" &&
+ t.Args == "" &&
+ t.IdleSeconds == 0 &&
+ t.MaxRunSeconds == 0 &&
+ t.Steering == "" &&
+ t.UpdateSettings == "" &&
+ t.EgressAllow == "" &&
+ t.Size == "" &&
+ t.PolicyExpiresAt == "" &&
+ t.BuildState == "" &&
+ t.Replicas == "" &&
+ !t.Replica &&
+ t.ClaimIncarnation == "" &&
+ t.ClaimStamp == 0 &&
+ t.ClaimOwner == "" &&
+ t.ClaimRowID == ""
+}
+
+// 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
+// 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",
+ }
+ for _, c := range ForwardForbidden {
+ zero := "''"
+ if c.Type == "INTEGER" {
+ zero = "0"
+ }
+ set = append(set, c.Column+" = "+zero)
+ }
+ return `INSERT INTO routes (` + routeCols + `)
+VALUES (` + placeholders(routeColCount) + `)
+ON CONFLICT(host) DO UPDATE SET
+ ` + strings.Join(set, ",\n ") + `
+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
+// 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.
+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)
+ }
+ if r.remote != nil {
+ _, err := r.remote.call(nil, remoteRequest{Method: "PutForward", TValue: rt}, nil)
+ return err
+ }
+
+ w := Route{
+ Host: rt.Host,
+ Kind: KindForward,
+ Slug: rt.Slug,
+ App: rt.App,
+ Account: rt.Account,
+ Region: rt.Region,
+ Channel: rt.Channel,
+ RateLimit: rt.RateLimit,
+ Status: "ready",
+ Provisioned: true,
+ CreatedAt: time.Now().Unix(),
+ }
+ return r.inImmediateTx(func(tx txer) error {
+ var kind string
+ err := tx.QueryRow(`SELECT kind FROM routes WHERE host = ?`, w.Host).Scan(&kind)
+ switch {
+ case errors.Is(err, sql.ErrNoRows):
+ case err != nil:
+ return err
+ case kind != KindForward:
+ return ErrHostHeld
+ }
+ res, err := tx.Exec(putForwardSQL, routeArgs(w)...)
+ if err != nil {
+ return err
+ }
+ n, err := res.RowsAffected()
+ if err != nil {
+ return err
+ }
+ if n != 1 {
+ return ErrHostHeld
+ }
+ return nil
+ })
+}
+
+// DeleteForward deletes host's row only while it is a forward row, in the
+// same statement, and reports whether it deleted one. Any other row at the
+// host, or none, is false with no error.
+func (r *Registry) DeleteForward(host string) (bool, error) {
+ if r.remote != nil {
+ out, err := r.remote.call(nil, remoteRequest{Method: "DeleteForward", Host: host}, nil)
+ return out.Changed, err
+ }
+
+ res, err := r.sql.Exec(`DELETE FROM routes WHERE host = ? AND kind = 'forward'`, host)
+ if err != nil {
+ return false, err
+ }
+ n, err := res.RowsAffected()
+ return n > 0, err
+}
diff --git a/internal/registry/forward_test.go b/internal/registry/forward_test.go
new file mode 100644
index 000000000..20d17656a
--- /dev/null
+++ b/internal/registry/forward_test.go
@@ -0,0 +1,440 @@
+package registry
+
+import (
+ "errors"
+ "reflect"
+ "sort"
+ "strings"
+ "testing"
+)
+
+// forwardFields is every persisted field of Route, the embedded
+// ClaimOwnership's included, by name: the fields a forward row's shape must
+// class (spec §4.2). A field tagged json:"-" is not persisted.
+func forwardFields(t *testing.T) []string {
+ t.Helper()
+ var out []string
+ var walk func(rt reflect.Type)
+ walk = func(rt reflect.Type) {
+ for i := 0; i < rt.NumField(); i++ {
+ f := rt.Field(i)
+ if f.Anonymous {
+ walk(f.Type)
+ continue
+ }
+ if f.Tag.Get("json") == "-" {
+ continue
+ }
+ out = append(out, f.Name)
+ }
+ }
+ walk(reflect.TypeOf(Route{}))
+ return out
+}
+
+// setNonZero sets the named field of rt to a non-zero value of its type.
+func setNonZero(t *testing.T, rt *Route, field string) {
+ t.Helper()
+ v := reflect.ValueOf(rt).Elem().FieldByName(field)
+ if !v.IsValid() {
+ t.Fatalf("Route has no field %s", field)
+ }
+ switch v.Kind() {
+ case reflect.String:
+ v.SetString("x")
+ case reflect.Bool:
+ v.SetBool(true)
+ case reflect.Int, reflect.Int64:
+ v.SetInt(1)
+ case reflect.Uint64:
+ v.SetUint(1)
+ default:
+ t.Fatalf("field %s: no non-zero value for kind %s", field, v.Kind())
+ }
+}
+
+// validForward is a forward row as the forward phase would declare it.
+func validForward(host, fleet string) Route {
+ return Route{
+ Host: host,
+ Kind: KindForward,
+ Slug: "shop",
+ App: "shop",
+ Account: "bah",
+ Region: PlacementTarget(fleet),
+ Channel: "beta",
+ RateLimit: `{"rps":5}`,
+ Status: "ready",
+ Provisioned: true,
+ }
+}
+
+// TestForwardShapeClassesEveryField: every persisted field of Route is in
+// exactly one class, and every class entry is a field (spec §8 test 1).
+func TestForwardShapeClassesEveryField(t *testing.T) {
+ fields := forwardFields(t)
+ seen := map[string]bool{}
+ for _, f := range fields {
+ seen[f] = true
+ class, ok := forwardShape[f]
+ if !ok {
+ t.Errorf("Route field %s is in no forward-row class (forwardShape)", f)
+ continue
+ }
+ switch class {
+ case "declared", "binding", "observational", "forbidden":
+ default:
+ t.Errorf("forwardShape[%s] = %q, not a class", f, class)
+ }
+ }
+ for f := range forwardShape {
+ if !seen[f] {
+ t.Errorf("forwardShape names %s, which is not a persisted Route field", f)
+ }
+ }
+ if _, ok := forwardShape["WakeIncarnation"]; ok {
+ t.Error("forwardShape lists WakeIncarnation, which is not persisted")
+ }
+}
+
+// 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.
+func TestForwardForbiddenMatchesTheTable(t *testing.T) {
+ reg := openTestRegistry(t)
+ rows, err := reg.sql.Query(`SELECT name, type FROM pragma_table_info('routes')`)
+ if err != nil {
+ t.Fatal(err)
+ }
+ table := map[string]string{}
+ for rows.Next() {
+ var name, typ string
+ if err := rows.Scan(&name, &typ); err != nil {
+ t.Fatal(err)
+ }
+ table[name] = typ
+ }
+ if err := rows.Err(); err != nil {
+ t.Fatal(err)
+ }
+ rows.Close()
+ for _, c := range []string{"claim_incarnation", "claim_stamp", "claim_owner", "claim_row_id"} {
+ if _, ok := table[c]; !ok {
+ t.Fatalf("routes has no %s column: the ClaimOwnership columns are not where this test expects", c)
+ }
+ }
+
+ var forbidden []string
+ for f, class := range forwardShape {
+ if class == "forbidden" {
+ forbidden = append(forbidden, f)
+ }
+ }
+ sort.Strings(forbidden)
+ var listed []string
+ byField := map[string]int{}
+ columns := map[string]string{}
+ for _, c := range ForwardForbidden {
+ listed = append(listed, c.Field)
+ byField[c.Field]++
+ if prev, ok := columns[c.Column]; ok {
+ t.Errorf("column %s is listed for both %s and %s", c.Column, prev, c.Field)
+ }
+ columns[c.Column] = c.Field
+ typ, ok := table[c.Column]
+ if !ok {
+ t.Errorf("ForwardForbidden %s: routes has no column %s", c.Field, c.Column)
+ continue
+ }
+ if typ != c.Type {
+ t.Errorf("ForwardForbidden %s: column %s is %s in routes, listed %s", c.Field, c.Column, typ, c.Type)
+ }
+ if forwardShape[c.Field] != "forbidden" {
+ t.Errorf("ForwardForbidden lists %s, whose class is %q", c.Field, forwardShape[c.Field])
+ }
+ }
+ for f, n := range byField {
+ if n != 1 {
+ t.Errorf("ForwardForbidden lists %s %d times", f, n)
+ }
+ }
+ sort.Strings(listed)
+ if !reflect.DeepEqual(listed, forbidden) {
+ t.Errorf("ForwardForbidden fields = %v\nforbidden class = %v", listed, forbidden)
+ }
+
+ for f, col := range forwardKeptColumns {
+ 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)
+ }
+ 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)
+ }
+ }
+ for col := range table {
+ if _, ok := columns[col]; !ok {
+ t.Errorf("routes column %s is classed by no field: class it in forwardShape and ForwardForbidden", col)
+ }
+ }
+ for col, f := range columns {
+ if _, ok := table[col]; !ok {
+ t.Errorf("field %s names column %s, which routes does not have", f, col)
+ }
+ }
+}
+
+// TestInertForwardChecksEachForbiddenField: one forbidden field set, and
+// only that one, makes a forward row not inert.
+func TestInertForwardChecksEachForbiddenField(t *testing.T) {
+ ok := validForward("shop.example.com", "home")
+ ok.FleetBox, ok.DNSStatus, ok.DNSCheckedAt, ok.CertExpiresAt, ok.CreatedAt = "box-1", "pointing", 7, 9, 11
+ if !ok.InertForward() {
+ t.Fatalf("a valid forward row is not inert: %+v", ok)
+ }
+ n := 0
+ for f, class := range forwardShape {
+ if class != "forbidden" {
+ continue
+ }
+ n++
+ rt := ok
+ setNonZero(t, &rt, f)
+ if rt.InertForward() {
+ t.Errorf("InertForward() true with %s set", f)
+ }
+ }
+ if n != len(ForwardForbidden) || n == 0 {
+ t.Fatalf("checked %d forbidden fields, ForwardForbidden has %d", n, len(ForwardForbidden))
+ }
+ hand := ok
+ hand.Kind = "instance"
+ if hand.IsForward() || hand.InertForward() {
+ t.Error("an instance row reads as a forward row")
+ }
+}
+
+// TestPutForwardWritesTheExactShape: declared columns come from the call,
+// observational ones and CreatedAt are kept, FleetBox is kept while Region is
+// unchanged and cleared when it changes, and every forbidden column is zero
+// whatever the stored row or the call carried.
+func TestPutForwardWritesTheExactShape(t *testing.T) {
+ reg := openTestRegistry(t)
+ const host = "shop.example.com"
+ if err := reg.PutForward(validForward(host, "home")); err != nil {
+ t.Fatal(err)
+ }
+ first, err := reg.Get(host)
+ if err != nil || first == nil {
+ t.Fatalf("Get = %v, %v", first, err)
+ }
+ if first.CreatedAt == 0 {
+ 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 {
+ 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 {
+ t.Fatalf("raw SQL did not persist: %+v, %v", stored, err)
+ }
+
+ // The call carries every forbidden field, a binding, observations, a
+ // status and a provisioned mark of its own: none of them is written.
+ in := validForward(host, "home")
+ in.Status, in.Provisioned = "failed", false
+ in.Channel, in.RateLimit, in.Slug = "stable", `{"rps":9}`, "shop2"
+ in.FleetBox, in.DNSStatus, in.DNSCheckedAt, in.CertExpiresAt, in.CreatedAt = "box-9", "elsewhere", 99, 99, 99
+ for _, c := range ForwardForbidden {
+ setNonZero(t, &in, c.Field)
+ }
+ if err := reg.PutForward(in); err != nil {
+ t.Fatal(err)
+ }
+ got, err := reg.Get(host)
+ if err != nil || got == nil {
+ t.Fatalf("Get = %v, %v", got, err)
+ }
+ want := Route{
+ 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,
+ }
+ if *got != want {
+ t.Fatalf("after PutForward:\n got %+v\nwant %+v", *got, want)
+ }
+ if !got.InertForward() {
+ t.Fatalf("PutForward left a row that is not inert: %+v", *got)
+ }
+
+ moved := validForward(host, "away")
+ if err := reg.PutForward(moved); err != nil {
+ t.Fatal(err)
+ }
+ got, err = reg.Get(host)
+ if err != nil || got == nil {
+ t.Fatalf("Get = %v, %v", got, err)
+ }
+ 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 {
+ t.Fatalf("after the move: %+v", *got)
+ }
+}
+
+// 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
+// row of its own, so one miss does not leak into the next.
+func TestPutForwardSanitisesEachForbiddenColumn(t *testing.T) {
+ reg := openTestRegistry(t)
+ for _, c := range ForwardForbidden {
+ host := strings.ReplaceAll(c.Column, "_", "-") + ".example.com"
+ if err := reg.PutForward(validForward(host, "home")); err != nil {
+ t.Fatalf("%s: %v", c.Field, err)
+ }
+ var v any = "x"
+ if c.Type == "INTEGER" {
+ v = 1
+ }
+ if _, err := reg.sql.Exec(`UPDATE routes SET `+c.Column+` = ? WHERE host = ?`, v, host); err != nil {
+ t.Fatalf("%s: %v", c.Column, err)
+ }
+ before, err := reg.Get(host)
+ if err != nil || before == nil {
+ t.Fatalf("%s: Get = %v, %v", c.Column, before, err)
+ }
+ if reflect.ValueOf(*before).FieldByName(c.Field).IsZero() {
+ t.Fatalf("column %s set by raw SQL, but field %s reads zero: the entry pairs the wrong column", c.Column, c.Field)
+ }
+ if before.InertForward() {
+ t.Fatalf("%s set: the row still reads inert", c.Field)
+ }
+ if err := reg.PutForward(validForward(host, "home")); err != nil {
+ t.Fatalf("%s: PutForward: %v", c.Field, err)
+ }
+ after, err := reg.Get(host)
+ if err != nil || after == nil {
+ t.Fatalf("%s: Get = %v, %v", c.Column, after, err)
+ }
+ if !reflect.ValueOf(*after).FieldByName(c.Field).IsZero() {
+ t.Errorf("PutForward kept forbidden %s (%s) = %v", c.Field, c.Column, reflect.ValueOf(*after).FieldByName(c.Field))
+ }
+ if !after.InertForward() {
+ t.Errorf("%s: row not inert after PutForward: %+v", c.Field, *after)
+ }
+ }
+}
+
+// TestPutForwardRefusesAHeldHost: a non-forward row at the host is another
+// writer's; PutForward returns ErrHostHeld and changes nothing. A call that
+// is not a forward row is refused and writes nothing.
+func TestPutForwardRefusesAHeldHost(t *testing.T) {
+ reg := openTestRegistry(t)
+ const host = "shop.example.com"
+ if err := reg.Upsert(Route{Host: host, Kind: "instance", Status: "ready", App: "shop", Account: "bah",
+ Socket: "/run/carlos/instances/shop.example.com/app.sock", Region: PlacementTarget("home")}); err != nil {
+ t.Fatal(err)
+ }
+ before, err := reg.Get(host)
+ if err != nil || before == nil {
+ t.Fatalf("Get = %v, %v", before, err)
+ }
+ err = reg.PutForward(validForward(host, "home"))
+ if !errors.Is(err, ErrHostHeld) {
+ t.Fatalf("PutForward over an instance row = %v, want ErrHostHeld", err)
+ }
+ after, err := reg.Get(host)
+ if err != nil || after == nil || *after != *before {
+ t.Fatalf("the instance row changed:\nbefore %+v\nafter %+v (%v)", *before, after, err)
+ }
+
+ notForward := validForward("other.example.com", "home")
+ notForward.Kind = "instance"
+ if err := reg.PutForward(notForward); err == nil {
+ t.Fatal("PutForward accepted an instance row")
+ }
+ if got, err := reg.Get("other.example.com"); err != nil || got != nil {
+ t.Fatalf("a refused PutForward wrote a row: %+v, %v", got, err)
+ }
+}
+
+// TestDeleteForwardLeavesOtherRows: DeleteForward deletes a forward row and
+// nothing else.
+func TestDeleteForwardLeavesOtherRows(t *testing.T) {
+ reg := openTestRegistry(t)
+ const hand, fwd = "hand.example.com", "shop.example.com"
+ if err := reg.Upsert(Route{Host: hand, Kind: "instance", Status: "ready", Region: PlacementTarget("home")}); err != nil {
+ t.Fatal(err)
+ }
+ if err := reg.PutForward(validForward(fwd, "home")); err != nil {
+ t.Fatal(err)
+ }
+ deleted, err := reg.DeleteForward(hand)
+ if err != nil || deleted {
+ t.Fatalf("DeleteForward(hand row) = %v, %v; want false, nil", deleted, err)
+ }
+ if got, err := reg.Get(hand); err != nil || got == nil {
+ t.Fatalf("the hand row is gone: %v, %v", got, err)
+ }
+ deleted, err = reg.DeleteForward(fwd)
+ if err != nil || !deleted {
+ t.Fatalf("DeleteForward(forward row) = %v, %v; want true, nil", deleted, err)
+ }
+ if got, err := reg.Get(fwd); err != nil || got != nil {
+ t.Fatalf("the forward row is still there: %v, %v", got, err)
+ }
+ if deleted, err := reg.DeleteForward("none.example.com"); err != nil || deleted {
+ t.Fatalf("DeleteForward(unknown) = %v, %v; want false, nil", deleted, err)
+ }
+}
+
+// TestForwardCallsOverRemote: both writers cross the remote transport, and
+// ErrHostHeld survives it.
+func TestForwardCallsOverRemote(t *testing.T) {
+ reg, _ := remoteTestRegistry(t)
+ const host, held = "shop.example.com", "held.example.com"
+ if err := reg.PutForward(validForward(host, "home")); err != nil {
+ t.Fatal(err)
+ }
+ got, err := reg.Get(host)
+ if err != nil || got == nil || !got.InertForward() || got.Region != PlacementTarget("home") {
+ t.Fatalf("remote PutForward: %+v, %v", got, err)
+ }
+ if err := reg.Upsert(Route{Host: held, Kind: "instance", Status: "ready"}); err != nil {
+ t.Fatal(err)
+ }
+ if err := reg.PutForward(validForward(held, "home")); !errors.Is(err, ErrHostHeld) {
+ t.Fatalf("remote PutForward over an instance row = %v, want ErrHostHeld", err)
+ }
+ if deleted, err := reg.DeleteForward(held); err != nil || deleted {
+ t.Fatalf("remote DeleteForward(instance row) = %v, %v", deleted, err)
+ }
+ if deleted, err := reg.DeleteForward(host); err != nil || !deleted {
+ t.Fatalf("remote DeleteForward(forward row) = %v, %v", deleted, err)
+ }
+ if got, err := reg.Get(host); err != nil || got != nil {
+ t.Fatalf("remote DeleteForward left %+v, %v", got, err)
+ }
+}
diff --git a/internal/registry/remote.go b/internal/registry/remote.go
index 8447c3b6a..380b91071 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}
+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}
func responseError(out remoteResponse) error {
if !out.Failed {
diff --git a/internal/registry/remote_dispatch.go b/internal/registry/remote_dispatch.go
index 39ad6b00c..50cf3cebe 100644
--- a/internal/registry/remote_dispatch.go
+++ b/internal/registry/remote_dispatch.go
@@ -292,6 +292,10 @@ func (r *Registry) dispatchRemote(ctx context.Context, q remoteRequest, callback
err = r.SetTunnel(q.Host, q.Tunnel)
case "SetFleetBoxIf":
out.Changed, err = r.SetFleetBoxIf(q.Host, q.Fleet, q.Label)
+ case "PutForward":
+ err = r.PutForward(q.TValue)
+ case "DeleteForward":
+ out.Changed, err = r.DeleteForward(q.Host)
case "SetPlacement":
err = r.SetPlacement(q.Host, q.Target)
case "SetEnvironments":