carlos / platform Public

Fleet public routes Task 5: a forward row's rate limit, plan throttle and upgrade tracking apply once, at the hub

rateAdmit, planThrottleOf, trackUpgrade and planThrottleFor admit a
forward row as well as an instance (spec §4.8). The fleet edge keeps
exempting tunneled requests. Spec §7 records Task 5's census card.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev 768dcb2560acef8c8ed508da44a77cfcf3b2f997 parent 1eb0ec0
6 files changed, +306 −8
  • docs/superpowers/specs/2026-10-29-fleet-public-routes-design.md +8 −0
  • internal/edge/fleetforward_policy_test.go +259 −0
  • internal/edge/planthrottle.go +6 −3
  • internal/edge/ratelimit.go +4 −2
  • internal/host/plans_pass.go +4 −3
  • internal/host/plans_pass_test.go +25 −0

CI failed — run details

Intent

Human

<task-notification> <task-id>aa8076ab7f4edf357</task-id> <tool-use-id>toolu_011ZsYn1RNZeYLyGbDYGfwDn</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/ba9fa944-a429-4788-9b3c-f2b2f42617f3/tasks/aa8076ab7f4edf357.output</output-file> <status>completed</status> <summary>Agent "Implement Task 3: writer guard" 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>Both review findings are fixed in one commit, 1eb0ec0c, on top of 506cce42, not pushed. Status: DONE. **Tests:** the CLI and copy tests, the related `add`, `route` and `remove` tests, and `TestPlan9B8RecordWriteCensus` pass. Build, vet, gofmt and the darwin, windows and linux/arm64 cross-builds are clean. Each new test failed before the change. 1. **FPR-C01 now comes first on a forward host.** - `carlos add` reads the row as soon as it knows the host and refuses a forward one before every other check. That includes the regional-domain check, which reads a stored claim, and the flag checks. - `carlos route` opens the registry as soon as `--host` or `--app` is settled and refuses a forward target before any flag, value or row check. - An `--app` batch gathers every row it selects first and refuses the whole batch if any is forward. This happens before the "skipped" messages for platform-minted rows and before the reserved-suffix check. - The new test cases pair a forward host with an input another check would refuse in its own words. For each, the output must be FPR-C01 with none of the other check's words and no "skipped" line. They cover: - `add` with a bad `-backing`, with `-kind sidecar`, with `-unit` plus `-socket`, and under a stored regional claim, with a control showing a claimed ordinary host does get the regional refusal; - `route` with an invalid channel, `-environment default`, and `-grant` plus `-revoke`; - two `--app` batches, one including a platform-minted row and one with an invalid channel. 2. **A forward row created mid-write now also gets FPR-C01.** The write errors of `carlos route --grant/--revoke`, `--hibernate`, `--backing`, `--unit` and `--replication` now go through the same mapping as the other verbs. The new `TestRouteSingleAxisWriteRaceAnswersC01` runs each of the five in a child process: it reads an ordinary row, swaps a forward row in, then runs the command on the row it read. Before the fix, all five printed the bare registry error. Four new mutations were each caught: removing the early `route` check, removing the early `add` check, removing the mapping from `--hibernate`, and skipping the `--app` branch of the early check. **Census:** - The record-write census flagged `runRoute` and `runRouteHibernate`; both are re-pinned. `runAdd` is not pinned there. - On the census card, the five single-axis `route` commands now show as changed and `refuseForwardTargets` is a new unit. - Spec §7 is updated to match. **Behaviour change for review:** `carlos add` now opens the registry before its flag checks, and `carlos route` does so right after deciding `--host` or `--app`. A bad flag on a box with no registry yet now creates the registry file before refusing. If the registry cannot be opened, that error now shows before any flag error. The fix report is appended to `.superpowers/sdd/2026-10-30-fleet-public-routes/task-3-report.md`.</result> <usage><subagent_tokens>465162</subagent_tokens><tool_uses>22</tool_uses><duration_ms>400154</duration_ms></usage> </task-notification>

Human

<task-notification> <task-id>bt8w2bez5</task-id> <tool-use-id>toolu_015d3HduSYeE1x5PdHKcZnyz</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/ba9fa944-a429-4788-9b3c-f2b2f42617f3/tasks/bt8w2bez5.output</output-file> <status>completed</status> <summary>Background command "Run the scoped Astra re-review of the C01 fix" completed (exit code 0)</summary> </task-notification>

Attributed to this commit: 20.8 g CO₂e (2,586,032 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 6e1d0dde3..2786fd7d5 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
@@ -1009,6 +1009,14 @@ Units, by file (N = new, R = removed, otherwise a changed body or sites):
the edge's own map, no registry field, and are not on the card either.
- `internal/edge/ratelimit.go`: `Edge.rateAdmit`.
- `internal/edge/planthrottle.go`: `Edge.planThrottleOf`, `Edge.trackUpgrade`.
+
+ Task 5's card, reconciled with this list and with `planThrottleFor`
+ above. `Edge.rateAdmit`, `Edge.planThrottleOf`, `Edge.trackUpgrade`:
+ `sites` (`+whole:Route` each, the `IsForward` call added to the kind
+ selector). `planThrottleFor`: `body`, read sites unchanged (2). Each
+ admits a forward row where it admitted only an instance; the
+ `fromTunnel` exemptions are unchanged. No unit on the card is missing
+ from this list, and none listed here is missing from the card.
- `internal/edge/assetcatch.go`: `Edge.localAssetCatch`.
- `internal/release/layoutintent.go`: `FleetForwardFloor`,
`FleetForwardFloorAllows`, `FleetForwardFloorOverrideFlag`,
diff --git a/internal/edge/fleetforward_policy_test.go b/internal/edge/fleetforward_policy_test.go
new file mode 100644
index 000000000..6ac865621
--- /dev/null
+++ b/internal/edge/fleetforward_policy_test.go
@@ -0,0 +1,259 @@
+package edge
+
+// Fleet public routes, Task 5 (spec §4.8, §8 test 7): a forward row's rate
+// limit, plan throttle and upgrade tracking apply once, at the hub, and the
+// fleet edge keeps exempting what arrives over the tunnel.
+//
+// Both edges come from forwardHubAndBox. The box is a real Edge whose own
+// row for the host carries a LOWER rate limit (burst 1) than the hub's
+// forward row (burst 2), so a box that also enforced would refuse the second
+// tunneled request: only the hub enforces (preflight T5). Both limiters run
+// on a frozen clock, so the buckets never refill during a test.
+// CARLOS_RATE_LIMIT is set before forwardHubAndBox, because New reads it once.
+
+import (
+ "bufio"
+ "fmt"
+ "io"
+ "net"
+ "net/http"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/plans"
+ "github.com/carlosframework/platform/internal/ratelimit"
+ "github.com/carlosframework/platform/internal/registry"
+)
+
+const (
+ polHost = "shop.example.com"
+ polHubRate = `{"rate":1,"burst":2}` // the hub's forward row: two requests, then 429
+ polBoxRate = `{"rate":1,"burst":1}` // the box's own row: one, if it ever judged
+)
+
+// polBackend is the app behind the fleet edge. It counts what reaches it,
+// answers a GET with "ok", and answers an upgrade with a 101 and then echoes
+// lines on the hijacked connection until the client or the hub goes away.
+type polBackend struct {
+ mu sync.Mutex
+ gets int
+ upgrades int
+ closed chan struct{} // one send per upgraded connection that ends
+}
+
+func (b *polBackend) ServeHTTP(w http.ResponseWriter, r *http.Request) {
+ if !isUpgradeRequest(r) {
+ b.mu.Lock()
+ b.gets++
+ b.mu.Unlock()
+ io.WriteString(w, "ok")
+ return
+ }
+ b.mu.Lock()
+ b.upgrades++
+ b.mu.Unlock()
+ conn, buf, err := w.(http.Hijacker).Hijack()
+ if err != nil {
+ return
+ }
+ defer func() {
+ conn.Close()
+ b.closed <- struct{}{}
+ }()
+ buf.WriteString("HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n\r\n")
+ buf.Flush()
+ for {
+ line, err := buf.ReadString('\n')
+ if err != nil {
+ return
+ }
+ buf.WriteString("echo:" + line)
+ buf.Flush()
+ }
+}
+
+func (b *polBackend) counts() (gets, upgrades int) {
+ b.mu.Lock()
+ defer b.mu.Unlock()
+ return b.gets, b.upgrades
+}
+
+// policyScene is forwardHubAndBox in enforce mode: the hub's forward row for
+// polHost carries polHubRate, the box's own row polBoxRate, and both edges'
+// limiters are on a frozen clock.
+func policyScene(t *testing.T) (hubURL string, hub, box *Edge, app *polBackend) {
+ t.Helper()
+ t.Setenv("CARLOS_RATE_LIMIT", "enforce")
+ app = &polBackend{closed: make(chan struct{}, 8)}
+ appAddr := startPolBackend(t, app)
+ fwd := forwardRow(polHost, "home", fwdOwner)
+ fwd.RateLimit = polHubRate
+ hubURL, hub, box = forwardHubAndBox(t, []registry.Route{fwd},
+ []registry.Route{{Host: polHost, Kind: "instance", Status: "ready", Addr: appAddr, Account: fwdOwner, App: "shop", RateLimit: polBoxRate}},
+ nil)
+ for name, e := range map[string]*Edge{"hub": hub, "box": box} {
+ if e.rateMode != RateEnforce {
+ t.Fatalf("the %s's rate mode is %v, want enforce", name, e.rateMode)
+ }
+ }
+ if got := hub.current()[polHost].rate; got.Burst != 2 {
+ t.Fatalf("the hub's forward row parsed to %+v, want burst 2 (the row's RateLimit)", got)
+ }
+ if got := box.current()[polHost].rate; got.Burst != 1 {
+ t.Fatalf("the box's row parsed to %+v, want burst 1", got)
+ }
+ frozen := time.Date(2026, 10, 30, 12, 0, 0, 0, time.UTC)
+ hub.rateLimiter = ratelimit.NewLimiter(func() time.Time { return frozen }, 1000)
+ box.rateLimiter = ratelimit.NewLimiter(func() time.Time { return frozen }, 1000)
+ return hubURL, hub, box, app
+}
+
+func startPolBackend(t *testing.T, h http.Handler) string {
+ t.Helper()
+ ln, err := net.Listen("tcp", "127.0.0.1:0")
+ if err != nil {
+ t.Fatal(err)
+ }
+ srv := &http.Server{Handler: h}
+ go srv.Serve(ln)
+ t.Cleanup(func() { srv.Close() })
+ return ln.Addr().String()
+}
+
+// polUpgrade sends one WebSocket handshake for polHost to the hub on a raw
+// connection and returns the connection, its reader and the answer.
+func polUpgrade(t *testing.T, hubURL string) (net.Conn, *bufio.Reader, *http.Response, string) {
+ t.Helper()
+ c, err := net.Dial("tcp", strings.TrimPrefix(hubURL, "http://"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { c.Close() })
+ c.SetDeadline(time.Now().Add(10 * time.Second))
+ fmt.Fprintf(c, "GET /socket HTTP/1.1\r\nHost: %s\r\nConnection: Upgrade\r\nUpgrade: websocket\r\n\r\n", polHost)
+ br := bufio.NewReader(c)
+ resp, err := http.ReadResponse(br, nil)
+ if err != nil {
+ t.Fatalf("handshake: %v", err)
+ }
+ body := ""
+ if resp.StatusCode != http.StatusSwitchingProtocols {
+ b, _ := io.ReadAll(resp.Body)
+ body = string(b)
+ }
+ return c, br, resp, body
+}
+
+// wantHubRefusal checks a refusal is the edge's 429, written at the hub.
+func wantHubRefusal(t *testing.T, resp *http.Response, body, what string) {
+ t.Helper()
+ if resp.StatusCode != http.StatusTooManyRequests {
+ t.Fatalf("%s: status %d %q, want 429", what, resp.StatusCode, body)
+ }
+ if resp.Header.Get("Retry-After") == "" || resp.Header.Get("Cache-Control") != "no-store" || body != rateLimitBody {
+ t.Fatalf("%s: %v %q, want the edge's whole refusal (Retry-After, no-store, its body)", what, resp.Header, body)
+ }
+}
+
+func TestForwardRateLimitAtTheHubOnly(t *testing.T) {
+ hubURL, _, _, app := policyScene(t)
+ for i := 1; i <= 2; i++ {
+ resp, body := fwdDo(t, hubURL, "GET", polHost, "/", "", nil)
+ if resp.StatusCode != http.StatusOK || string(body) != "ok" {
+ t.Fatalf("GET %d: %d %q, want the app's 200: within the hub's burst of 2, and the box, whose own row allows 1, must not judge a tunneled request", i, resp.StatusCode, body)
+ }
+ }
+ resp, body := fwdDo(t, hubURL, "GET", polHost, "/", "", nil)
+ wantHubRefusal(t, resp, string(body), "GET 3, past the forward row's burst")
+ if gets, _ := app.counts(); gets != 2 {
+ t.Fatalf("the app saw %d requests, want 2: the third is refused at the hub and never crosses the tunnel", gets)
+ }
+}
+
+// Upgrades do not cross the fleet tunnel today: the hub's tunnel transport is
+// an HTTP/2 client, which refuses a request with an Upgrade header ("http2:
+// invalid Upgrade request header"), so an admitted handshake for any
+// fleet-placed row is answered 502 by the hub and never reaches the box. What
+// the hub's admission decides is still visible: an admitted handshake gets
+// the transport's answer, a refused one the edge's 429.
+func TestForwardUpgradeIsLimitedAtTheHub(t *testing.T) {
+ hubURL, _, _, app := policyScene(t)
+ for i := 1; i <= 2; i++ {
+ _, _, resp, body := polUpgrade(t, hubURL)
+ if resp.StatusCode != http.StatusSwitchingProtocols && resp.StatusCode != http.StatusBadGateway {
+ t.Fatalf("handshake %d: %d %q, want it admitted at the hub (its burst is 2) and handed to the tunnel", i, resp.StatusCode, body)
+ }
+ }
+ _, _, resp, body := polUpgrade(t, hubURL)
+ wantHubRefusal(t, resp, body, "handshake 3, past the forward row's burst")
+ if got := resp.Header.Get("Retry-After"); got != "1" {
+ t.Fatalf("handshake 3: Retry-After %q, want the rate limit's 1", got)
+ }
+ if _, ups := app.counts(); ups > 2 {
+ t.Fatalf("the app saw %d upgrades, want at most 2", ups)
+ }
+}
+
+// The plan throttle and upgrade tracking key on the forward row's account at
+// the hub. Since no upgrade stays open across the tunnel (above), "an open
+// upgrade is closed" is shown at the moment the hub asks the throttle about
+// it: trackUpgrade registers the request first (Astra plans-4c finding 2), so
+// a CloseAccountUpgrades from inside the throttle hook finds it and cancels
+// it. That is the window the host's pass relies on.
+func TestForwardPlanThrottleAndUpgradeClose(t *testing.T) {
+ hubURL, hub, _, app := policyScene(t)
+ var mu sync.Mutex
+ throttled, closeInHook := true, false
+ closedInHook := -1
+ hub.SetPlanThrottleFor(func(rt registry.Route) (plans.Throttle, bool) {
+ if rt.Account != fwdOwner {
+ return plans.Throttle{}, false
+ }
+ mu.Lock()
+ on, closeNow := throttled, closeInHook
+ closeInHook = false
+ mu.Unlock()
+ if closeNow {
+ n := hub.CloseAccountUpgrades(fwdOwner)
+ mu.Lock()
+ closedInHook = n
+ mu.Unlock()
+ }
+ if !on {
+ return plans.Throttle{}, false
+ }
+ return plans.Throttle{Bandwidth: true, Awake: true, Until: time.Now().Add(time.Hour)}, true
+ })
+
+ // Awake-throttled: the hub refuses the upgrade with the plan throttle's
+ // 429 (Retry-After 60, not the rate limit's 1).
+ _, _, resp, body := polUpgrade(t, hubURL)
+ wantHubRefusal(t, resp, body, "a handshake while the account is awake-throttled")
+ if got := resp.Header.Get("Retry-After"); got != "60" {
+ t.Fatalf("Retry-After %q, want the plan throttle's 60", got)
+ }
+ if _, ups := app.counts(); ups != 0 {
+ t.Fatalf("the app saw %d upgrades, want 0", ups)
+ }
+
+ // Plans govern bah and the throttle is lifted: the handshake is tracked
+ // under bah while it is in flight, and closable.
+ hub.SetPlanGovernedFor(func(rt registry.Route) bool { return rt.Account == fwdOwner })
+ mu.Lock()
+ throttled, closeInHook = false, true
+ mu.Unlock()
+ if _, _, resp, body := polUpgrade(t, hubURL); resp.StatusCode == http.StatusTooManyRequests {
+ t.Fatalf("an unthrottled handshake: 429 %q", body)
+ }
+ mu.Lock()
+ n := closedInHook
+ mu.Unlock()
+ if n != 1 {
+ t.Fatalf("CloseAccountUpgrades(%q) during the forward row's handshake closed %d, want 1: the hub tracks a forward row's upgrade under its account", fwdOwner, n)
+ }
+ if n := hub.CloseAccountUpgrades(fwdOwner); n != 0 {
+ t.Fatalf("CloseAccountUpgrades after the handshake ended closed %d, want 0", n)
+ }
+}
diff --git a/internal/edge/planthrottle.go b/internal/edge/planthrottle.go
index 65358f5f3..e2a98743d 100644
--- a/internal/edge/planthrottle.go
+++ b/internal/edge/planthrottle.go
@@ -49,10 +49,12 @@ func (e *Edge) notePlanThrottled(rt registry.Route, what string) {
}
// planThrottleOf is the route's throttle when one applies to this request.
+// An instance or a forward row (fleet public routes §4.8: the hub throttles
+// a forward row's account; the fleet edge sees it only over the tunnel).
// Door, hop-door and tunnel callers are exempt, as from the rate limit.
func (e *Edge) planThrottleOf(r *http.Request, up upstream) (plans.Throttle, bool) {
f := e.planThrottle.Load()
- if f == nil || up.route.Kind != "instance" {
+ if f == nil || (up.route.Kind != "instance" && !up.route.IsForward()) {
return plans.Throttle{}, false
}
if _, door := doorCallerFrom(r.Context()); door || hopDoorFrom(r.Context()) || fromTunnel(r.Context()) {
@@ -95,10 +97,11 @@ func (e *Edge) planUpgradeAdmit(w http.ResponseWriter, r *http.Request, up upstr
// account without plans keeps its request exactly as it was. The caller
// registers BEFORE asking the throttle (Astra plans-4c finding 2): the host
// publishes a throttle and then closes, so either this request sees the
-// throttle, or it is registered when the close comes.
+// throttle, or it is registered when the close comes. An instance or a
+// forward row, tracked at the hub (fleet public routes §4.8).
func (e *Edge) trackUpgrade(r *http.Request, up upstream) (*http.Request, func()) {
g := e.planGoverned.Load()
- if g == nil || up.route.Kind != "instance" || !(*g)(up.route) {
+ if g == nil || (up.route.Kind != "instance" && !up.route.IsForward()) || !(*g)(up.route) {
return r, func() {}
}
acct := release.RouteAccount(up.route)
diff --git a/internal/edge/ratelimit.go b/internal/edge/ratelimit.go
index 124db8f74..10a08a268 100644
--- a/internal/edge/ratelimit.go
+++ b/internal/edge/ratelimit.go
@@ -115,14 +115,16 @@ func (e *Edge) parseRateSettings(rt registry.Route) ratelimit.Settings {
// writer has not already. An upgrade holds one like any request, until its
// handshake is answered.
//
-// Not judged: anything but an instance, a door caller (the box itself, on
+// Not judged: anything but an instance or a forward row (fleet public
+// routes §4.8: the hub judges a forward row once, with the app's own
+// settings from the row's rate_limit column), a door caller (the box itself, on
// this box or on the box that backhauled it, hopDoorFrom), and a request
// that arrived over a fleet tunnel. On the fleet side of a tunnel every
// request comes from the hub, so keying on it would put every client in one
// bucket; the hub has the route row and the real client, and limits there
// (its route is viaTunnel).
func (e *Edge) rateAdmit(w http.ResponseWriter, r *http.Request, up upstream) (release func(), ok bool) {
- if e.rateMode == RateOff || up.route.Kind != "instance" {
+ if e.rateMode == RateOff || (up.route.Kind != "instance" && !up.route.IsForward()) {
return nil, true
}
if _, door := doorCallerFrom(r.Context()); door || hopDoorFrom(r.Context()) || fromTunnel(r.Context()) {
diff --git a/internal/host/plans_pass.go b/internal/host/plans_pass.go
index 30ff06193..05cedfffc 100644
--- a/internal/host/plans_pass.go
+++ b/internal/host/plans_pass.go
@@ -203,10 +203,11 @@ func planRateCeilingFor(rt registry.Route) ratelimit.Ceiling {
const planAwakeCeiling = 15 * time.Minute
// planThrottleFor is the route's account's plan throttle when one is in
-// force: an instance route, plans on, a record with a throttle, before its
-// Until. Anything else is (zero, false).
+// force: an instance or forward route (fleet public routes §4.8: the hub
+// throttles a forward row's account), plans on, a record with a throttle,
+// before its Until. Anything else is (zero, false).
func planThrottleFor(rt registry.Route) (plans.Throttle, bool) {
- if rt.Kind != "instance" {
+ if rt.Kind != "instance" && !rt.IsForward() {
return plans.Throttle{}, false
}
snap := planLimits.Load()
diff --git a/internal/host/plans_pass_test.go b/internal/host/plans_pass_test.go
index 843bbbe06..f06dd18bc 100644
--- a/internal/host/plans_pass_test.go
+++ b/internal/host/plans_pass_test.go
@@ -233,3 +233,28 @@ func TestPlansPassesDoNotRestoreDisabledLimits(t *testing.T) {
t.Fatal("a stalled pass restored limits after plans were disabled")
}
}
+
+// Fleet public routes (spec §4.8): a forward row's account is throttled at
+// the hub like an instance's. The account is "bah" (domains.Sqid(7)), a real
+// non-ops sqid; a route of another kind stays unthrottled.
+func TestPlanThrottleForAdmitsForwardRows(t *testing.T) {
+ t.Cleanup(func() { planLimits.Store(nil) })
+ planLimits.Store(&planLimitsSnapshot{byAccount: map[string]plans.Limits{}, throttle: map[string]plans.Throttle{
+ "bah": {Bandwidth: true, Awake: true, Until: time.Now().Add(time.Hour)},
+ }})
+ fwd := registry.Route{Host: "shop.example.com", Kind: registry.KindForward, Slug: "shop", App: "shop",
+ Account: "bah", Region: registry.PlacementTarget("home")}
+ if th, ok := planThrottleFor(fwd); !ok || !th.Awake {
+ t.Fatalf("forward row of a throttled account: %+v, %v, want its awake throttle", th, ok)
+ }
+ inst := fwd
+ inst.Kind = "instance"
+ if _, ok := planThrottleFor(inst); !ok {
+ t.Fatal("control: the same account's instance row is not throttled")
+ }
+ other := fwd
+ other.Kind = "worker"
+ if _, ok := planThrottleFor(other); ok {
+ t.Fatal("a worker row is throttled; only instance and forward rows are")
+ }
+}