carlos / platform Public

feat: probe copies on the box without waking them

Read copy identity and serving-generation evidence through held-leg
admission, and probe the app socket only on the private tunnel landing.
Refuse public, door and backhaul probes and scrub the private marker.

Add the private replica-health Unix socket with bounded shutdown and
an empty snapshot source for slice 1b. Leave hub probing and routing,
HA behavior and the combined Task 1 census review to their owners.
Co-Authored-By: Codex (gpt-6-astra) <noreply@openai.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev df6b2f8228d7fc31f647f2bb726f6b485c75cbbe parent 6209ce4
12 files changed, +881 −0
  • internal/activator/replicaprobe.go +64 −0
  • internal/activator/replicaprobe_test.go +94 −0
  • internal/edge/edge.go +7 −0
  • internal/edge/replicaprobe.go +96 −0
  • internal/edge/replicaprobe_test.go +243 −0
  • internal/host/agent.go +13 −0
  • internal/host/replicahealth_linux.go +109 −0
  • internal/host/replicahealth_linux_test.go +184 −0
  • internal/host/replicahealth_other.go +17 −0
  • internal/replicas/health.go +39 −0
  • internal/replicas/health_test.go +12 −0
  • internal/tunnelclient/tunnelclient.go +3 −0

Intent

Human

<task-notification> <task-id>a2b356e8b1ad6bce4</task-id> <tool-use-id>toolu_01BtW8okY1duEPcKVr5bLo1B</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/195ef15b-aac6-42d6-b49b-41ffb7a4abbc/tasks/a2b356e8b1ad6bce4.output</output-file> <status>completed</status> <summary>Agent "Plan 3 preflight conflict scan" 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>The scan is written to `/home/paulca/amadan.net/carlos/platform/.claude/worktrees/stateless-replicas-3/.superpowers/sdd/2026-11-01-stateless-replicas-3-routing/preflight-scan.md` (85 lines: four tables and nine proposed rulings). The five most important findings: 1. **Hub routing of replica rows is already wrong on main, though not yet released.** Plan 2 clears the single-box label on every row that carries a set of boxes, and the edge never looks at the set. So the hub sends a copies=1 stateless app to whichever connected box sorts first, which may not be the assigned box. That box then refuses the request. Ruling R1: Plan 3 must close this before any release is cut from a main that contains 6209ce43, or a small guard lands first. 2. **`TestLegacyFleetRoutingUnchanged` does not exist on main.** The plan says to keep its "unlabelled fallback" assertions, but replica rows are now unlabelled rows. A test written after the code would lock in the very fallback Plan 3 has to remove. 3. **Reuse what main already has.** - The activator's held-stream admission (`AdmitHeldLeg` / `HeldAdmissible` in `internal/activator/heldlegs.go`) already answers "awake on the current generation" without waking anything or counting as activity. `ProbeCopy` should build on it. - The existing header-stripping points (`edge.go:1968`, `scrubTunnelMarkers` at `:3738`) should strip the new probe marker too. - Status `replica_copies` should follow the existing `Probes.Upstreams` route rather than adding a field to `BoxMetrics`. - A separate replica prober and proxy are justified, because the start state, concurrency and retry point all differ. But the shared fail/rise counting and the proxy setup code should be factored out, or review will flag them as duplicates. 4. **Region HA P3a overlap.** Group admission now refuses requests near the top of `ServeHTTP`. The plan puts the private probe path "before normal host gates"; it must come after the admission check, or a box with admission closed reports healthy. HA's forwarding, admission and load-balancer health code must stay byte-identical. `edge.go`, `host/agent.go` and `activator.go` are edited by both workstreams. The owner agreement the index requires is still not on record (R8). 5. **Plan defects.** - Task 3's edits to `fleetbind.go` and `provision/forward.go` are already done by Plan 2, so they would be empty diffs. - Task 3's console join in `apiinstances.go` collides with Plan 4.3, which owns that field. - Copy row SR-3-C08 points at `console/replicaview.go`, which no task creates. - Task 2 has no file for `RetryAllowed` and no `reqrec` fields for the box and attempt tags. - Task 1's security tests (forged marker sent through the public hub, socket permissions) have no names, and its test command never runs the host package. - The snapshot socket is readable only by the agent's user; it is not known which user `console.service` runs as. Check that on dev before building (R7). I made no code changes and no commits; the scan file is the only thing written.</result> <usage><subagent_tokens>187078</subagent_tokens><tool_uses>57</tool_uses><duration_ms>510194</duration_ms></usage> </task-notification>

Human

<paseo-system version="1" kind="agent-message" source-agent-id="78223e69-0073-4772-bcd6-25641b472a31" message-id="4e2b0c6d-c8c0-4552-8441-fddf111e49bc" source-agent-title="Region HA P3a dev rollout (executing approved card)"> P3a window CLOSED (09:00Z); the dev channel freeze is lifted. Dev is on v0.34.1. sophie and leo now run with CARLOS_GROUP_ADMISSION=1 behind dev NLB carlos-dev-ie-nlb (EIPs 54.77.110.223 / 18.203.21.74). Details on #421. Any future host.env edit on sophie or leo should back up first and expect the edge restart to close tenant routes for ~30 s while admission opens. </paseo-system>

Human

<paseo-system version="1" kind="agent-message" source-agent-id="8a3d302a-eac7-407c-b61c-f5ccc66b5544" message-id="3fbcb991-7d66-4a19-a45e-8ddddc4e83a7"> From the agent manager (8a3d302): the region HA P3a dev window closed at 09:00Z, and dev runs v0.34.1, which includes the coordinator fix. So the Plan 1 fleet smoke rerun can go first, with no release needed (the Plan 2 controller appended this to your HANDOFF.md). It&apos;s a dev smoke on the existing fleet box: run it, and tell me before any change to box config or any restart. </paseo-system>

Human

<task-notification> <task-id>a430a06046b52f7fc</task-id> <tool-use-id>toolu_01MPKLHyGykwAT6JuLNFfG2Y</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/195ef15b-aac6-42d6-b49b-41ffb7a4abbc/tasks/a430a06046b52f7fc.output</output-file> <status>completed</status> <summary>Agent "Plan 1 fleet smoke rerun on dev" is waiting on its own background work</summary> <note>This agent stopped with background work of its own still running. It may resume on its own when that work completes or reports, and the same task-id notifies again if it does; the result below may be interim.</note> <result>Waiting on the monitor notification.</result> <usage><subagent_tokens>129209</subagent_tokens><tool_uses>83</tool_uses><duration_ms>707905</duration_ms></usage> </task-notification>

Human

<task-notification> <task-id>a430a06046b52f7fc</task-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/195ef15b-aac6-42d6-b49b-41ffb7a4abbc/tasks/a430a06046b52f7fc.output</output-file> <status>completed</status> <summary>Agent "Plan 1 fleet smoke rerun on dev" 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>**FAIL.** The fix for F1 works, but a stateless release still never deploys on fleet r10r, now for a different reason (F8). The old build kept serving the whole time, so nothing broke. Full evidence is in `/home/paulca/.cache/sr-plan1-smoke/fleet-evidence.md`. The sample app source is in `/home/paulca/.cache/sr-plan1-smoke/sample-app/`. **Two deviations from the brief:** - **App name:** I used `statelesssmokef` instead of `statelesssmoke`. The first run's app is still in the trash with its old database data left on the box and in S3. Restoring it would have mixed that data into this run. - **Console:** this machine's default console is flagship (console.carloku.com). I pinned dev in a scratch config and checked it before running anything. Nothing touched flagship. The first run didn't pass `--console`, which is worth knowing for future dev smokes. **Steps:** - **Precheck: PASS.** A test call to the replicas path on the tunnel host now reaches the console (it carries the console's version header). The forwarding code returns a bare 503 when it finds zero or several console routes, so exactly one was found. No CLI command lists those routes, so this test call was the check. - **Step 1 (stateful s1): PASS.** It served `build=s1` with `CARLOS_DB` set and `/hit` counted hits. On the box: the `.db` file was 4096 bytes (sha256 starting 52a37144). Litestream was syncing and `lock.json` was held by box-1. - **Step 2 (s2 `--stateless`): FAIL.** - From 09:05:57 to 09:19:47 box-1 logged `release attempt onto s2 abandoned: replicas: fenced` every 15 seconds, 54 times in all. - `instances list` showed INSTALLED s2, SERVING s1, REASON "rolling out". Every GET answered `build=s1`. - **Steps 3, 4 and 5: not run.** s2 never started, so the stateless copy, worker, release command (pass and fail), `carlos run`, interactive session, restart and the stateful-to-stateless switch are still unproven on a fleet. - **Step 6 (`--copies 2` refused): PASS.** The v0.34.1 CLI answers `flag provided but not defined: -copies` (exit 2). - **Step 7 (no other app changed): PASS.** All nine baseline apps are unchanged apart from hibernating apps idling, which is normal. Shop is still v4; railsdemo is still held at r4 and serving r3b. - **Step 8 (cleanup): PASS.** - The instance is deleted, the app is in the trash and the host answers 503. - No smoke process remains on box-1 and the retry loop stopped. - Local scratch is deleted. - As in the first run, the data dir, the empty slice unit, the S3 prefix and the fleet binding stay until the purge. **Findings:** - **F8 (new, P1, blocks Plan 1 on fleets):** - The console only accepts a replica coordinator call if the instance's record names the calling box (`fleet_box`). The check is in `replicaFleetRecord`, `internal/console/replicacoordinator.go`, and the v0.34.1 tag has it too. - A new record only gets that label from the console's 5-minute relabel pass. That pass needs two or more active boxes in the fleet, and r10r has only box-1 (box-2 is detached). - So the record never got labelled, even though its binding names box-1. I watched it from 09:10 to 09:19, at least two passes. - The console then answers 404, and the box reads any non-200 from the console as "fenced", indefinitely. - Possible fixes (none made): accept the box named by the binding, or the fleet's only active box; or label the record when the instance is created. Main's version of the check also accepts replica-assignment members, so it's worth checking whether Plan 2's placement writes an assignment on a one-box fleet. - **F1:** fixed. - **F1b:** still reproduces. When the console refuses the call, the owner only sees "starting build s2" and "rolling out", with no cause. - **F3:** still reproduces. `--size small` on the fleet app was refused, citing dennis-stenciling's memory. - **F4:** still reproduces. The fleet create printed "Region: Dublin (IE), from your timezone". - **F5:** not observed. It needs a serving stateless copy, which never happened. - **F7:** still reproduces. "wake failed: … could not be installed" was logged at 09:04:51, before the instance served. - **F9 (new, cosmetic):** after the delete, the worker's unit on box-1 is left in `failed (Result: signal)`. Resetting it would be a change on the box, so I left it. Nothing needed a box config change, edge or box restart, or infrastructure change. All box and S3 reads were read-only (SSM and `s3 ls`/`cp`, profile kass). The Go build needed the sandbox lifted once, because the default Go cache is read-only inside the sandbox. Copying the report into `~/.cache/sr-plan1-smoke` needed it lifted once too.</result> <usage><subagent_tokens>140971</subagent_tokens><tool_uses>90</tool_uses><duration_ms>1287112</duration_ms></usage> </task-notification>

Attributed to this commit: 34.3 g CO₂e (3,779,357 tokens). This is an attribution, not a measurement — usage counted from this commit's own marker forward to the next one on stateless-replicas-3-routing, 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/internal/activator/replicaprobe.go b/internal/activator/replicaprobe.go
new file mode 100644
index 000000000..eaf944047
--- /dev/null
+++ b/internal/activator/replicaprobe.go
@@ -0,0 +1,64 @@
+package activator
+
+import (
+ "context"
+ "time"
+
+ "github.com/carlosframework/platform/internal/registry"
+ "github.com/carlosframework/platform/internal/replicas"
+)
+
+// ProbeCopy reads the already-serving copy. It cannot join a wake, start a
+// process, acquire authority, read a bucket, or record activity.
+func (a *Service) ProbeCopy(ctx context.Context, host string) (replicas.Copy, error) {
+ if err := ctx.Err(); err != nil {
+ return replicas.Copy{}, err
+ }
+ a.mu.Lock()
+ defer a.mu.Unlock()
+ e := a.entries[host]
+ if !a.heldAdmissibleLocked(e) {
+ return replicas.Copy{}, ErrHeldAsleep
+ }
+ rt := e.route
+ if rt.FleetBoxes == "" || !rt.ValidReplicaProjection() || rt.Kind != "instance" || rt.Hibernate || rt.HA || !e.gen.Stateless || a.Routes == nil {
+ return replicas.Copy{}, ErrFenced
+ }
+ // The registry is the reconciler's local assignment projection. Never
+ // call currentWakeRoute here: its fresh record check reads the bucket.
+ now, err := a.Routes.Get(host)
+ if err != nil || now == nil || wakeRouteChanged(rt, *now, false) != nil || now.ReplicaIncarnation != rt.ReplicaIncarnation || now.Region != rt.Region || now.Incarnation != rt.Incarnation || !now.Stateless || now.Hibernate || now.HA {
+ return replicas.Copy{}, ErrFenced
+ }
+ // Membership may change while this generation stays assigned. Report
+ // the current revision, but never relabel a process across lifetimes.
+ rt = *now
+ fleet, placed := registry.FleetPlacement(rt.Region)
+ coord, ok := a.Coordinator.(*CoordinationClient)
+ if !placed || a.Fleet.Mode != FleetWakeCheck || a.Fleet.Fleet != fleet || !rt.ReplicaContains(a.Fleet.Label) || !ok || coord.box != a.Fleet.Label || coord.boot == "" {
+ return replicas.Copy{}, ErrFenced
+ }
+ g := e.gen
+ if g.Socket == "" || g.N == 0 || g.Build == "" || g.Digest == "" {
+ return replicas.Copy{}, ErrFenced
+ }
+ c := replicas.Copy{Host: host, Account: rt.Account, App: rt.App, Fleet: fleet,
+ Box: a.Fleet.Label, BootID: coord.boot, Incarnation: rt.ReplicaIncarnation,
+ AssignmentRevision: rt.ReplicaRevision, Generation: g.N,
+ Version: g.Build, Digest: g.Digest, Socket: g.Socket, State: "running", ObservedAt: time.Now()}
+ for _, wk := range e.rootfsWorkers {
+ if wk.gen == g.N {
+ c.WorkersDeclared++
+ if !wk.starting && wk.proc != nil && !wk.startFailed && !workerEnded(wk.proc) {
+ c.WorkersRunning++
+ }
+ }
+ }
+ if e.sidecarWanted {
+ c.WorkersDeclared++
+ if e.sidecarGen == g.N && e.sidecar != nil && !e.sidecar.Exited() {
+ c.WorkersRunning++
+ }
+ }
+ return c, nil
+}
diff --git a/internal/activator/replicaprobe_test.go b/internal/activator/replicaprobe_test.go
new file mode 100644
index 000000000..218feef33
--- /dev/null
+++ b/internal/activator/replicaprobe_test.go
@@ -0,0 +1,94 @@
+package activator
+
+import (
+ "context"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/provision"
+ "github.com/carlosframework/platform/internal/registry"
+ "github.com/carlosframework/platform/internal/replicas"
+)
+
+func replicaProbeFixture(t *testing.T) (*Service, *fakeBackend, registry.Route) {
+ t.Helper()
+ a, b, _, _ := testActivator(t, time.Hour)
+ rt := testRoute("shop.example.com")
+ rt.Account, rt.App, rt.Region = "bab", "shop", "fleet/pi"
+ rt.Hibernate, rt.Stateless = false, true
+ rt.FleetBoxes, rt.Copies, rt.ReplicaRevision, rt.ReplicaIncarnation = `["a","b"]`, 2, 7, "life"
+ a.Routes = startupRoutes{rt.Host: rt}
+ a.Fleet = FleetWake{Mode: FleetWakeCheck, Fleet: "pi", Label: "a", Record: func(context.Context, registry.Route) (*provision.Record, error) {
+ t.Fatal("probe read bucket")
+ return nil, nil
+ }}
+ a.Coordinator = NewCoordinatorClient("a", "boot", func(context.Context, replicas.Identity, replicas.CoordinatorChange) (replicas.CoordinatorReply, error) {
+ t.Fatal("probe acquired authority")
+ return replicas.CoordinatorReply{}, nil
+ }, nil)
+ // Install launch evidence directly: the probe fixture never wakes.
+ a.entries[rt.Host] = &actEntry{host: rt.Host, route: rt, state: actAwake,
+ proc: &fakeProc{label: "instance", rec: b}, lastActive: time.Unix(1, 0),
+ gen: Gen{N: 12, Stateless: true, Socket: "/unused/serving.sock", Build: "v1", Digest: "digest"}}
+ return a, b, rt
+}
+
+func TestReplicaProbeNeverWakes(t *testing.T) {
+ for _, state := range []string{"running", "asleep", "down", "hibernating", "waking", "fenced", "probe-held", "shutdown", "stateful", "legacy", "old-lifetime", "new-revision", "wrong-account", "removed", "unknown-fleet", "cancelled"} {
+ t.Run(state, func(t *testing.T) {
+ a, b, rt := replicaProbeFixture(t)
+ e := a.entries[rt.Host]
+ ctx, cancel := context.WithCancel(t.Context())
+ defer cancel()
+ switch state {
+ case "asleep":
+ delete(a.entries, rt.Host)
+ case "down":
+ e.proc.(*fakeProc).dead = true
+ case "hibernating":
+ e.state = actStopping
+ case "waking":
+ e.state = actWaking
+ case "fenced":
+ a.fences = map[string]uint64{rt.Host: 1}
+ case "probe-held":
+ e.probeHeld = true
+ case "shutdown":
+ a.shuttingDown = true
+ case "stateful":
+ e.gen.Stateless = false
+ case "legacy":
+ e.route.FleetBoxes = ""
+ case "old-lifetime":
+ rt.ReplicaIncarnation = "new"
+ case "new-revision":
+ rt.ReplicaRevision++
+ case "wrong-account":
+ rt.Account = "other"
+ case "removed":
+ rt.FleetBoxes = `["b"]`
+ case "unknown-fleet":
+ a.Fleet.Mode = FleetWakeUnknown
+ case "cancelled":
+ cancel()
+ }
+ a.Routes = startupRoutes{rt.Host: rt}
+ c, err := a.ProbeCopy(ctx, rt.Host)
+ if (err == nil) != (state == "running" || state == "new-revision") {
+ t.Fatalf("copy=%+v err=%v", c, err)
+ }
+ if state == "new-revision" && c.AssignmentRevision != 8 {
+ t.Fatalf("current revision=%d", c.AssignmentRevision)
+ }
+ if state == "running" && (c.Host != rt.Host || c.Box != "a" || c.BootID != "boot" || c.Incarnation != "life" || c.AssignmentRevision != 7 || c.Generation != 12 || c.Version != "v1" || c.Digest != "digest" || c.State != "running" || c.Healthy || c.Socket != e.gen.Socket) {
+ t.Fatalf("evidence=%+v", c)
+ }
+ if acquires, restores, starts := b.counts(); acquires != 0 || restores != 0 || starts != 0 {
+ t.Fatalf("probe woke: %d/%d/%d", acquires, restores, starts)
+ }
+ if e.inflight != 0 || e.lastActive != time.Unix(1, 0) || len(e.heldLegs) != 0 {
+ t.Fatal("probe recorded activity")
+ }
+ })
+ }
+}
diff --git a/internal/edge/edge.go b/internal/edge/edge.go
index 0e863a711..b8ccca2c4 100644
--- a/internal/edge/edge.go
+++ b/internal/edge/edge.go
@@ -1970,10 +1970,16 @@ func (e *Edge) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// is this hub's to send, and only on a stream its upgrade branch
// admitted: never a client's, on any arm.
r.Header.Del(tunnelclient.UpgradeHeader)
+ replicaProbe := replicaProbeAuthenticated(r) && !isDoor && !hopPresent
+ r.Header.Del(tunnelclient.ReplicaProbeHeader)
up, ok := e.lookupUpstreamPath(host, r.URL.Path)
if ok && e.admissionRefuses(w, r, up.route) {
return
}
+ if r.URL.Path == replicaProbePath {
+ e.serveReplicaProbe(w, r, host, up.route, replicaProbe)
+ return
+ }
// GeoIP steps 3-4 (geoip spec §8.1, §8.2): decide once, keep it on the
// context for setGeo and analytics, and expose the app-visible headers on
// r.Header so the cache's Vary matching sees exactly what the app will
@@ -3738,6 +3744,7 @@ func tunnelUpgradeError(w http.ResponseWriter, r *http.Request, err error, hub *
func scrubTunnelMarkers(pr *httputil.ProxyRequest) {
pr.Out.Header.Del(tunnelclient.UpgradeHeader)
pr.Out.Header.Del(tunnelclient.UpgradedHeader)
+ pr.Out.Header.Del(tunnelclient.ReplicaProbeHeader)
}
// errFleetDark is the sentinel fleetProxy's Transport returns when fleet has
diff --git a/internal/edge/replicaprobe.go b/internal/edge/replicaprobe.go
new file mode 100644
index 000000000..5b44a38a5
--- /dev/null
+++ b/internal/edge/replicaprobe.go
@@ -0,0 +1,96 @@
+package edge
+
+import (
+ "context"
+ "encoding/json"
+ "io"
+ "net"
+ "net/http"
+ "time"
+
+ "github.com/carlosframework/platform/internal/registry"
+ "github.com/carlosframework/platform/internal/replicas"
+ "github.com/carlosframework/platform/internal/tunnelclient"
+)
+
+const replicaProbePath = "/__carlos/replica-probe"
+const replicaProbeTimeout = time.Second
+
+// ReplicaHealth is the hub's current assignment-scoped health view.
+type ReplicaHealth interface {
+ Snapshot(host string) replicas.Snapshot
+}
+
+type copyProbeSource interface {
+ ProbeCopy(context.Context, string) (replicas.Copy, error)
+}
+
+func (e *Edge) serveReplicaProbe(w http.ResponseWriter, r *http.Request, host string, rt registry.Route, authenticated bool) {
+ w.Header().Set("Cache-Control", "no-store")
+ if !authenticated || r.Method != http.MethodGet || r.URL.RawQuery != "" {
+ w.WriteHeader(http.StatusNotFound)
+ return
+ }
+ source, ok := e.act.(copyProbeSource)
+ if !ok || rt.Host != host || rt.Kind != "instance" || rt.FleetBoxes == "" || !rt.ReplicaContains(e.box) || rt.Hibernate || rt.HA {
+ w.WriteHeader(http.StatusServiceUnavailable)
+ return
+ }
+ ctx, cancel := context.WithTimeout(r.Context(), replicaProbeTimeout)
+ defer cancel()
+ initial, err := source.ProbeCopy(ctx, host)
+ if err != nil || !e.replicaCopyMatches(initial, rt) {
+ w.WriteHeader(http.StatusServiceUnavailable)
+ return
+ }
+ // A held leg is cancelled on stop or generation switch, without keeping
+ // the instance awake or entering request accounting. Check awake first
+ // so a sleeping or waking copy never enters the held-leg wait loop.
+ leg, err := e.act.AdmitHeldLeg(ctx, rt)
+ if err != nil {
+ w.WriteHeader(http.StatusServiceUnavailable)
+ return
+ }
+ defer leg.Done()
+ c, err := source.ProbeCopy(leg.Context(), host)
+ if err != nil || !e.replicaCopyMatches(c, rt) || c.Generation != initial.Generation || c.Socket != initial.Socket {
+ w.WriteHeader(http.StatusServiceUnavailable)
+ return
+ }
+ transport := &http.Transport{DisableKeepAlives: true, DisableCompression: true,
+ DialContext: func(ctx context.Context, _, _ string) (net.Conn, error) {
+ return (&net.Dialer{}).DialContext(ctx, "unix", c.Socket)
+ }}
+ defer transport.CloseIdleConnections()
+ probe, _ := http.NewRequestWithContext(leg.Context(), http.MethodGet, "http://"+host+"/", nil)
+ // RoundTrip never follows redirects. A fresh request carries no visitor
+ // credentials or probe marker, and bypasses every edge gate and cache.
+ resp, probeErr := transport.RoundTrip(probe)
+ if resp != nil {
+ _, _ = io.CopyN(io.Discard, resp.Body, 4<<10)
+ _ = resp.Body.Close()
+ c.Healthy = probeErr == nil && replicas.HealthyStatus(resp.StatusCode)
+ }
+ after, err := source.ProbeCopy(leg.Context(), host)
+ if err != nil || leg.Context().Err() != nil || !e.replicaCopyMatches(after, rt) || after.Generation != c.Generation || after.Socket != c.Socket || after.BootID != c.BootID || after.Version != c.Version || after.Digest != c.Digest {
+ w.WriteHeader(http.StatusServiceUnavailable)
+ return
+ }
+ if !c.Healthy {
+ // copy SR-3-C03 (provisional)
+ c.Reason = "this copy did not pass its health check"
+ }
+ c.ObservedAt = time.Now()
+ w.Header().Set("Content-Type", "application/json")
+ _ = json.NewEncoder(w).Encode(c)
+}
+
+func (e *Edge) replicaCopyMatches(c replicas.Copy, rt registry.Route) bool {
+ fleet, ok := registry.FleetPlacement(rt.Region)
+ return ok && c.Fleet == fleet && c.Host == rt.Host && c.Account != "" && c.Account == rt.Account && c.App != "" && c.App == rt.App && c.Box == e.box && rt.ReplicaContains(c.Box) && c.Incarnation == rt.ReplicaIncarnation && c.AssignmentRevision == rt.ReplicaRevision && c.State == "running" && c.BootID != "" && c.Generation != 0 && c.Version != "" && c.Digest != "" && c.Socket != ""
+}
+
+// The context mark alone also accompanies ordinary visitor traffic.
+func replicaProbeAuthenticated(r *http.Request) bool {
+ return tunnelclient.FromTunnel(r.Context()) && r.Header.Get(tunnelclient.ReplicaProbeHeader) == "1"
+}
diff --git a/internal/edge/replicaprobe_test.go b/internal/edge/replicaprobe_test.go
new file mode 100644
index 000000000..f91df8379
--- /dev/null
+++ b/internal/edge/replicaprobe_test.go
@@ -0,0 +1,243 @@
+package edge
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "net/http/httputil"
+ "path/filepath"
+ "strings"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/registry"
+ "github.com/carlosframework/platform/internal/replicas"
+ "github.com/carlosframework/platform/internal/tunnelclient"
+)
+
+type replicaProbeLeg struct{ ctx context.Context }
+
+func (l replicaProbeLeg) Context() context.Context { return l.ctx }
+func (l replicaProbeLeg) Done() {}
+
+type replicaProbeAct struct {
+ *genActivator
+ copy replicas.Copy
+ probes int
+ onProbe func()
+}
+
+func (a *replicaProbeAct) ProbeCopy(context.Context, string) (replicas.Copy, error) {
+ a.probes++
+ if a.onProbe != nil {
+ a.onProbe()
+ }
+ return a.copy, nil
+}
+func (a *replicaProbeAct) AdmitHeldLeg(ctx context.Context, _ registry.Route) (HeldLeg, error) {
+ return replicaProbeLeg{ctx}, nil
+}
+
+func replicaLanding(t *testing.T, h http.Handler) (*Edge, *replicaProbeAct) {
+ t.Helper()
+ dir := genSockDir(t)
+ app := startGenApp(t, filepath.Join(dir, "serving.sock"), h)
+ reg := openReg(t)
+ rt := registry.Route{Host: "shop.example.com", Kind: "instance", Status: "ready", Account: "bab", App: "shop", Region: "fleet/pi", Stateless: true, FleetBoxes: `["a","b"]`, Copies: 2, ReplicaRevision: 7, ReplicaIncarnation: "life", Socket: filepath.Join(dir, "wrong.sock")}
+ if err := reg.Upsert(rt); err != nil {
+ t.Fatal(err)
+ }
+ act := &replicaProbeAct{genActivator: &genActivator{fakeGens: newFakeGens(true)}, copy: replicas.Copy{Host: rt.Host, Account: rt.Account, App: rt.App, Fleet: "pi", Box: "a", BootID: "boot", Incarnation: "life", AssignmentRevision: 7, Generation: 12, Version: "v1", Digest: "digest", State: "running", Socket: app.sock}}
+ e, err := New(reg, act)
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(e.probers.Stop)
+ e.box = "a"
+ return e, act
+}
+
+func replicaRequest(t *testing.T, handler http.Handler, marker string) *httptest.ResponseRecorder {
+ t.Helper()
+ r := httptest.NewRequest(http.MethodGet, "http://shop.example.com"+replicaProbePath, nil)
+ r.Header.Set(tunnelclient.ReplicaProbeHeader, marker)
+ r.Header.Set("Authorization", "Bearer secret")
+ w := httptest.NewRecorder()
+ handler.ServeHTTP(w, r)
+ if strings.Contains(w.Body.String(), "secret") || strings.Contains(w.Body.String(), ".sock") {
+ t.Fatal("private data in reply")
+ }
+ return w
+}
+
+func TestReplicaProbeLandingRefusesPublic(t *testing.T) {
+ var hits atomic.Int64
+ e, act := replicaLanding(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { hits.Add(1); w.WriteHeader(200) }))
+ if w := replicaRequest(t, e, "1"); w.Code != 404 {
+ t.Fatalf("public forged marker: %d", w.Code)
+ }
+ if w := replicaRequest(t, tunnelclient.Mark(e), ""); w.Code != 404 {
+ t.Fatalf("tunnel without marker: %d", w.Code)
+ }
+ if w := replicaRequest(t, tunnelclient.Mark(e), "2"); w.Code != 404 {
+ t.Fatalf("wrong marker: %d", w.Code)
+ }
+ for _, ingress := range []string{"door", "backhaul"} {
+ h := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if ingress == "door" {
+ r = r.WithContext(context.WithValue(r.Context(), doorCallerKey{}, doorCaller{"bab", "shop"}))
+ } else {
+ r.Header.Set(hopHeader, "forged")
+ }
+ e.ServeHTTP(w, r)
+ })
+ if w := replicaRequest(t, tunnelclient.Mark(h), "1"); w.Code != 404 {
+ t.Fatalf("%s: %d", ingress, w.Code)
+ }
+ }
+ // A PUBLIC hub route must refuse before its proxy can turn the forged
+ // request into an authenticated tunnel request on a box.
+ var forwarded atomic.Int64
+ _, hub, _ := forwardHubAndBox(t, []registry.Route{forwardRow("shop.example.com", "home", fwdOwner)}, nil, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ forwarded.Add(1)
+ if r.Header.Get(tunnelclient.ReplicaProbeHeader) != "" {
+ t.Error("public marker crossed tunnel")
+ }
+ w.WriteHeader(200)
+ }))
+ if w := replicaRequest(t, hub, "1"); w.Code != 404 || forwarded.Load() != 0 {
+ t.Fatalf("public hub: %d forwarded=%d", w.Code, forwarded.Load())
+ }
+ ordinary := httptest.NewRequest("GET", "http://shop.example.com/", nil)
+ ordinary.Header.Set(tunnelclient.ReplicaProbeHeader, "1")
+ ordinaryReply := httptest.NewRecorder()
+ hub.ServeHTTP(ordinaryReply, ordinary)
+ if ordinaryReply.Code != 200 || forwarded.Load() != 1 {
+ t.Fatalf("hub fixture did not forward ordinary request: %d", ordinaryReply.Code)
+ }
+ if act.probes != 0 || hits.Load() != 0 {
+ t.Fatal("untrusted ingress probed")
+ }
+ if w := replicaRequest(t, tunnelclient.Mark(e), "1"); w.Code != 200 {
+ t.Fatalf("private landing: %d %s", w.Code, w.Body.String())
+ }
+ if hits.Load() != 1 {
+ t.Fatal("valid private probe did not reach app")
+ }
+ // Both forwarding boundaries scrub even on ordinary URLs.
+ r := httptest.NewRequest("GET", "http://missing.example.com/", nil)
+ r.Header.Set(tunnelclient.ReplicaProbeHeader, "1")
+ e.ServeHTTP(httptest.NewRecorder(), r)
+ if r.Header.Get(tunnelclient.ReplicaProbeHeader) != "" {
+ t.Fatal("request scrub retained marker")
+ }
+ r.Header.Set(tunnelclient.ReplicaProbeHeader, "1")
+ pr := &httputil.ProxyRequest{In: r, Out: r.Clone(r.Context())}
+ scrubTunnelMarkers(pr)
+ if pr.Out.Header.Get(tunnelclient.ReplicaProbeHeader) != "" {
+ t.Fatal("rewrite retained marker")
+ }
+}
+
+func TestReplicaProbeStatusRange(t *testing.T) {
+ for _, code := range []int{200, 302, 404, 499, 500, 503} {
+ t.Run(fmt.Sprint(code), func(t *testing.T) {
+ var hits atomic.Int64
+ e, _ := replicaLanding(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ hits.Add(1)
+ if r.URL.Path != "/" || r.Method != "GET" || r.Header.Get("Authorization") != "" || r.Header.Get(tunnelclient.ReplicaProbeHeader) != "" {
+ t.Error("not a clean GET /")
+ }
+ w.Header().Set("Location", "/login")
+ w.WriteHeader(code)
+ _, _ = w.Write([]byte(strings.Repeat("x", 8192)))
+ }))
+ w := replicaRequest(t, tunnelclient.Mark(e), "1")
+ var c replicas.Copy
+ if w.Code != 200 || json.Unmarshal(w.Body.Bytes(), &c) != nil {
+ t.Fatalf("%d: %s", w.Code, w.Body.String())
+ }
+ if c.Healthy != replicas.HealthyStatus(code) || hits.Load() != 1 {
+ t.Fatalf("health=%v hits=%d", c.Healthy, hits.Load())
+ }
+ })
+ }
+}
+
+func TestReplicaProbeAssignedIdentity(t *testing.T) {
+ for _, field := range []string{"lifetime", "revision", "box", "account", "fleet", "build", "boot", "state"} {
+ t.Run(field, func(t *testing.T) {
+ e, a := replicaLanding(t, http.HandlerFunc(func(http.ResponseWriter, *http.Request) { t.Error("mismatched identity reached app") }))
+ switch field {
+ case "lifetime":
+ a.copy.Incarnation = "old"
+ case "revision":
+ a.copy.AssignmentRevision--
+ case "box":
+ a.copy.Box = "b"
+ case "account":
+ a.copy.Account = "other"
+ case "fleet":
+ a.copy.Fleet = "other"
+ case "build":
+ a.copy.Digest = ""
+ case "boot":
+ a.copy.BootID = ""
+ case "state":
+ a.copy.State = "starting"
+ }
+ if w := replicaRequest(t, tunnelclient.Mark(e), "1"); w.Code != 503 {
+ t.Fatalf("%d: %s", w.Code, w.Body.String())
+ }
+ })
+ }
+}
+
+type replicaClosedAdmission struct{}
+
+func (replicaClosedAdmission) TenantAdmitted() bool { return false }
+func TestReplicaProbeAdmissionAndTimeout(t *testing.T) {
+ e, a := replicaLanding(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { <-r.Context().Done() }))
+ e.admission = replicaClosedAdmission{}
+ if w := replicaRequest(t, tunnelclient.Mark(e), "1"); w.Code != 503 || a.probes != 0 {
+ t.Fatal("closed admission was probed")
+ }
+ e.admission = nil
+ start := time.Now()
+ if w := replicaRequest(t, tunnelclient.Mark(e), "1"); w.Code != 503 {
+ t.Fatalf("timed-out probe: %d", w.Code)
+ }
+ if time.Since(start) > 3*time.Second {
+ t.Fatal("probe exceeded timeout")
+ }
+}
+
+func TestReplicaHealthAppDoorRefusesSnapshot(t *testing.T) {
+ s := newDoorScene(t)
+ w := s.do(t, "GET", doorOwnHost, "/__carlos/replica-probe", s.key, map[string]string{tunnelclient.ReplicaProbeHeader: "1"}, nil)
+ if w.Code != 404 || upstreamCalls(s.own) != 0 {
+ t.Fatalf("door private probe: %d", w.Code)
+ }
+ w = s.do(t, "GET", doorOwnHost, "/replica-health", s.key, nil, nil)
+ if w.Code != 200 || w.Body.String() != doorOwnBody {
+ t.Fatalf("door snapshot URL must be an ordinary app URL: %d %s", w.Code, w.Body.String())
+ }
+}
+
+func TestReplicaProbeServingGenerationChanges(t *testing.T) {
+ e, a := replicaLanding(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(200) }))
+ a.onProbe = func() {
+ if a.probes == 3 {
+ a.copy.Generation++
+ }
+ }
+ if w := replicaRequest(t, tunnelclient.Mark(e), "1"); w.Code != 503 {
+ t.Fatalf("retired generation accepted: %d", w.Code)
+ }
+ if a.served.Load() != 0 {
+ t.Fatal("probe entered request accounting")
+ }
+}
diff --git a/internal/host/agent.go b/internal/host/agent.go
index 39168ecfb..d9c4e863a 100644
--- a/internal/host/agent.go
+++ b/internal/host/agent.go
@@ -1100,7 +1100,20 @@ func runAgent(args []string, buildClaims ClaimFactory) {
if admissionOption != nil {
edgeOpts = append(edgeOpts, admissionOption)
}
+ healthCtx, healthCancel := context.WithCancel(context.Background())
+ var healthWG sync.WaitGroup
+ defer func() { healthCancel(); healthWG.Wait() }()
edge.RunWithActivatorReady(args, act, cache, func(e *edge.Edge) {
+ // Slice 1b replaces the empty source with e.ReplicaSnapshots.
+ readReplicaHealth := func() map[string]replicas.Snapshot { return map[string]replicas.Snapshot{} }
+ healthWG.Add(1)
+ go func() {
+ defer healthWG.Done()
+ serveAgentSocket(healthCtx, replicaHealthSocket, func(ctx context.Context, path string) error {
+ return serveReplicaHealth(ctx, path, readReplicaHealth)
+ })
+ }()
+
// Edge-held streams (spec 2026-10-28 §3.2, §3.7): the activator
// signals the edge's held streams when a host may have become
// admissible. act is nil when hibernation is not armed; no route
diff --git a/internal/host/replicahealth_linux.go b/internal/host/replicahealth_linux.go
new file mode 100644
index 000000000..6bf4a67cb
--- /dev/null
+++ b/internal/host/replicahealth_linux.go
@@ -0,0 +1,109 @@
+//go:build linux
+
+package host
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "net"
+ "net/http"
+ "os"
+ "path/filepath"
+ "syscall"
+ "time"
+
+ "github.com/carlosframework/platform/internal/replicas"
+)
+
+const replicaHealthSocket = "/run/carlos/.replicas/health.sock"
+
+func serveReplicaHealth(ctx context.Context, path string, read func() map[string]replicas.Snapshot) error {
+ if ctx.Err() != nil {
+ return nil
+ }
+ dir := filepath.Dir(path)
+ if err := os.MkdirAll(dir, 0700); err != nil {
+ return err
+ }
+ info, err := os.Lstat(dir)
+ if err != nil {
+ return err
+ }
+ if st, ok := info.Sys().(*syscall.Stat_t); !ok || !info.IsDir() || st.Uid != uint32(os.Geteuid()) {
+ return os.ErrPermission
+ }
+ if err := os.Chmod(dir, 0700); err != nil {
+ return err
+ }
+ // Serialise stale-socket cleanup and binding across agent processes.
+ // Holding the directory lock avoids unlinking a successor after a crash.
+ lock, err := os.Open(dir)
+ if err != nil {
+ return err
+ }
+ defer lock.Close()
+ if err := syscall.Flock(int(lock.Fd()), syscall.LOCK_EX|syscall.LOCK_NB); err != nil {
+ if errors.Is(err, syscall.EWOULDBLOCK) {
+ return os.ErrExist
+ }
+ return err
+ }
+ if info, err := os.Lstat(path); err == nil {
+ if info.Mode()&os.ModeSocket == 0 {
+ return os.ErrExist
+ }
+ conn, dialErr := net.DialTimeout("unix", path, time.Second)
+ if dialErr == nil {
+ conn.Close()
+ return os.ErrExist
+ }
+ // Only a proven stale socket may be removed. A timeout or denied
+ // connection may still belong to a live listener.
+ if !errors.Is(dialErr, syscall.ECONNREFUSED) {
+ return dialErr
+ }
+ if err := os.Remove(path); err != nil {
+ return err
+ }
+ } else if !errors.Is(err, os.ErrNotExist) {
+ return err
+ }
+ ln, err := net.ListenUnix("unix", &net.UnixAddr{Name: path, Net: "unix"})
+ if err != nil {
+ return err
+ }
+ defer ln.Close() // the listener unlinks its own socket
+ if err := os.Chmod(path, 0600); err != nil {
+ return err
+ }
+ srv := &http.Server{ReadHeaderTimeout: time.Second, ReadTimeout: time.Second,
+ WriteTimeout: time.Second, IdleTimeout: time.Second, MaxHeaderBytes: 4096,
+ Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Cache-Control", "no-store")
+ if r.Method != http.MethodGet || r.URL.Path != "/replica-health" || r.URL.RawQuery != "" {
+ w.WriteHeader(http.StatusNotFound)
+ return
+ }
+ w.Header().Set("Content-Type", "application/json")
+ _ = json.NewEncoder(w).Encode(read())
+ })}
+ done := make(chan error, 1)
+ go func() { done <- srv.Serve(ln) }()
+ select {
+ case err := <-done:
+ if errors.Is(err, http.ErrServerClosed) {
+ return nil
+ }
+ return err
+ case <-ctx.Done():
+ stop, cancel := context.WithTimeout(context.Background(), time.Second)
+ defer cancel()
+ err := srv.Shutdown(stop)
+ if err != nil {
+ _ = srv.Close()
+ }
+ <-done
+ return err
+ }
+}
diff --git a/internal/host/replicahealth_linux_test.go b/internal/host/replicahealth_linux_test.go
new file mode 100644
index 000000000..f7a061ceb
--- /dev/null
+++ b/internal/host/replicahealth_linux_test.go
@@ -0,0 +1,184 @@
+//go:build linux
+
+package host
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "net"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "strings"
+ "sync/atomic"
+ "syscall"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/edge"
+ "github.com/carlosframework/platform/internal/registry"
+ "github.com/carlosframework/platform/internal/replicas"
+)
+
+func replicaHealthFixture(t *testing.T) (string, func(), *atomic.Int64) {
+ t.Helper()
+ dir, err := os.MkdirTemp("", "rh")
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { os.RemoveAll(dir) })
+ path := filepath.Join(dir, ".replicas", "health.sock")
+ var reads atomic.Int64
+ ctx, cancel := context.WithCancel(t.Context())
+ done := make(chan error, 1)
+ go func() {
+ done <- serveReplicaHealth(ctx, path, func() map[string]replicas.Snapshot {
+ reads.Add(1)
+ return map[string]replicas.Snapshot{"shop.example.com": {Host: "shop.example.com", Incarnation: "private-lifetime", Revision: 7}}
+ })
+ }()
+ var stopped atomic.Bool
+ stop := func() {
+ if stopped.Swap(true) {
+ return
+ }
+ cancel()
+ select {
+ case err := <-done:
+ if err != nil {
+ t.Error(err)
+ }
+ case <-time.After(5 * time.Second):
+ t.Error("snapshot shutdown did not join")
+ }
+ }
+ t.Cleanup(stop)
+ deadline := time.Now().Add(5 * time.Second)
+ for {
+ if info, err := os.Stat(path); err == nil && info.Mode().Perm() == 0600 {
+ break
+ }
+ select {
+ case err := <-done:
+ stopped.Store(true)
+ cancel()
+ t.Fatalf("socket startup: %v", err)
+ default:
+ }
+ if time.Now().After(deadline) {
+ t.Fatal("socket never became ready")
+ }
+ time.Sleep(time.Millisecond)
+ }
+ return path, stop, &reads
+}
+
+func TestReplicaHealthSocketMode(t *testing.T) {
+ path, stop, _ := replicaHealthFixture(t)
+ for p, mode := range map[string]os.FileMode{path: 0600, filepath.Dir(path): 0700} {
+ info, err := os.Lstat(p)
+ if err != nil || info.Mode().Perm() != mode {
+ t.Fatalf("%s: %v %v", p, info, err)
+ }
+ if info.Sys().(*syscall.Stat_t).Uid != uint32(os.Geteuid()) {
+ t.Fatal("not agent-owned")
+ }
+ }
+ transport := &http.Transport{DialContext: func(ctx context.Context, _, _ string) (net.Conn, error) {
+ return (&net.Dialer{}).DialContext(ctx, "unix", path)
+ }}
+ defer transport.CloseIdleConnections()
+ client := &http.Client{Transport: transport, Timeout: time.Second}
+ res, err := client.Get("http://local/replica-health")
+ if err != nil {
+ t.Fatal(err)
+ }
+ var snapshots map[string]replicas.Snapshot
+ err = json.NewDecoder(res.Body).Decode(&snapshots)
+ res.Body.Close()
+ if err != nil || snapshots["shop.example.com"].Incarnation != "private-lifetime" {
+ t.Fatalf("snapshot=%+v err=%v", snapshots, err)
+ }
+ // Another listener must not unlink the first one's socket.
+ if err := serveReplicaHealth(t.Context(), path, nil); !errors.Is(err, os.ErrExist) {
+ t.Fatalf("second listener: %v", err)
+ }
+ stop()
+ if _, err := os.Lstat(path); !errors.Is(err, os.ErrNotExist) {
+ t.Fatalf("socket remains: %v", err)
+ }
+}
+
+func TestReplicaHealthNamespace(t *testing.T) {
+ if os.Getenv("CARLOS_REPLICA_NAMESPACE_CHILD") == "1" {
+ path := os.Getenv("CARLOS_REPLICA_NAMESPACE_PATH")
+ if err := syscall.Mount("", "/", "", syscall.MS_REC|syscall.MS_PRIVATE, ""); err != nil {
+ t.Fatal(err)
+ }
+ // The tenant template replaces /run/carlos with a private tmpfs.
+ // Apply the same mount to the fixture's runtime directory.
+ if err := syscall.Mount("tmpfs", filepath.Dir(filepath.Dir(path)), "tmpfs", syscall.MS_RDONLY, "mode=0755"); err != nil {
+ t.Fatal(err)
+ }
+ if c, err := net.DialTimeout("unix", path, time.Second); err == nil {
+ c.Close()
+ t.Fatal("tenant reached health socket")
+ }
+ return
+ }
+ path, _, reads := replicaHealthFixture(t)
+ unit, err := unitsFS.ReadFile("units/carlos-instance@.service")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !strings.Contains(string(unit), "TemporaryFileSystem=/run/carlos:ro") {
+ t.Fatal("tenant no longer hides runtime directory")
+ }
+ for _, line := range strings.Split(string(unit), "\n") {
+ if strings.HasPrefix(line, "Bind") && strings.Contains(line, "/.replicas") {
+ t.Fatal("tenant exposes snapshot directory")
+ }
+ }
+ // Neither the public listener nor the authenticated app door installs
+ // the snapshot handler. An app URL cannot invoke its read callback.
+ reg, err := registry.Open(filepath.Join(t.TempDir(), "registry.db"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer reg.Close()
+ e, err := edge.New(reg, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, host := range []string{"public.example.com", "shop.example.com"} {
+ for _, urlPath := range []string{"/replica-health", "/__carlos/replica-probe"} {
+ r := httptest.NewRequest("GET", "http://"+host+urlPath, nil)
+ r.Header.Set("X-Carlos-Replica-Probe", "1")
+ w := httptest.NewRecorder()
+ e.ServeHTTP(w, r)
+ if w.Code == 200 || strings.Contains(w.Body.String(), "private-lifetime") || reads.Load() != 0 {
+ t.Fatal("public request read health snapshot")
+ }
+ }
+ }
+ t.Run("tenant-mount", func(t *testing.T) {
+ ctx, cancel := context.WithTimeout(t.Context(), 10*time.Second)
+ defer cancel()
+ cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestReplicaHealthNamespace$", "-test.timeout=8s")
+ cmd.Env = append(os.Environ(), "CARLOS_REPLICA_NAMESPACE_CHILD=1", "CARLOS_REPLICA_NAMESPACE_PATH="+path)
+ cmd.Dir = filepath.Dir(path)
+ cmd.SysProcAttr = &syscall.SysProcAttr{Cloneflags: syscall.CLONE_NEWUSER | syscall.CLONE_NEWNS,
+ UidMappings: []syscall.SysProcIDMap{{ContainerID: 0, HostID: os.Getuid(), Size: 1}},
+ GidMappings: []syscall.SysProcIDMap{{ContainerID: 0, HostID: os.Getgid(), Size: 1}}, GidMappingsEnableSetgroups: false}
+ out, err := cmd.CombinedOutput()
+ if errors.Is(err, syscall.EPERM) {
+ t.Skipf("unprivileged mount namespace unavailable: %v", err)
+ }
+ if err != nil {
+ t.Fatalf("namespace witness: %v\n%s", err, out)
+ }
+ })
+}
diff --git a/internal/host/replicahealth_other.go b/internal/host/replicahealth_other.go
new file mode 100644
index 000000000..dfe20e8e3
--- /dev/null
+++ b/internal/host/replicahealth_other.go
@@ -0,0 +1,17 @@
+//go:build !linux
+
+package host
+
+import (
+ "context"
+ "errors"
+
+ "github.com/carlosframework/platform/internal/replicas"
+)
+
+const replicaHealthSocket = "/run/carlos/.replicas/health.sock"
+
+func serveReplicaHealth(context.Context, string, func() map[string]replicas.Snapshot) error {
+ // copy SR-3-C07 (provisional)
+ return errors.New("live replica health is unavailable on this system")
+}
diff --git a/internal/replicas/health.go b/internal/replicas/health.go
new file mode 100644
index 000000000..ea594af3b
--- /dev/null
+++ b/internal/replicas/health.go
@@ -0,0 +1,39 @@
+package replicas
+
+import "time"
+
+// Copy is platform launch evidence plus the latest private health observation.
+// Socket is local-only; the hub must never choose a dial path from JSON.
+type Copy struct {
+ Host string `json:"host"`
+ Account string `json:"account"`
+ App string `json:"app"`
+ Fleet string `json:"fleet"`
+ Box string `json:"box"`
+ BootID string `json:"boot_id"`
+ Incarnation string `json:"incarnation"`
+ AssignmentRevision uint64 `json:"assignment_revision"`
+ Generation uint64 `json:"generation"`
+ Version string `json:"version"`
+ Digest string `json:"digest"`
+ State string `json:"state"`
+ Reason string `json:"reason,omitempty"`
+ Healthy bool `json:"healthy"`
+ ObservedAt time.Time `json:"observed_at"`
+ WorkersRunning int `json:"workers_running"`
+ WorkersDeclared int `json:"workers_declared"`
+ Socket string `json:"-"`
+}
+
+type Snapshot struct {
+ Host string `json:"host"`
+ Account string `json:"account"`
+ App string `json:"app"`
+ Incarnation string `json:"incarnation"`
+ Revision uint64 `json:"revision"`
+ Desired int `json:"desired"`
+ Copies []Copy `json:"copies"`
+}
+
+// HealthyStatus accepts final HTTP responses below 500, including redirects.
+func HealthyStatus(code int) bool { return code >= 200 && code < 500 }
diff --git a/internal/replicas/health_test.go b/internal/replicas/health_test.go
new file mode 100644
index 000000000..432d540be
--- /dev/null
+++ b/internal/replicas/health_test.go
@@ -0,0 +1,12 @@
+package replicas
+
+import "testing"
+
+func TestHealthyStatus(t *testing.T) {
+ for _, code := range []int{-1, 0, 99, 100, 199, 200, 302, 404, 499, 500, 503, 600} {
+ want := code == 200 || code == 302 || code == 404 || code == 499
+ if HealthyStatus(code) != want {
+ t.Errorf("HealthyStatus(%d) != %v", code, want)
+ }
+ }
+}
diff --git a/internal/tunnelclient/tunnelclient.go b/internal/tunnelclient/tunnelclient.go
index 9c3ec791a..464840926 100644
--- a/internal/tunnelclient/tunnelclient.go
+++ b/internal/tunnelclient/tunnelclient.go
@@ -268,6 +268,9 @@ func Dial(ctx context.Context, rawURL, name, token string) (net.Conn, error) {
return conn, nil
}
+// ReplicaProbeHeader marks private hub health requests, never visitor traffic.
+const ReplicaProbeHeader = "X-Carlos-Replica-Probe"
+
type tunnelKey struct{}
// FromTunnel reports whether a request was served over a tunnel this client