carlos / platform Public

edge: forward fleet replica coordinator calls on the tunnel host (#511)

A fleet box posts replica coordinator calls to its tunnel URL, where the edge only forwarded /store/ and the hub answered 404; the box read that as fenced, so stateless rootfs apps never deployed on fleets (Plan 1 dev smoke F1). The tunnel-host branch now forwards clean POST paths under /api/fleet/replicas/ to the local console route only; the console still authenticates with fleetIdentityOK. Answers that are not from the console are reported as console unreachable, not fenced, and surface as the rollout reason. Census approved on #280 (re-sealed on main at 7974cb07). Not released.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Squashed from stateless-coordinator-route into main.
Paul Campbell pushed by claude agent, operated by paul@keymail.dev 7920cccf19e770a16045f8fcc35982da5f2c07ab parent 3487d6f
23 files changed, +388 −12
  • approved_stateless_replicas_copy_test.go +1 −1
  • docs/superpowers/notes/census-claims-stateless-coordinator-route.tsv +3 −0
  • docs/superpowers/notes/census-proposal-stateless-coordinator-route.md +27 −0
  • docs/superpowers/plans/2026-11-01-stateless-replicas-copy.md +1 −0
  • instances_cli.go +3 −0
  • instances_rollout_test.go +1 −0
  • internal/activator/swap.go +7 −2
  • internal/activator/swap_error_test.go +21 −0
  • internal/console/instancepage.go +3 −0
  • internal/console/swapcopy_truth_test.go +7 −0
  • internal/edge/edge.go +4 −0
  • internal/edge/replicaconsole.go +39 −0
  • internal/edge/replicaconsole_test.go +102 −0
  • internal/host/replicacoordinator.go +30 −3
  • internal/host/replicacoordinator_test.go +72 −2
  • internal/provision/testdata/plan14-root-reads-chain.tsv +1 −0
  • internal/provision/testdata/plan14-root-reads-stateless-coordinator-route.tsv +16 −0
  • internal/replicas/types.go +2 −0
  • internal/rollout/fake_test.go +6 −2
  • internal/rollout/queue.go +3 −2
  • internal/rollout/scheduler.go +10 −0
  • internal/rollout/status.go +4 −0
  • internal/rollout/status_test.go +25 −0

CI failed — run details

diff --git a/approved_stateless_replicas_copy_test.go b/approved_stateless_replicas_copy_test.go
index 3fd9b1200..035bcf296 100644
--- a/approved_stateless_replicas_copy_test.go
+++ b/approved_stateless_replicas_copy_test.go
@@ -9,7 +9,7 @@ import (
const statelessReplicaCopyDeck = "docs/superpowers/plans/2026-11-01-stateless-replicas-copy.md"
-var statelessReplicaBuiltCopy = []string{"SR-1-C08", "SR-1-C06", "SR-1-C07", "SR-1-C01", "SR-1-C02", "SR-1-C03", "SR-1-C04", "SR-1-C05", "SR-1-C12", "SR-1-C09", "SR-1-C10", "SR-1-C13"}
+var statelessReplicaBuiltCopy = []string{"SR-1-C08", "SR-1-C06", "SR-1-C07", "SR-1-C01", "SR-1-C02", "SR-1-C03", "SR-1-C04", "SR-1-C05", "SR-1-C12", "SR-1-C09", "SR-1-C10", "SR-1-C13", "SR-1-C14"}
func statelessReplicaCopyRows(t *testing.T) []copyRow {
t.Helper()
diff --git a/docs/superpowers/notes/census-claims-stateless-coordinator-route.tsv b/docs/superpowers/notes/census-claims-stateless-coordinator-route.tsv
new file mode 100644
index 000000000..20684e1c5
--- /dev/null
+++ b/docs/superpowers/notes/census-claims-stateless-coordinator-route.tsv
@@ -0,0 +1,3 @@
+internal/edge/edge.go:Edge.ServeHTTP P24/P25: POST only, exact /api/fleet/replicas/ prefix on the reserved tunnel host calls the existing local console proxy only for an unescaped, already-clean path; malformed forms remain on the hub. No new read sites relative to origin/main. Merge with main 3487d6f6 retains its region HA admission checks before routing and after login target lookup, its empty-home refusal, and their two existing whole:Route reads; these change this unit's digest relative to the previously approved branch tip 92b24a7d.
+internal/edge/replicaconsole.go:Edge.serveReplicaConsole Reads existing in-memory route fields to select a unique accountless console.service local upstream; refuses missing or ambiguous console, tenant routes, remote and tunnel upstreams. Reuses proxy and version wrapper; leaves fleet identity authentication at console.
+internal/rollout/scheduler.go:scheduler.done P25: classifies the preserved SwapResult.Err with errors.Is, including wrapped console-unreachable causes, to record the current scheduler revision and suppress duplicate abandoned logs. Diagnostic text no longer grants this classification. No new read sites or failure-book authority.
diff --git a/docs/superpowers/notes/census-proposal-stateless-coordinator-route.md b/docs/superpowers/notes/census-proposal-stateless-coordinator-route.md
new file mode 100644
index 000000000..9e2933d43
--- /dev/null
+++ b/docs/superpowers/notes/census-proposal-stateless-coordinator-route.md
@@ -0,0 +1,27 @@
+# Census proposal: stateless-coordinator-route
+
+Review history: round 1 and P25 fixes are recorded in coord-route-report.md. The controller reports tip 92b24a7d reviewed, census-approved and CI-green, with Paul approving landing. This refresh re-seals the merge with origin/main 3487d6f6, retaining both sides. No new independent review round was opened.
+
+Ruling `census-ruling-stateless-coordinator-route`. The independent reviewer approves or rejects every change below, 1 with a new disposition; nothing goes to the census owner (Paul, #280, 2026-10-26).
+
+| unit | change | read sites | what changed |
+|---|---|---|---|
+| `internal/edge/edge.go` `Edge.ServeHTTP` | body | unchanged (42) | P24/P25: POST only, exact /api/fleet/replicas/ prefix on the reserved tunnel host calls the existing local console proxy only for an unescaped, already-clean path; malformed forms remain on the hub. No new read sites relative to origin/main. Merge with main 3487d6f6 retains its region HA admission checks before routing and after login target lookup, its empty-home refusal, and their two existing whole:Route reads; these change this unit's digest relative to the previously approved branch tip 92b24a7d. |
+| `internal/rollout/scheduler.go` `scheduler.done` | body | unchanged (6) | P25: classifies the preserved SwapResult.Err with errors.Is, including wrapped console-unreachable causes, to record the current scheduler revision and suppress duplicate abandoned logs. Diagnostic text no longer grants this classification. No new read sites or failure-book authority. |
+
+Envelopes re-pinned: `.`, `internal/activator`, `internal/edge`, `internal/host`, `internal/replicas`, `internal/rollout`.
+
+Review: a model from the other family than the author reads the branch's diff against main on the amadan.net remote (`origin` or `amadan`, whichever points at amadan.net) and gives a verdict for every unit and every re-pinned envelope above. For a unit, compare the change with its recorded disposition and basis below; for an envelope, read every changed function in the package and what it reaches. Reject if the change lets root open, run, query or follow anything it did not before from a path or input a tenant, an app or a box agent can create, write or name; if it weakens a check, refusal, validation, argument or environment the basis relies on; or if the diff cannot settle either. Otherwise approve. Record each verdict on #280 with the tip. A rejected unit goes back to the author to correct; nothing escalates to the census owner.
+
+Recorded dispositions, which each change must still satisfy:
+
+- `internal/edge/edge.go` `Edge.ServeHTTP`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-seeded-instances;basis=the edge inside the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): main's body with the import gate checked after the door's scope and a gated row left out of the response cache; serving only;rev3=census-ruling-edge-request-records;basis=one more call in the observer defer, observeRecords(up.route, ...), passing on the route the defer already holds; no new kind of read;rev3=census-ruling-design-edge-rate-limit-358;basis=calls rateAdmit twice, and an admitted request holds a slot on both paths: on the upgrade path before the activator or proxy (the handshake holds its slot through slotWriter, given back at the first final answer or at the reverse proxy's hijack on a 101, so an open WebSocket is not counted; released by a defer), and on the ordinary path after the response-cache check and before the activator and proxy (an admitted request holds a slot through slotWriter, released by a defer); a refusal is a 429 written there and returns; the upgrade path's comment now names slotWriter as its one wrapper; one comment on the door mark reworded; read sites unchanged (22: main's 21 plus edge-request-records' observeRecords pass of the route), offsets moved; no read added;rev3=census-ruling-plans-4c-box-throttle;basis=calls planThrottleAdmit before the response cache, and on an upgrade trackUpgrade then planUpgradeAdmit (plans 4c, Astra findings 1 and 2); the new reads live in those units (plans-4c-units decision). The same read sites here.;rev3=census-ruling-plans-4d-lapse;basis=calls planDisabledAdmit right after the import gate, passing the final upstream's route and the request host; a turned-off route gets the fixed disabled page before the meter, gate, cache and activator (plans 4d). The new read lives in that unit (plans-4d-units decision); one more whole-row pass here.;rev3=census-ruling-edge-protection-2;basis=runs the guard, a pure in-memory matcher on r.URL.Path and RawQuery (internal/edgeguard), once per request after the meter and observer defer and before the password gate, the upgrade branch, the cache and the activator, for a request that is not a door call, a backhauled door hop or a tunnel delivery; a matched block answers a 404 itself through guardDecide; the two new sites are one expression, up.route.Kind == "static" (a static route this box serves checks only the hard tier here and leaves the probe tier to serveTree), a read of the route row the edge already resolved; no new kind of read;rev3=census-ruling-edge-asset-cache-3;basis=the asset cache's three hooks (asset cache plan 3): the request's reserved asset headers are deleted at entry (the fill assertion kept only beside a verified hop); on the exact-remote and lookup-miss branches the far catch (serveAssetFar) is tried before backhaulTo and backhaul; after the observer defer and main's hard and probe checks, a verified hop with a valid fill assertion is answered by serveAssetFillForHop; after the upgrade branch and before gzip and the shared cache, the local catch (serveAssetLocal); the observer defer skips only the usage meter for an acknowledged home fill (out.unbilled); the new reads live in the new units of the edge-asset-cache-3-decisions overlay; the same route row and read sites (25); no read added;rev3=census-ruling-regional-domains-447;basis=#447 Task 5: straight after lookupUpstreamPath it calls regionalGate (regional.go), which for an entry built from a regional_domains row answers 503 to a hop or a deny entry before any arm that can leave the box (the exact-home backhaul, the far asset catch, the door dial, the miss backhaul), and lets a star match through only to the exact-home arm when ExactHome names another box for that distinct exact name; after the exact-home arm a regional deny entry the arm did not answer is refused (regionalRefuse, 503); refusals only, on the route map the edge already holds; read sites unchanged (25);rev3=census-ruling-static-headers;basis=the shared response cache is no longer looked up or filled for a static-kind route: one more read of the route row the edge already resolved (up.route.Kind == "static") in the cacheable expression; a refusal only, nothing new opened or followed;rev3=census-ruling-region-ha-p1b2;basis=region HA P1b-2 (N-HA10): one call, frontForwardHA, right after the route lookup's !ok block and before the login POST; same reads;rev3=census-ruling-fleet-public-routes;basis=fleet public routes (spec 2026-10-29 rev 4, §4.2 writer rule): Task 4: loginPost and cacheable treat a forward row as not this box's to answer (IsForward(), +whole:Route x2): no login form and no shared cache for a forward host. Serving only.;rev3=census-ruling-tunnel-websockets;basis=Deletes the Carlos-Upgrade marker header from incoming requests and puts the upgrade admission (host, path, the entry tenancy, all in hand) on a tunnel arm request. For a login POST on an ungated ArmTunnel row it reads the visitor request body (bounded by gate.MaxFormBody, 413 past it; a request body, not a file) and resolves next against the entry Reload built (Gate, Route); the bytes pass on only when loginPassesThrough holds (spec 7, Tasks 3, 5 and 6).;rev3=census-ruling-console-protection-tab;basis=one more call in the observer defer, observeGuardCount(up.route, out), beside the observeRecords call that files the guard Match: it passes on the route row the defer already holds (+whole:Route) and the request outcome to the usage meter, which counts the check in memory. Called whether or not the request was unbilled, as observeRecords is. Nothing is opened, read or followed; no new kind of read; no check, refusal or serving decision changes.;rev3=census-ruling-probe-burst-limit;basis=answers a probe-burst notice POST (serveBurstNotice) ahead of every route for a non-door caller; builds the guard state for up.route and stamps its account and app (RouteAccount, App) for the cool-down's this-app/other-app label; for a catalogue match on a non-static or tunnelled route, offers the burst rule (in-memory limiter, burstDecide: 429 or a watch verdict, never a block for a fleet or forward row); the observer defer calls noteBurst(up.route, ...); the added sites are the route value already in hand (+registry:App, +whole:Route x5); no new root read or write kind;rev3=census-ruling-edge-held-streams;basis=the edge in the agent (carlos-edge.service, user carlos): parses the request's query once (stripHoldMarker) to record the carlos_hold=1 mark in the request context; calls classifyHold on the upstream already resolved from the loaded map (the +whole:Route is that in-memory Route), including a second pass for a login POST; gives a marked request on a door-refused route the plain 404; adds the hold branch (planThrottleAdmit, rateAdmit, serveHeld) after the gate; and excludes marked requests from the shared cache. Reads only the request and the already-loaded upstream map; no registry or bucket read added.;rev3=census-ruling-region-ha-p3a;basis=Complete the P3a cut: an exact peer name with no dial target answers the approved admission 503 before local wildcard dispatch or asset serving. ExactHome and lookupHome stop fallback at a present non-dial entry; backhaulTo refuses an empty target before signing or dialing. Retain Task 3 local admission and fixed platform/unit exemptions. Two added whole Route uses feed the local in-memory admission predicate; existing Route values and store/path reads are unchanged.
+- `internal/rollout/scheduler.go` `scheduler.done`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=J1,J4;basis=route-and-input
+
+New dispositions, which census-propose wrote and the reviewer checks against the unit's reads and the diff:
+
+- new `internal/edge/replicaconsole.go:Edge.serveReplicaConsole`: reads +registry:Account, +registry:App, +registry:Host, +registry:Socket, +registry:Unit, +whole:Route; written legacy, accepted-legacy, frozen
+
+Seal: `f44d209a054eee55fdee54227d419b74c34a9b2fc174c7a0bb74d5c2711a68bb` → `7974cb078e82272605cbc8ef6809c9ae5e0b02edc22ca843cd2ef4b38d9e44e9`.
+
+Overlay: `internal/provision/testdata/plan14-root-reads-stateless-coordinator-route.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`.
diff --git a/docs/superpowers/plans/2026-11-01-stateless-replicas-copy.md b/docs/superpowers/plans/2026-11-01-stateless-replicas-copy.md
index 841036018..692e3a491 100644
--- a/docs/superpowers/plans/2026-11-01-stateless-replicas-copy.md
+++ b/docs/superpowers/plans/2026-11-01-stateless-replicas-copy.md
@@ -30,6 +30,7 @@ copy too. Internal wire enums are not an excuse to expose unreviewed text.
| SR-1-C11 | docs/site/cli.md | A stateless release can run more than one copy on a fleet after every fleet box and the console support replicas. Apps keep one copy until you set --copies. | approved by delegation (Luna pass, 2026-11-01) |
| SR-1-C12 | internal/console/replicacoordinator.go | this instance changed before the coordination update finished. try again | approved by delegation (Luna pass, 2026-11-01); was: this instance changed while coordination was being updated. try again |
| SR-1-C13 | docs/site/cli.md | If the box running the release command disappears, its result may be unknown. The deploy stops and the previous build keeps serving. Deploying again runs the command again, so release commands must be safe to repeat. Rails migrations record completed migrations in schema_migrations. | approved by delegation (Luna pass, 2026-11-01); Luna's text for SR-4-C26, reused here because Plan 1 documents repeat-safe release commands |
+| SR-1-C14 | internal/replicas/types.go | console unreachable | approved provisionally (controller ruling P25; for Paul's copy review) |
## Plan 2: count and placement
diff --git a/instances_cli.go b/instances_cli.go
index 83506a2df..730ab193b 100644
--- a/instances_cli.go
+++ b/instances_cli.go
@@ -39,6 +39,7 @@ import (
"github.com/carlosframework/platform/internal/appconfig"
"github.com/carlosframework/platform/internal/provision"
"github.com/carlosframework/platform/internal/release"
+ "github.com/carlosframework/platform/internal/replicas"
"github.com/carlosframework/platform/internal/rolloutwords"
"github.com/carlosframework/platform/internal/updatewords"
)
@@ -603,6 +604,8 @@ func rolloutReason(r *apiRollout) string {
return fmt.Sprintf(rolloutwords.StateHeldBecause, r.HeldBy, rolloutwords.Reason(r.Reason))
case r.HeldBy != "":
return fmt.Sprintf(rolloutwords.StateHeld, r.HeldBy)
+ case r.Reason == replicas.ErrConsoleUnreachable.Error():
+ return r.Reason
case !r.Awake && r.Installed != r.Good:
return fmt.Sprintf(rolloutwords.StateAsleep, r.Installed)
case r.Awake && r.Installed != r.Serving:
diff --git a/instances_rollout_test.go b/instances_rollout_test.go
index 5fabcb2c1..7b392d108 100644
--- a/instances_rollout_test.go
+++ b/instances_rollout_test.go
@@ -39,6 +39,7 @@ func TestRolloutReason(t *testing.T) {
want string
}{
{nil, ""},
+ {&apiRollout{Installed: "v2", Serving: "v1", Awake: true, Reason: "console unreachable"}, "console unreachable"},
{&apiRollout{Installed: "v2", Serving: "v2", Awake: true}, ""},
{&apiRollout{Installed: "v2", Serving: "v1", Awake: true, HeldBy: "v2"}, fmt.Sprintf(rolloutwords.StateHeld, "v2")},
// Plan 5 reports no serving build for an asleep instance: its last
diff --git a/internal/activator/swap.go b/internal/activator/swap.go
index f5702d602..4fe0a3aa0 100644
--- a/internal/activator/swap.go
+++ b/internal/activator/swap.go
@@ -71,6 +71,7 @@ type SwapResult struct {
Outcome SwapOutcome
Gen Gen // the generation now current (on SwapDone)
Reason string
+ Err error // Preserves wrapped causes for scheduler classification.
// Drain is how long the retiring generation took from SIGTERM to its
// proven exit (an overlap), or the old generation's stop (a hold). Zero
// when nothing retired. The "swapped" event reports it (spec §9.4).
@@ -112,8 +113,12 @@ var (
errSwapMode = errors.New("swap: unknown mode")
)
-func abandon(err error) SwapResult { return SwapResult{Outcome: SwapAbandoned, Reason: err.Error()} }
-func failSwap(err error) SwapResult { return SwapResult{Outcome: SwapFailed, Reason: err.Error()} }
+func abandon(err error) SwapResult {
+ return SwapResult{Outcome: SwapAbandoned, Reason: err.Error(), Err: err}
+}
+func failSwap(err error) SwapResult {
+ return SwapResult{Outcome: SwapFailed, Reason: err.Error(), Err: err}
+}
// stepOutcome is how one step of an attempt (a spawn, a health check, a
// readiness or settle window, a pinned wake) ended.
diff --git a/internal/activator/swap_error_test.go b/internal/activator/swap_error_test.go
new file mode 100644
index 000000000..382fdb2c3
--- /dev/null
+++ b/internal/activator/swap_error_test.go
@@ -0,0 +1,21 @@
+package activator
+
+import (
+ "errors"
+ "fmt"
+ "testing"
+
+ "github.com/carlosframework/platform/internal/replicas"
+)
+
+func TestSwapResultPreservesWrappedCause(t *testing.T) {
+ cause := fmt.Errorf("acquire coordinator: %w", replicas.ErrConsoleUnreachable)
+ for _, result := range []SwapResult{abandon(cause), failSwap(cause)} {
+ if !errors.Is(result.Err, replicas.ErrConsoleUnreachable) || result.Reason != cause.Error() {
+ t.Fatalf("lost diagnostic or wrapped cause: %+v", result)
+ }
+ }
+ if result := abandon(errors.New(replicas.ErrConsoleUnreachable.Error())); errors.Is(result.Err, replicas.ErrConsoleUnreachable) {
+ t.Fatal("diagnostic text was treated as the sentinel")
+ }
+}
diff --git a/internal/console/instancepage.go b/internal/console/instancepage.go
index fa8f2e543..f4ffd4edf 100644
--- a/internal/console/instancepage.go
+++ b/internal/console/instancepage.go
@@ -10,6 +10,7 @@ import (
"time"
"github.com/carlosframework/platform/internal/provision"
+ "github.com/carlosframework/platform/internal/replicas"
"github.com/carlosframework/platform/internal/rolloutwords"
"github.com/carlosframework/platform/internal/status"
)
@@ -117,6 +118,8 @@ func (d *instanceDetail) RolloutNote() string {
switch {
case r == nil || r.Unavailable != "" || r.HeldBy != "":
return ""
+ case r.Reason == replicas.ErrConsoleUnreachable.Error():
+ return r.Reason
case !r.Awake && r.Installed != r.Good:
return fmt.Sprintf(swapCopy.Asleep, r.Installed)
case r.Awake && r.Installed != r.Serving:
diff --git a/internal/console/swapcopy_truth_test.go b/internal/console/swapcopy_truth_test.go
index 6f696bacb..88e0c3b8b 100644
--- a/internal/console/swapcopy_truth_test.go
+++ b/internal/console/swapcopy_truth_test.go
@@ -69,3 +69,10 @@ func TestInstancePageHoldTextTellsDownFromHeld(t *testing.T) {
t.Error("the down page lost its Retry")
}
}
+
+func TestRolloutNoteConsoleUnreachable(t *testing.T) {
+ d := instanceDetail{Rollout: &rolloutView{Installed: "v2", Serving: "v1", Awake: true, Reason: "console unreachable"}}
+ if got := d.RolloutNote(); got != "console unreachable" {
+ t.Fatalf("note: %q", got)
+ }
+}
diff --git a/internal/edge/edge.go b/internal/edge/edge.go
index bfff0da37..0e863a711 100644
--- a/internal/edge/edge.go
+++ b/internal/edge/edge.go
@@ -1929,6 +1929,10 @@ func (e *Edge) ServeHTTP(w http.ResponseWriter, r *http.Request) {
e.door.ServeHTTP(w, r)
return
}
+ if p := r.URL.Path; r.Method == http.MethodPost && r.URL.RawPath == "" && path.Clean(p) == p && strings.HasPrefix(p, "/api/fleet/replicas/") {
+ e.serveReplicaConsole(w, r)
+ return
+ }
e.tunnels.ServeHTTP(w, r)
return
}
diff --git a/internal/edge/replicaconsole.go b/internal/edge/replicaconsole.go
new file mode 100644
index 000000000..808673492
--- /dev/null
+++ b/internal/edge/replicaconsole.go
@@ -0,0 +1,39 @@
+package edge
+
+import "net/http"
+
+// serveReplicaConsole reuses the local console route, including its version
+// header. Only POSTs on the reserved tunnel host enter here; other methods
+// keep the hub's 404. Authentication remains the console's fleetIdentityOK.
+func (e *Edge) serveReplicaConsole(w http.ResponseWriter, r *http.Request) {
+ var console http.Handler
+ for host, up := range *e.upstreams.Load() {
+ rt := up.route
+ if host != rt.Host || up.alias || up.regional != 0 || up.viaTunnel || rt.Account != "" || rt.App != "console" || rt.Unit != "console.service" || rt.ActivatorOwned() {
+ continue
+ }
+ if rt.Socket == "" {
+ addrs := rt.AddrList()
+ if len(addrs) == 0 {
+ continue
+ }
+ local := true
+ for _, addr := range addrs {
+ local = local && isLocalUpstream(addr)
+ }
+ if !local {
+ continue
+ }
+ }
+ if console != nil {
+ w.WriteHeader(http.StatusServiceUnavailable)
+ return
+ }
+ console = up.proxy
+ }
+ if console == nil {
+ w.WriteHeader(http.StatusServiceUnavailable)
+ return
+ }
+ console.ServeHTTP(w, e.withForwardKey(r))
+}
diff --git a/internal/edge/replicaconsole_test.go b/internal/edge/replicaconsole_test.go
new file mode 100644
index 000000000..277102b77
--- /dev/null
+++ b/internal/edge/replicaconsole_test.go
@@ -0,0 +1,102 @@
+package edge
+
+import (
+ "context"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/registry"
+)
+
+func TestFleetReplicaConsoleOnTunnelHost(t *testing.T) {
+ var hits atomic.Int32
+ console := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ hits.Add(1)
+ body, err := io.ReadAll(r.Body)
+ if err != nil || string(body) != `{"op":"acquire"}` || r.Header.Get("Authorization") != "Bearer fleet-token" || r.Header.Get("Carlos-Tunnel-Name") != "fleet/box" || r.Header.Get("Content-Type") != "application/json" {
+ t.Errorf("upstream request: %s %v %q %v", r.URL, r.Header, body, err)
+ }
+ w.Header().Set("Content-Type", "application/json")
+ w.Header().Set("X-Upstream-Path", r.URL.RequestURI())
+ _, _ = io.WriteString(w, `{"lease":{}}`)
+ }))
+ defer console.Close()
+ app := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { _, _ = io.WriteString(w, "app") }))
+ defer app.Close()
+ reg := openReg(t)
+ rt := registry.Route{Host: "console.test", App: "console", Unit: "console.service", Kind: "service", Addr: console.Listener.Addr().String(), Status: "ready", Version: "v-test"}
+ for _, route := range []registry.Route{rt, {Host: "app.test", Kind: "service", Addr: app.Listener.Addr().String(), Status: "ready"}} {
+ if err := reg.Upsert(route); err != nil {
+ t.Fatal(err)
+ }
+ }
+ e, err := New(reg, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer e.probers.Stop()
+ e.EnableTunnels(NewTunnelHub("tunnel.test", nil))
+ const prefix = "/api/fleet/replicas/a/app/h/"
+ for _, tc := range []struct {
+ method, host, path string
+ code int
+ body string
+ hit bool
+ }{
+ {"POST", "tunnel.test", prefix + "coordinator", 200, `{"lease":{}}`, true},
+ {"POST", "tunnel.test:443", prefix + "release", 200, `{"lease":{}}`, true},
+ {"POST", "tunnel.test", prefix + "retire-ack", 200, `{"lease":{}}`, true},
+ {"GET", "tunnel.test", prefix + "coordinator", 404, "", false},
+ {"POST", "tunnel.test", "/api/fleet/replicas", 404, "", false},
+ {"POST", "tunnel.test", "/api/fleet/replicas-other/a", 404, "", false},
+ {"POST", "tunnel.test", "/api/accounts", 404, "", false},
+ {"POST", "tunnel.test", "/api%2Ffleet%2Freplicas%2Fx", 404, "", false},
+ {"POST", "tunnel.test", "/api/fleet/replicas/../../cli/apps/x", 404, "", false},
+ {"POST", "tunnel.test", "//api/fleet/replicas/x", 404, "", false},
+ {"POST", "tunnel.test", "/api/fleet/replicas/%2e%2e/x", 404, "", false},
+ {"POST", "tunnel.test", "/api/fleet/replicas/a%2Fb/app/h/coordinator", 404, "", false},
+ {"GET", "tunnel.test", "/register", 401, "", false},
+ {"POST", "app.test", prefix + "coordinator", 200, "app", false},
+ {"POST", "unknown.test", prefix + "coordinator", 404, "", false},
+ {"POST", "console.test", prefix + "coordinator", 200, `{"lease":{}}`, true},
+ } {
+ t.Run(tc.method+tc.host+tc.path, func(t *testing.T) {
+ ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
+ defer cancel()
+ req := httptest.NewRequest(tc.method, "https://"+tc.host+tc.path, strings.NewReader(`{"op":"acquire"}`)).WithContext(ctx)
+ req.Header.Set("Authorization", "Bearer fleet-token")
+ req.Header.Set("Carlos-Tunnel-Name", "fleet/box")
+ req.Header.Set("Content-Type", "application/json")
+ before := hits.Load()
+ w := httptest.NewRecorder()
+ e.ServeHTTP(w, req)
+ if w.Code != tc.code || tc.body != "" && w.Body.String() != tc.body || (hits.Load() > before) != tc.hit {
+ t.Fatalf("response %d %q, console hits %d", w.Code, w.Body.String(), hits.Load()-before)
+ }
+ if tc.hit && w.Header().Get("X-Upstream-Path") != tc.path {
+ t.Fatalf("upstream path: %q", w.Header().Get("X-Upstream-Path"))
+ }
+ if tc.hit && w.Header().Get("X-Carlos-Version") != "v-test" {
+ t.Fatal("missing console version header")
+ }
+ })
+ }
+ // A tenant app named console must not become the reserved API upstream.
+ rt.Account = "a"
+ if err := reg.Upsert(rt); err != nil {
+ t.Fatal(err)
+ }
+ if err := e.Reload(); err != nil {
+ t.Fatal(err)
+ }
+ w := httptest.NewRecorder()
+ e.ServeHTTP(w, httptest.NewRequest("POST", "https://tunnel.test"+prefix+"coordinator", nil))
+ if w.Code != http.StatusServiceUnavailable {
+ t.Fatalf("tenant console: %d", w.Code)
+ }
+}
diff --git a/internal/host/replicacoordinator.go b/internal/host/replicacoordinator.go
index 5038aea5f..a8fefe31d 100644
--- a/internal/host/replicacoordinator.go
+++ b/internal/host/replicacoordinator.go
@@ -4,11 +4,14 @@ import (
"bytes"
"context"
"encoding/json"
+ "errors"
"fmt"
"io"
+ "log"
"net/http"
"net/url"
"strings"
+ "sync"
"time"
"github.com/carlosframework/platform/internal/activator"
@@ -71,9 +74,12 @@ func (s *replicaCoordinatorStore) releaseState(ctx context.Context, id replicas.
type replicaCoordinatorAPI struct {
base, fleet, box, token string
client *http.Client
+ mu sync.Mutex
+ unreachable map[replicas.Identity]bool
}
-func (a *replicaCoordinatorAPI) post(ctx context.Context, id replicas.Identity, op string, body, out any) error {
+func (a *replicaCoordinatorAPI) post(ctx context.Context, id replicas.Identity, op string, body, out any) (result error) {
+ defer func() { a.observe(id, result) }()
raw, err := json.Marshal(body)
if err != nil {
return err
@@ -88,12 +94,15 @@ func (a *replicaCoordinatorAPI) post(ctx context.Context, id replicas.Identity,
req.Header.Set("Content-Type", "application/json")
resp, err := a.client.Do(req)
if err != nil {
- return err
+ return replicas.ErrConsoleUnreachable
}
defer resp.Body.Close()
+ if resp.StatusCode >= 500 || resp.Header.Get("X-Carlos-Version") == "" {
+ return replicas.ErrConsoleUnreachable
+ }
d := json.NewDecoder(io.LimitReader(resp.Body, 8192))
if resp.StatusCode != http.StatusOK {
- if resp.StatusCode >= 500 || resp.StatusCode == http.StatusTooManyRequests || resp.StatusCode == http.StatusRequestTimeout {
+ if resp.StatusCode == http.StatusTooManyRequests || resp.StatusCode == http.StatusRequestTimeout {
return fmt.Errorf("replica coordinator HTTP %d", resp.StatusCode)
}
if resp.StatusCode == http.StatusConflict && op == "coordinator" {
@@ -139,3 +148,21 @@ func closeReplicaCoordinator(client *activator.CoordinationClient) {
defer cancel()
client.Close(ctx)
}
+
+func (a *replicaCoordinatorAPI) observe(id replicas.Identity, err error) {
+ unreachable := errors.Is(err, replicas.ErrConsoleUnreachable)
+ a.mu.Lock()
+ defer a.mu.Unlock()
+ if a.unreachable[id] == unreachable {
+ return
+ }
+ if unreachable {
+ if a.unreachable == nil {
+ a.unreachable = make(map[replicas.Identity]bool)
+ }
+ a.unreachable[id] = true
+ } else {
+ delete(a.unreachable, id)
+ }
+ log.Printf("replica coordinator: %s: console unreachable=%t", id.Host, unreachable)
+}
diff --git a/internal/host/replicacoordinator_test.go b/internal/host/replicacoordinator_test.go
index 066ad0118..328a0c48c 100644
--- a/internal/host/replicacoordinator_test.go
+++ b/internal/host/replicacoordinator_test.go
@@ -1,11 +1,13 @@
package host
import (
+ "bytes"
"context"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
+ "log"
"net/http"
"net/http/httptest"
"path/filepath"
@@ -74,7 +76,10 @@ func TestReplicaReleaseFleetAPI(t *testing.T) {
if err != nil {
t.Fatal(err)
}
- ts := httptest.NewServer(srv)
+ ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("X-Carlos-Version", "test")
+ srv.ServeHTTP(w, r)
+ }))
t.Cleanup(ts.Close)
denied := &replicaDeniedStore{}
client := newCoordinatorClient(denied, ts.URL, "home", "b1", token)
@@ -84,6 +89,10 @@ func TestReplicaReleaseFleetAPI(t *testing.T) {
t.Fatal(err)
}
id := replicas.Identity{Account: rec.Account, App: rec.App, Host: rec.Host, Incarnation: inc}
+ unauthorized := &replicaCoordinatorAPI{base: ts.URL, fleet: "home", box: "b1", token: "wrong-token", client: &http.Client{Timeout: time.Second}}
+ if _, err := unauthorized.coordinator(ctx, id, replicas.CoordinatorChange{Op: "acquire"}); !errors.Is(err, replicas.ErrFenced) || errors.Is(err, replicas.ErrConsoleUnreachable) {
+ t.Fatalf("console's marked authorization 404: %v", err)
+ }
authority, err := client.Acquire(ctx, id)
if err != nil {
t.Fatal(err)
@@ -330,7 +339,10 @@ func TestCoordinatorConstructorTrustedStore(t *testing.T) {
func TestCoordinatorAPITransientStatus(t *testing.T) {
for _, status := range []int{500, 503, 429, 408, 403} {
t.Run(http.StatusText(status), func(t *testing.T) {
- server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(status) }))
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("X-Carlos-Version", "test")
+ w.WriteHeader(status)
+ }))
defer server.Close()
api := &replicaCoordinatorAPI{base: server.URL, client: server.Client()}
_, err := api.coordinator(context.Background(), replicas.Identity{}, replicas.CoordinatorChange{Op: "renew"})
@@ -362,6 +374,7 @@ type replicaHandlerTransport struct {
func (tr *replicaHandlerTransport) RoundTrip(r *http.Request) (*http.Response, error) {
w := httptest.NewRecorder()
+ w.Header().Set("X-Carlos-Version", "test")
tr.handler.ServeHTTP(w, r)
tr.status = w.Code
return w.Result(), nil
@@ -540,3 +553,60 @@ func TestCoordinatorHangingConsoleDoesNotDelayFastTick(t *testing.T) {
}
})
}
+
+func TestCoordinatorAPIConsoleUnreachable(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ code int
+ version, body string
+ want error
+ }{
+ {"hub 404", 404, "", "", replicas.ErrConsoleUnreachable},
+ {"console 404", 404, "test", "", replicas.ErrFenced},
+ {"proxy 502", 502, "test", "", replicas.ErrConsoleUnreachable},
+ {"console 503", 503, "test", "", replicas.ErrConsoleUnreachable},
+ {"unmarked conflict", 409, "", "", replicas.ErrConsoleUnreachable},
+ {"unmarked success", 200, "", `{}`, replicas.ErrConsoleUnreachable},
+ {"fenced", 409, "test", `{}`, replicas.ErrFenced},
+ {"success", 200, "test", `{}`, nil},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("X-Carlos-Version", tc.version)
+ w.WriteHeader(tc.code)
+ _, _ = w.Write([]byte(tc.body))
+ }))
+ defer server.Close()
+ api := &replicaCoordinatorAPI{base: server.URL, client: &http.Client{Timeout: time.Second}}
+ ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
+ defer cancel()
+ for _, op := range []string{"coordinator", "release", "retire-ack"} {
+ err := api.post(ctx, replicas.Identity{Host: "shop.example.com"}, op, struct{}{}, new(any))
+ if !errors.Is(err, tc.want) || tc.want == replicas.ErrConsoleUnreachable && errors.Is(err, replicas.ErrFenced) {
+ t.Fatalf("%s: %v, want %v", op, err, tc.want)
+ }
+ }
+ })
+ }
+ ctx, cancel := context.WithCancel(context.Background())
+ cancel()
+ api := &replicaCoordinatorAPI{base: "http://127.0.0.1:1", client: &http.Client{Timeout: time.Second}}
+ if err := api.post(ctx, replicas.Identity{}, "coordinator", struct{}{}, new(any)); !errors.Is(err, replicas.ErrConsoleUnreachable) {
+ t.Fatalf("transport error: %v", err)
+ }
+}
+
+func TestCoordinatorAPIReachabilityLogsTransitions(t *testing.T) {
+ var buf bytes.Buffer
+ old := log.Writer()
+ log.SetOutput(&buf)
+ defer log.SetOutput(old)
+ api := &replicaCoordinatorAPI{}
+ id := replicas.Identity{Host: "shop.example.com"}
+ for _, err := range []error{nil, replicas.ErrConsoleUnreachable, replicas.ErrConsoleUnreachable, nil, nil, replicas.ErrConsoleUnreachable} {
+ api.observe(id, err)
+ }
+ if strings.Count(buf.String(), "console unreachable=true") != 2 || strings.Count(buf.String(), "console unreachable=false") != 1 {
+ t.Fatalf("logs: %s", buf.String())
+ }
+}
diff --git a/internal/provision/testdata/plan14-root-reads-chain.tsv b/internal/provision/testdata/plan14-root-reads-chain.tsv
index 27c1c0c26..1446909d6 100644
--- a/internal/provision/testdata/plan14-root-reads-chain.tsv
+++ b/internal/provision/testdata/plan14-root-reads-chain.tsv
@@ -80,3 +80,4 @@ plan14-root-reads-managed-fleets-2a.tsv f85f8dabebc725fa75b88853af634fa9ca083237
plan14-root-reads-agent-start-demo-1.tsv 6ef1e3bc1dbacd5b548b1cbfe3a6d37bd5f701e03969feef2736212ee11713df
plan14-root-reads-region-ha-followups.tsv cfb026f1f9d59f325937cbddf26df2d94d5240d1f7846e80db713b8f6a15c387
plan14-root-reads-region-ha-p3a.tsv f44d209a054eee55fdee54227d419b74c34a9b2fc174c7a0bb74d5c2711a68bb
+plan14-root-reads-stateless-coordinator-route.tsv 7974cb078e82272605cbc8ef6809c9ae5e0b02edc22ca843cd2ef4b38d9e44e9
diff --git a/internal/provision/testdata/plan14-root-reads-stateless-coordinator-route.tsv b/internal/provision/testdata/plan14-root-reads-stateless-coordinator-route.tsv
new file mode 100644
index 000000000..dc178c490
--- /dev/null
+++ b/internal/provision/testdata/plan14-root-reads-stateless-coordinator-route.tsv
@@ -0,0 +1,16 @@
+# Census overlay stateless-coordinator-route, written by census-propose (#369). census-ruling-stateless-coordinator-route, Opus approved 7d072d77; refreshed for controller ruling P25 Fix round 1; the approval card is docs/superpowers/notes/census-proposal-stateless-coordinator-route.md.
+# Merge refresh: controller reports 92b24a7d census-approved; re-sealed on origin/main 3487d6f6 without a new review round.
+# 2 body, 0 sites, 6 envelope: each changed unit re-frozen at its existing disposition with its claim appended.
+# 1 new dispositions: 0 reads re-frozen at their disposition with the claim, 1 new units frozen accepted-legacy, 0 quiet units retired while they read nothing, 0 other.
+@legacy 15c6b5821dcca0a8c91804101b886494743deedb3310cf486c3fdb00d0124f27 internal/edge/edge.go Edge.ServeHTTP legacy accepted-legacy accepted-legacy;rev3=census-ruling-seeded-instances;basis=the edge inside the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): main's body with the import gate checked after the door's scope and a gated row left out of the response cache; serving only;rev3=census-ruling-edge-request-records;basis=one more call in the observer defer, observeRecords(up.route, ...), passing on the route the defer already holds; no new kind of read;rev3=census-ruling-design-edge-rate-limit-358;basis=calls rateAdmit twice, and an admitted request holds a slot on both paths: on the upgrade path before the activator or proxy (the handshake holds its slot through slotWriter, given back at the first final answer or at the reverse proxy's hijack on a 101, so an open WebSocket is not counted; released by a defer), and on the ordinary path after the response-cache check and before the activator and proxy (an admitted request holds a slot through slotWriter, released by a defer); a refusal is a 429 written there and returns; the upgrade path's comment now names slotWriter as its one wrapper; one comment on the door mark reworded; read sites unchanged (22: main's 21 plus edge-request-records' observeRecords pass of the route), offsets moved; no read added;rev3=census-ruling-plans-4c-box-throttle;basis=calls planThrottleAdmit before the response cache, and on an upgrade trackUpgrade then planUpgradeAdmit (plans 4c, Astra findings 1 and 2); the new reads live in those units (plans-4c-units decision). The same read sites here.;rev3=census-ruling-plans-4d-lapse;basis=calls planDisabledAdmit right after the import gate, passing the final upstream's route and the request host; a turned-off route gets the fixed disabled page before the meter, gate, cache and activator (plans 4d). The new read lives in that unit (plans-4d-units decision); one more whole-row pass here.;rev3=census-ruling-edge-protection-2;basis=runs the guard, a pure in-memory matcher on r.URL.Path and RawQuery (internal/edgeguard), once per request after the meter and observer defer and before the password gate, the upgrade branch, the cache and the activator, for a request that is not a door call, a backhauled door hop or a tunnel delivery; a matched block answers a 404 itself through guardDecide; the two new sites are one expression, up.route.Kind == "static" (a static route this box serves checks only the hard tier here and leaves the probe tier to serveTree), a read of the route row the edge already resolved; no new kind of read;rev3=census-ruling-edge-asset-cache-3;basis=the asset cache's three hooks (asset cache plan 3): the request's reserved asset headers are deleted at entry (the fill assertion kept only beside a verified hop); on the exact-remote and lookup-miss branches the far catch (serveAssetFar) is tried before backhaulTo and backhaul; after the observer defer and main's hard and probe checks, a verified hop with a valid fill assertion is answered by serveAssetFillForHop; after the upgrade branch and before gzip and the shared cache, the local catch (serveAssetLocal); the observer defer skips only the usage meter for an acknowledged home fill (out.unbilled); the new reads live in the new units of the edge-asset-cache-3-decisions overlay; the same route row and read sites (25); no read added;rev3=census-ruling-regional-domains-447;basis=#447 Task 5: straight after lookupUpstreamPath it calls regionalGate (regional.go), which for an entry built from a regional_domains row answers 503 to a hop or a deny entry before any arm that can leave the box (the exact-home backhaul, the far asset catch, the door dial, the miss backhaul), and lets a star match through only to the exact-home arm when ExactHome names another box for that distinct exact name; after the exact-home arm a regional deny entry the arm did not answer is refused (regionalRefuse, 503); refusals only, on the route map the edge already holds; read sites unchanged (25);rev3=census-ruling-static-headers;basis=the shared response cache is no longer looked up or filled for a static-kind route: one more read of the route row the edge already resolved (up.route.Kind == "static") in the cacheable expression; a refusal only, nothing new opened or followed;rev3=census-ruling-region-ha-p1b2;basis=region HA P1b-2 (N-HA10): one call, frontForwardHA, right after the route lookup's !ok block and before the login POST; same reads;rev3=census-ruling-fleet-public-routes;basis=fleet public routes (spec 2026-10-29 rev 4, §4.2 writer rule): Task 4: loginPost and cacheable treat a forward row as not this box's to answer (IsForward(), +whole:Route x2): no login form and no shared cache for a forward host. Serving only.;rev3=census-ruling-tunnel-websockets;basis=Deletes the Carlos-Upgrade marker header from incoming requests and puts the upgrade admission (host, path, the entry tenancy, all in hand) on a tunnel arm request. For a login POST on an ungated ArmTunnel row it reads the visitor request body (bounded by gate.MaxFormBody, 413 past it; a request body, not a file) and resolves next against the entry Reload built (Gate, Route); the bytes pass on only when loginPassesThrough holds (spec 7, Tasks 3, 5 and 6).;rev3=census-ruling-console-protection-tab;basis=one more call in the observer defer, observeGuardCount(up.route, out), beside the observeRecords call that files the guard Match: it passes on the route row the defer already holds (+whole:Route) and the request outcome to the usage meter, which counts the check in memory. Called whether or not the request was unbilled, as observeRecords is. Nothing is opened, read or followed; no new kind of read; no check, refusal or serving decision changes.;rev3=census-ruling-probe-burst-limit;basis=answers a probe-burst notice POST (serveBurstNotice) ahead of every route for a non-door caller; builds the guard state for up.route and stamps its account and app (RouteAccount, App) for the cool-down's this-app/other-app label; for a catalogue match on a non-static or tunnelled route, offers the burst rule (in-memory limiter, burstDecide: 429 or a watch verdict, never a block for a fleet or forward row); the observer defer calls noteBurst(up.route, ...); the added sites are the route value already in hand (+registry:App, +whole:Route x5); no new root read or write kind;rev3=census-ruling-edge-held-streams;basis=the edge in the agent (carlos-edge.service, user carlos): parses the request's query once (stripHoldMarker) to record the carlos_hold=1 mark in the request context; calls classifyHold on the upstream already resolved from the loaded map (the +whole:Route is that in-memory Route), including a second pass for a login POST; gives a marked request on a door-refused route the plain 404; adds the hold branch (planThrottleAdmit, rateAdmit, serveHeld) after the gate; and excludes marked requests from the shared cache. Reads only the request and the already-loaded upstream map; no registry or bucket read added.;rev3=census-ruling-region-ha-p3a;basis=Complete the P3a cut: an exact peer name with no dial target answers the approved admission 503 before local wildcard dispatch or asset serving. ExactHome and lookupHome stop fallback at a present non-dial entry; backhaulTo refuses an empty target before signing or dialing. Retain Task 3 local admission and fixed platform/unit exemptions. Two added whole Route uses feed the local in-memory admission predicate; existing Route values and store/path reads are unchanged.;rev3=census-ruling-stateless-coordinator-route;basis=P24/P25: POST only, exact /api/fleet/replicas/ prefix on the reserved tunnel host calls the existing local console proxy only for an unescaped, already-clean path; malformed forms remain on the hub. No new read sites relative to origin/main. Merge with main 3487d6f6 retains its region HA admission checks before routing and after login target lookup, its empty-home refusal, and their two existing whole:Route reads; these change this unit's digest relative to the previously approved branch tip 92b24a7d. file:ReadAll@15296,registry:App@21453,registry:Gate@14270,registry:Gate@25844,registry:Gate@25904,registry:Gate@25962,registry:Host@25947,registry:ImportGate@33347,registry:Kind@20315,registry:Kind@23753,registry:Kind@33289,registry:Kind@33318,whole:Route@14165,whole:Route@14276,whole:Route@17093,whole:Route@17877,whole:Route@18335,whole:Route@18527,whole:Route@20318,whole:Route@21379,whole:Route@21445,whole:Route@21456,whole:Route@21709,whole:Route@21804,whole:Route@21880,whole:Route@21924,whole:Route@22226,whole:Route@22256,whole:Route@23756,whole:Route@24041,whole:Route@25847,whole:Route@25907,whole:Route@25950,whole:Route@25965,whole:Route@26883,whole:Route@28946,whole:Route@33292,whole:Route@33321,whole:Route@33350,whole:Route@33382,whole:Route@35230,whole:Route@5457 c3f3a2b28a73c97c8e24bec12293d2a8ef9781337c966274dfa23f6f7758115a
+@legacy c5779f8357a6f496f695d25c9997b0b121b7fee7b10554aad613c84c15c2ec01 internal/rollout/scheduler.go scheduler.done legacy accepted-legacy accepted-legacy;rev3=J1,J4;basis=route-and-input;rev3=census-ruling-stateless-coordinator-route;basis=P25: classifies the preserved SwapResult.Err with errors.Is, including wrapped console-unreachable causes, to record the current scheduler revision and suppress duplicate abandoned logs. Diagnostic text no longer grants this classification. No new read sites or failure-book authority. file:Exec@5205,whole:Route@8410,whole:Route@8668,whole:Route@8826,whole:Route@8898,whole:Route@9017 be7a510e4735ea1770f9ef9e5c24e20d8991e826931ef6daab943428c866bda9
+@legacy f556651f876e3633ca8f37a367df46660c6d3dee4838e49d96321869de90e39f internal/edge/replicaconsole.go Edge.serveReplicaConsole legacy accepted-legacy accepted-legacy;rev3=census-ruling-stateless-coordinator-route;basis=Reads existing in-memory route fields to select a unique accountless console.service local upstream; refuses missing or ambiguous console, tenant routes, remote and tunnel upstreams. Reuses proxy and version wrapper; leaves fleet identity authentication at console. registry:Account@237,registry:App@257,registry:Host@178,registry:Socket@355,registry:Unit@280,whole:Route@159 dc98dc841eb2dc9b7f8f1e4a63a4b875c69c384b1af97ebfc5b563691362fa70
+internal/edge/edge.go Edge.ServeHTTP legacy accepted-legacy accepted-legacy;rev3=census-ruling-seeded-instances;basis=the edge inside the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): main's body with the import gate checked after the door's scope and a gated row left out of the response cache; serving only;rev3=census-ruling-edge-request-records;basis=one more call in the observer defer, observeRecords(up.route, ...), passing on the route the defer already holds; no new kind of read;rev3=census-ruling-design-edge-rate-limit-358;basis=calls rateAdmit twice, and an admitted request holds a slot on both paths: on the upgrade path before the activator or proxy (the handshake holds its slot through slotWriter, given back at the first final answer or at the reverse proxy's hijack on a 101, so an open WebSocket is not counted; released by a defer), and on the ordinary path after the response-cache check and before the activator and proxy (an admitted request holds a slot through slotWriter, released by a defer); a refusal is a 429 written there and returns; the upgrade path's comment now names slotWriter as its one wrapper; one comment on the door mark reworded; read sites unchanged (22: main's 21 plus edge-request-records' observeRecords pass of the route), offsets moved; no read added;rev3=census-ruling-plans-4c-box-throttle;basis=calls planThrottleAdmit before the response cache, and on an upgrade trackUpgrade then planUpgradeAdmit (plans 4c, Astra findings 1 and 2); the new reads live in those units (plans-4c-units decision). The same read sites here.;rev3=census-ruling-plans-4d-lapse;basis=calls planDisabledAdmit right after the import gate, passing the final upstream's route and the request host; a turned-off route gets the fixed disabled page before the meter, gate, cache and activator (plans 4d). The new read lives in that unit (plans-4d-units decision); one more whole-row pass here.;rev3=census-ruling-edge-protection-2;basis=runs the guard, a pure in-memory matcher on r.URL.Path and RawQuery (internal/edgeguard), once per request after the meter and observer defer and before the password gate, the upgrade branch, the cache and the activator, for a request that is not a door call, a backhauled door hop or a tunnel delivery; a matched block answers a 404 itself through guardDecide; the two new sites are one expression, up.route.Kind == "static" (a static route this box serves checks only the hard tier here and leaves the probe tier to serveTree), a read of the route row the edge already resolved; no new kind of read;rev3=census-ruling-edge-asset-cache-3;basis=the asset cache's three hooks (asset cache plan 3): the request's reserved asset headers are deleted at entry (the fill assertion kept only beside a verified hop); on the exact-remote and lookup-miss branches the far catch (serveAssetFar) is tried before backhaulTo and backhaul; after the observer defer and main's hard and probe checks, a verified hop with a valid fill assertion is answered by serveAssetFillForHop; after the upgrade branch and before gzip and the shared cache, the local catch (serveAssetLocal); the observer defer skips only the usage meter for an acknowledged home fill (out.unbilled); the new reads live in the new units of the edge-asset-cache-3-decisions overlay; the same route row and read sites (25); no read added;rev3=census-ruling-regional-domains-447;basis=#447 Task 5: straight after lookupUpstreamPath it calls regionalGate (regional.go), which for an entry built from a regional_domains row answers 503 to a hop or a deny entry before any arm that can leave the box (the exact-home backhaul, the far asset catch, the door dial, the miss backhaul), and lets a star match through only to the exact-home arm when ExactHome names another box for that distinct exact name; after the exact-home arm a regional deny entry the arm did not answer is refused (regionalRefuse, 503); refusals only, on the route map the edge already holds; read sites unchanged (25);rev3=census-ruling-static-headers;basis=the shared response cache is no longer looked up or filled for a static-kind route: one more read of the route row the edge already resolved (up.route.Kind == "static") in the cacheable expression; a refusal only, nothing new opened or followed;rev3=census-ruling-region-ha-p1b2;basis=region HA P1b-2 (N-HA10): one call, frontForwardHA, right after the route lookup's !ok block and before the login POST; same reads;rev3=census-ruling-fleet-public-routes;basis=fleet public routes (spec 2026-10-29 rev 4, §4.2 writer rule): Task 4: loginPost and cacheable treat a forward row as not this box's to answer (IsForward(), +whole:Route x2): no login form and no shared cache for a forward host. Serving only.;rev3=census-ruling-tunnel-websockets;basis=Deletes the Carlos-Upgrade marker header from incoming requests and puts the upgrade admission (host, path, the entry tenancy, all in hand) on a tunnel arm request. For a login POST on an ungated ArmTunnel row it reads the visitor request body (bounded by gate.MaxFormBody, 413 past it; a request body, not a file) and resolves next against the entry Reload built (Gate, Route); the bytes pass on only when loginPassesThrough holds (spec 7, Tasks 3, 5 and 6).;rev3=census-ruling-console-protection-tab;basis=one more call in the observer defer, observeGuardCount(up.route, out), beside the observeRecords call that files the guard Match: it passes on the route row the defer already holds (+whole:Route) and the request outcome to the usage meter, which counts the check in memory. Called whether or not the request was unbilled, as observeRecords is. Nothing is opened, read or followed; no new kind of read; no check, refusal or serving decision changes.;rev3=census-ruling-probe-burst-limit;basis=answers a probe-burst notice POST (serveBurstNotice) ahead of every route for a non-door caller; builds the guard state for up.route and stamps its account and app (RouteAccount, App) for the cool-down's this-app/other-app label; for a catalogue match on a non-static or tunnelled route, offers the burst rule (in-memory limiter, burstDecide: 429 or a watch verdict, never a block for a fleet or forward row); the observer defer calls noteBurst(up.route, ...); the added sites are the route value already in hand (+registry:App, +whole:Route x5); no new root read or write kind;rev3=census-ruling-edge-held-streams;basis=the edge in the agent (carlos-edge.service, user carlos): parses the request's query once (stripHoldMarker) to record the carlos_hold=1 mark in the request context; calls classifyHold on the upstream already resolved from the loaded map (the +whole:Route is that in-memory Route), including a second pass for a login POST; gives a marked request on a door-refused route the plain 404; adds the hold branch (planThrottleAdmit, rateAdmit, serveHeld) after the gate; and excludes marked requests from the shared cache. Reads only the request and the already-loaded upstream map; no registry or bucket read added.;rev3=census-ruling-region-ha-p3a;basis=Complete the P3a cut: an exact peer name with no dial target answers the approved admission 503 before local wildcard dispatch or asset serving. ExactHome and lookupHome stop fallback at a present non-dial entry; backhaulTo refuses an empty target before signing or dialing. Retain Task 3 local admission and fixed platform/unit exemptions. Two added whole Route uses feed the local in-memory admission predicate; existing Route values and store/path reads are unchanged.;rev3=census-ruling-stateless-coordinator-route;basis=P24/P25: POST only, exact /api/fleet/replicas/ prefix on the reserved tunnel host calls the existing local console proxy only for an unescaped, already-clean path; malformed forms remain on the hub. No new read sites relative to origin/main. Merge with main 3487d6f6 retains its region HA admission checks before routing and after login target lookup, its empty-home refusal, and their two existing whole:Route reads; these change this unit's digest relative to the previously approved branch tip 92b24a7d. file:ReadAll@15296,registry:App@21453,registry:Gate@14270,registry:Gate@25844,registry:Gate@25904,registry:Gate@25962,registry:Host@25947,registry:ImportGate@33347,registry:Kind@20315,registry:Kind@23753,registry:Kind@33289,registry:Kind@33318,whole:Route@14165,whole:Route@14276,whole:Route@17093,whole:Route@17877,whole:Route@18335,whole:Route@18527,whole:Route@20318,whole:Route@21379,whole:Route@21445,whole:Route@21456,whole:Route@21709,whole:Route@21804,whole:Route@21880,whole:Route@21924,whole:Route@22226,whole:Route@22256,whole:Route@23756,whole:Route@24041,whole:Route@25847,whole:Route@25907,whole:Route@25950,whole:Route@25965,whole:Route@26883,whole:Route@28946,whole:Route@33292,whole:Route@33321,whole:Route@33350,whole:Route@33382,whole:Route@35230,whole:Route@5457 c3f3a2b28a73c97c8e24bec12293d2a8ef9781337c966274dfa23f6f7758115a
+internal/rollout/scheduler.go scheduler.done legacy accepted-legacy accepted-legacy;rev3=J1,J4;basis=route-and-input;rev3=census-ruling-stateless-coordinator-route;basis=P25: classifies the preserved SwapResult.Err with errors.Is, including wrapped console-unreachable causes, to record the current scheduler revision and suppress duplicate abandoned logs. Diagnostic text no longer grants this classification. No new read sites or failure-book authority. file:Exec@5205,whole:Route@8410,whole:Route@8668,whole:Route@8826,whole:Route@8898,whole:Route@9017 be7a510e4735ea1770f9ef9e5c24e20d8991e826931ef6daab943428c866bda9
+internal/edge/replicaconsole.go Edge.serveReplicaConsole legacy accepted-legacy accepted-legacy;rev3=census-ruling-stateless-coordinator-route;basis=Reads existing in-memory route fields to select a unique accountless console.service local upstream; refuses missing or ambiguous console, tenant routes, remote and tunnel upstreams. Reuses proxy and version wrapper; leaves fleet identity authentication at console. registry:Account@237,registry:App@257,registry:Host@178,registry:Socket@355,registry:Unit@280,whole:Route@159 dc98dc841eb2dc9b7f8f1e4a63a4b875c69c384b1af97ebfc5b563691362fa70
+@coverage . 7e95942f29f593fab48b5c9759c445ab95481b6c9bc89ba80347c447b163745f
+@coverage internal/activator d4ca0f35d18e64c9d1949a3dc06891f1c2f039ae33b5c487091b30dd11eb4470
+@coverage internal/edge 18498e5c9a564504740b4189f771e9a74ca7bd0ced4c904f5e175327ea27531a
+@coverage internal/host 670f6dd1490bef1c33952075039a59ce17a20a4fc01878ceb6c2cbb4689c08f7
+@coverage internal/replicas f76f8a259d2d13f0225975171e6d97df4eec49eab6cb9d794e411500b0c91796
+@coverage internal/rollout 8df1b67e05ffb20872edc17e263385cb0119a44575f2e238cbd57485090cec80
diff --git a/internal/replicas/types.go b/internal/replicas/types.go
index c0f738ef6..9d45cff6d 100644
--- a/internal/replicas/types.go
+++ b/internal/replicas/types.go
@@ -41,6 +41,8 @@ type CoordinatorHeldError struct{ RetryAt time.Time }
func (e *CoordinatorHeldError) Error() string { return "replicas: coordinator held" }
+var ErrConsoleUnreachable = errors.New("console unreachable")
+
var ErrFenced = errors.New("replicas: fenced")
var ErrInvalid = errors.New("replicas: invalid transition")
diff --git a/internal/rollout/fake_test.go b/internal/rollout/fake_test.go
index 95a2529cb..f6e5c20d7 100644
--- a/internal/rollout/fake_test.go
+++ b/internal/rollout/fake_test.go
@@ -46,7 +46,8 @@ type fakeAct struct {
mode activator.SwapMode
// reason, when set, is a failed Swap's diagnostic text in place of
// "health check failed".
- reason string
+ reason string
+ resultErr error
// onHeldPublish, when set, runs on every PublishHeldServing: a test's
// view of the moment the scheduler releases a held worker publication.
onHeldPublish func(host string)
@@ -225,7 +226,10 @@ func (f *fakeAct) Swap(_ context.Context, a activator.Attempt, newest func(strin
if f.reason != "" {
reason = f.reason
}
- return activator.SwapResult{Outcome: out, Reason: reason, Mode: f.mode, Executed: executed}
+ if f.resultErr != nil {
+ reason = f.resultErr.Error()
+ }
+ return activator.SwapResult{Outcome: out, Reason: reason, Err: f.resultErr, Mode: f.mode, Executed: executed}
}
f.n++
g := activator.Gen{N: f.n, Build: a.Build, StagedPath: a.StagedPath, Digest: a.Digest, Demand: a.Demand}
diff --git a/internal/rollout/queue.go b/internal/rollout/queue.go
index 30c24e9bc..bee41720f 100644
--- a/internal/rollout/queue.go
+++ b/internal/rollout/queue.go
@@ -82,8 +82,9 @@ type hostSlot struct {
configAfter time.Time // a failed config attempt's backoff (spec §8.1)
notBefore time.Time // a staging refusal's wait (spec §4.2)
- running *dispatch
- buildRev uint64 // newest(host): moved only by a change of desired build
+ consoleUnreachableRev uint64
+ running *dispatch
+ buildRev uint64 // newest(host): moved only by a change of desired build
// forceBuilds are `carlos instances retry`'s canary entitlements, one per
// retried build: each lets the adoption onto its build through a halt,
// as a canary. Each is its build's, whatever the slot wants when the
diff --git a/internal/rollout/scheduler.go b/internal/rollout/scheduler.go
index 409650d3c..f14a6c08a 100644
--- a/internal/rollout/scheduler.go
+++ b/internal/rollout/scheduler.go
@@ -9,6 +9,7 @@ import (
"github.com/carlosframework/platform/internal/activator"
"github.com/carlosframework/platform/internal/registry"
"github.com/carlosframework/platform/internal/release"
+ "github.com/carlosframework/platform/internal/replicas"
)
// scheduler is one app's goroutine (spec §6.1). It runs off the agent's
@@ -344,6 +345,12 @@ func (s *scheduler) done(d dispatch, res activator.SwapResult, mode activator.Sw
s.q.rearmRetry(d)
}
h := s.q.hosts[d.ID.Host]
+ if h != nil && h.buildRev == d.SchedRev {
+ h.consoleUnreachableRev = 0
+ if res.Outcome == activator.SwapAbandoned && errors.Is(res.Err, replicas.ErrConsoleUnreachable) {
+ h.consoleUnreachableRev = d.SchedRev
+ }
+ }
if cfgCounted && h != nil && h.wantConfig == d.ID.ConfigRev {
s.q.configFailed(d.ID.Host, now.Add(cfgWait))
}
@@ -416,6 +423,9 @@ func (s *scheduler) done(d dispatch, res activator.SwapResult, mode activator.Sw
m.emit(rt, EvConfigPending, "warn", textConfigPending(reasonWord(res.Reason), cfgWait))
}
case activator.SwapAbandoned:
+ if errors.Is(res.Err, replicas.ErrConsoleUnreachable) {
+ return
+ }
m.d.Logf("rollout: %s: %s attempt onto %s abandoned: %s", d.ID.Host, d.ID.Cause, d.ID.Build, res.Reason)
}
}
diff --git a/internal/rollout/status.go b/internal/rollout/status.go
index b3c5f8df2..d347521cb 100644
--- a/internal/rollout/status.go
+++ b/internal/rollout/status.go
@@ -4,6 +4,7 @@ import (
"sort"
"github.com/carlosframework/platform/internal/activator"
+ "github.com/carlosframework/platform/internal/replicas"
"github.com/carlosframework/platform/internal/status"
)
@@ -132,6 +133,9 @@ func (m *Manager) Status() status.RolloutReport {
}
}
}
+ if hr.HeldBy == "" && h.consoleUnreachableRev != 0 && h.consoleUnreachableRev == h.buildRev {
+ hr.Reason = replicas.ErrConsoleUnreachable.Error()
+ }
r.Hosts[host] = hr
}
s.mu.Unlock()
diff --git a/internal/rollout/status_test.go b/internal/rollout/status_test.go
index 0cf4333ca..3d6cc73a1 100644
--- a/internal/rollout/status_test.go
+++ b/internal/rollout/status_test.go
@@ -2,6 +2,7 @@ package rollout
import (
"context"
+ "fmt"
"runtime"
"strings"
"sync"
@@ -11,6 +12,7 @@ import (
"github.com/carlosframework/platform/internal/activator"
"github.com/carlosframework/platform/internal/release"
+ "github.com/carlosframework/platform/internal/replicas"
"github.com/carlosframework/platform/internal/status"
)
@@ -366,3 +368,26 @@ func TestStatusCallsAHostThatJoinedAfterTheNamesWereReadTransient(t *testing.T)
t.Fatalf("a = %+v, want awake on v1", a)
}
}
+
+func TestStatusReportsConsoleUnreachableUntilRecovery(t *testing.T) {
+ h := newHarness(t, "a")
+ h.stage("v2")
+ h.act.resultErr = fmt.Errorf("acquire coordinator: %w", replicas.ErrConsoleUnreachable)
+ var recovered atomic.Bool
+ h.act.outcome = func(activator.Attempt) activator.SwapOutcome {
+ if recovered.Load() {
+ return activator.SwapDone
+ }
+ return activator.SwapAbandoned
+ }
+ h.install("v2", "a")
+ h.pass()
+ waitFor(t, "console unreachable reason", func() bool { return h.m.Status().Hosts["a"].Reason == replicas.ErrConsoleUnreachable.Error() })
+ if row := h.m.Status().Hosts["a"]; row.Serving != "v1" || row.HeldBy != "" || len(h.book.List()) != 0 {
+ t.Fatalf("unreachable changed serving or held build: %+v", row)
+ }
+ recovered.Store(true)
+ h.advance(abandonDeferral + time.Second)
+ h.pass()
+ waitFor(t, "recovery", func() bool { row := h.m.Status().Hosts["a"]; return row.Serving == "v2" && row.Reason == "" })
+}