feat: probe assigned copies over fleet tunnels
Track independent copy health jobs over authenticated tunnel connections, with generation checks, unknown startup, bounded probes and shared consecutive failure/recovery counts. Expose detached health snapshots through the private agent socket without enabling replica routing. Propose the combined Task 1 root-read census for independent review. Keep fixed-address probing and HA routing behavior unchanged.
Co-Authored-By: Codex (gpt-6-astra) <noreply@openai.com>
docs/superpowers/notes/census-proposal-stateless-replicas-3.md+42 −0internal/edge/edge.go+8 −0internal/edge/prober.go+18 −12internal/edge/replicaprober.go+420 −0internal/edge/replicaprober_test.go+762 −0internal/edge/tunnel.go+61 −7internal/host/agent.go+2 −2internal/provision/testdata/plan14-root-reads-chain.tsv+1 −0internal/provision/testdata/plan14-root-reads-stateless-replicas-3.tsv+45 −0
Intent
<task-notification> <task-id>bmy0c6z68</task-id> <tool-use-id>toolu_01UWzWHLv1ymUo5BjDYE5Ngi</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/195ef15b-aac6-42d6-b49b-41ffb7a4abbc/tasks/bmy0c6z68.output</output-file> <status>completed</status> <summary>Background command "Wait for first of Task 1b or F8 to finish" completed (exit code 0)</summary> </task-notification>
Attributed to this commit: 20.1 g CO₂e (2,229,997 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/docs/superpowers/notes/census-proposal-stateless-replicas-3.md b/docs/superpowers/notes/census-proposal-stateless-replicas-3.md| new file mode 100644 |
| index 000000000..7a11e0f61 |
| --- /dev/null |
| +++ b/docs/superpowers/notes/census-proposal-stateless-replicas-3.md |
| @@ -0,0 +1,42 @@ |
| +# Census approval: stateless-replicas-3 |
| + |
| +Ruling `census-ruling-stateless-replicas-3`. The independent reviewer approves or rejects every change below, 16 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` `RunWithActivatorReady` | body | unchanged (5) | Task 1b: defer stopping and joining the edge's replica jobs at shutdown. Existing five direct read sites unchanged; no new reader or authority. | |
| +| `internal/host/agent.go` `runAgent` | body | unchanged (5) | Task 1a+1b: run the private replica-health Unix server with existing retry shape, cancel/join it at shutdown and supply Edge.ReplicaSnapshots in the ready hook. Existing five direct read sites unchanged; no console reader, polling loop or new credentials. | |
| +| `internal/edge/edge.go` `Edge.ServeHTTP` | sites | +whole:Route | Task 1a: pass the already-resolved Route to the reserved replica-probe handler after acceptHop and existing admissionRefuses, requiring tunnel context plus private marker and refusing door/backhaul ingress. Added whole Route use only; scrub marker before forwarding; HA calls remain unchanged. | |
| + |
| +Envelopes re-pinned: `internal/activator`, `internal/edge`, `internal/host`, `internal/replicas`, `internal/tunnelclient`. |
| + |
| +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` `RunWithActivatorReady`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=J4;basis=root-input;rev3=census-ruling-certwarm-wake;basis=registers the cert warm's nudge on OnReload and on the home map's new served-hosts wake (#386); nudge only sends on a buffered channel; no read added, same 5 sites;rev3=census-ruling-edge-roll-blip;basis=the :80/:443 (and dev) listeners are bound on the calling goroutine with net.Listen via listen()/listenAddr (same empty-address defaults as ListenAndServe) before the serve goroutines, which now call Serve/ServeTLS on them, and one log line names the bound addresses; no read added, same 5 sites;rev3=census-ruling-edge-held-streams;basis=the edge in the agent (carlos-edge.service, user carlos): the inline home-map arming (newHomeMap, one boot Refresh, Store, run) moves unchanged into the new Edge.ArmHomeMap and is called here as e.ArmHomeMap(); same refresh, same timeout, same order. The reads are moved, none added.;rev3=census-ruling-agent-start-demo-1;basis=Logs the combined explicit wildcard parents through demoWildcardDomains; no new watcher or read loop.;rev3=census-ruling-region-ha-p3a;basis=P3a Task 3: invoke the local admission Close before HTTP/HTTPS draining and door shutdown in both dev and normal listeners. Preserve merged main's startup behavior and its census basis; the same five read sites, no new reads. |
| +- `internal/host/agent.go` `runAgent`: authority, task B,C,D,F. Basis: rev3=census-ruling-self-serve-moves-1;basis=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): builds the box's lifetime judge once (newBoxJudge, nil with host claims on) and hands it to the seed placement, the moves and runs workers and every loop it starts; read sites unchanged, offsets moved; B,C,D,F authority retained; self-serve moves 1 Task 8: derives the box's lifetimes switch from the judge once (lifetimes := boxJudge != nil) and hands it to the edges file loop; read sites unchanged, offsets moved;rev3=census-ruling-plans-4d-lapse;basis=arms two more plans hooks from the same snapshot: e.SetPlanDisabledFor(planDisabledFor) beside SetPlanGovernedFor, and svc.SetDisabledFor(planDisabledRoute) beside SetMaxRunFor (plans 4d); the reads live in those units (plans-4d-units decision); read sites unchanged, offsets moved;rev3=census-ruling-rootfs-apps-2;basis=main's body as of the merge of origin/main 9b81d97b (with main's plan rate ceiling, edge request records, regional box names, self-serve moves plan 1, plans 4d-1 lapse and its other later changes under main's own census rulings) plus the rootfs placement wiring in the activator start: an agentRootfs built from eb.NestedOK, CARLOS_DEPLOYMENT_SINGLE_TENANT, CARLOS_POOLS, the claim flag, swapArming's answer, the control client's /ready/rootfs and, on a fleet box whose identity resolved, fleetOwnerCheck over the deploy store main already opens for the fleet label (fleetStore), then arm and armedRootfs.Store; this body reads nothing new itself; the closures it wires read later, at a rootfs wake and each status tick: GET /ready/rootfs over the control socket, NestedOK's checks, and release.FleetOwnerKey for the judged row's own account and this box's fleet from the deploy store;rev3=census-ruling-instance-egress-sizes-328-329;basis=#328 plan 2 Tasks 7 and 11, #329 plan 3 Task 7 and plan 1 Task 7's policy cache: the control client is built once and handed to eb.Control, to the status tick (egressStatus) and to a new egressNudgeLoop goroutine; armSizeSource(svc, "/sys/fs/cgroup") after the activator Service; armPolicyCache() after armChangeIndex; statusLoop takes egressStatus. The reads are those units' own (decision rows); this body reads nothing new: the same five sites, offsets moved, in the agent; B,C,D,F authority retained.;rev3=census-ruling-remote-instance-metrics;basis=builds the metrics loop's owners closure (metricsOwners over the agent's registry, the activator and cgm.Leftover) when an activator exists and hands it to metricsLoop; reads nothing new itself;rev3=census-ruling-edge-asset-cache-3;basis=adds file:Statfs. runAgent keeps its authority (B,C,D,F). The new site is assetcache.Statfs, an exported assetcache.FS interface value (var Statfs FS = statfsFS{}), not a function value and not a call in runAgent: the ready hook passes it to armEdgeAssetCache as the store's filesystem, and armEdgeAssetCache calls its Space method on the configured data directory (dataDir(): $CARLOS_DATA_DIR, else /data), which calls unix.Statfs there (statfsFS.Space, accepted legacy at census-ruling-edge-asset-cache-2). No request-supplied pathname reaches it.;rev3=census-ruling-remote-metrics-nested;basis=main's body (merged origin/main acfa4f80, under main's own census rulings) plus: snapshots the nested layout (snapshotNestedUnits over /sys/fs/cgroup/carlos.slice/carlos-instances.slice) once at start, before the activator, and hands the metrics loop a unitSources struct (stamped units, routeHostNames, that root and the snapshot); reads nothing new itself;rev3=census-ruling-region-ha-p1a;basis=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): wires region HA P1a into the activator: cfg.Record = haRecordFacts(openDeployStore, boxJudge) (the box's lifetime judge this body already builds with newBoxJudge, nil with host claims on; CI fix) and cfg.Self = lease.CurrentSelf; eb.Lifetimes (the process's lifetime index), eb.Registry, eb.StartupSwept (seedSweptAtStart.Load), eb.FilesStore from newProductionFilesStore (now lease.NewFilesStore, rootaws-loaded, a log line on failure) and lease.SetObligationDir(<data>/.ha-owed) (logged on failure; HA acquires then refuse); this body reads nothing new itself, the same five sites; the reads are those units' own (haRecordFacts and lease's SetObligationDir are new rows on this card); merge of origin/main d7ae1d76: main's own later changes to this body are kept as main has them, under main's rulings (census-ruling-remote-instance-metrics: the metricsOwners closure for metricsLoop; census-ruling-edge-asset-cache-3: the +file:Statfs site, assetcache.Statfs handed to the asset ready hook); this branch's change is the same as above;rev3=census-ruling-region-ha-p1b1;basis=region HA P1b-1: builds one termfence.Confirmer (Self from lease.CurrentSelf at each call, EC2 DescribeInstances method only, client from rootaws.LoadDefaultConfig with retries off, built lazily on first use) and sets eb.OwnerTerminated; this body reads nothing new itself, the same six sites;rev3=census-ruling-rootfs-apps-3;basis=rootfs Plan 3 Task 7: the startup Sweep literal hands its answer to startupSwept, which logs as before and, only on a clean sweep, marks rootfs admission swept (MarkRootfsSwept); same Sweep call, no read added;rev3=census-ruling-managed-fleets-1b;basis=managed fleets 1b (controller ruling after branch review R1, and Paul's R2 ruling): sets svc.Fleet = fleetWakeFor(os.Getenv, identity, identErr, fleetStore) from the identity it already resolves once and the deployment store the fleet loops already opened, and logs an ERROR naming the identity error when the box is on a fleet with an invalid identity. fleetWakeFor reads CARLOS_REGION and CARLOS_FLEET from the same environment. Read sites unchanged (6). Agent, not root; a platform box is unchanged.;rev3=census-ruling-rootfs-apps-6;basis=rootfs Plan 6 Task 12: one call more beside armRunsPass, armInteractivePass(svc, reg, rolloutSink, boxJudge), in the same activator Configure hook, handing it the same box judge; fix round 1 (Astra P2, shutdown): after svc.Shutdown(ctx), shutdownInteractive(ctx) ends and joins every interactive session under the same shutdown budget; the worker's own reads are its units' (interactive.go); this body reads nothing new, the same six sites; merge of origin/main 6f1f6ca6: main's svc.Fleet = fleetWakeFor(...) and its invalid-identity ERROR line are kept as main has them (census-ruling-managed-fleets-1b); this branch's change is the same as above; read sites unchanged (6);rev3=census-ruling-fix-set-aside-exdev;basis=set-aside EXDEV fix: one field more on the agent ExecBackend literal, RawInstanceDir: layout.RawInstanceDir (a pure path join: <dataDir>/.instances/<InstanceID(host)>), so the start rule set-aside moves a copy out through the raw directory instead of through the nosymfollow bind; this body reads nothing new, the same six sites;rev3=census-ruling-durability-3a-escrow;basis=durability 3a Task 3: one more assignment beside eb.FilesStore: eb.EscrowKey = haEscrowKey(os.Getenv("CARLOS_SECRETS_KEY")), the agent's own environment parsed by appconfig.ParsePrivateKey as the moves pass parses it (unset or unparseable: a log line and nil, and HA publication refuses on the box). No path is opened or read, no read site added; the same six sites, offsets moved; B,C,D,F authority retained. Durability 3a Task 4: one more goroutine beside configSyncLoop: go escrowLoop(agentCtx, reg, svc), the escrow sweep every 30 s over the same registry and Service. This body reads nothing new itself; the same six sites, offsets moved; B,C,D,F authority retained. Durability 3a Task 5: one more call beside eb.EscrowKey: wireRawSecretPages(eb, PageOperator, metricsBoxLabel(os.Getenv, readMachineID())), which sets eb.OnRawSecret to page an operator (alerting.Page through PageOperator, LevelIncident) on its own goroutine with a 20 s timeout; metricsBoxLabel and readMachineID are the reads this body already makes for the moves refusal log; no new read site; the same six sites, offsets moved; B,C,D,F authority retained. Merge of origin/main 90c4d3aa: main's own later changes to this body are kept as main has them, under main's rulings; this branch's change is the same as above. Merge of origin/main 00bf5b8c (fleet set-aside EXDEV fix): main's change to this body is kept as main has it, under its own census ruling; this branch's change is unchanged.;rev3=census-ruling-probe-burst-limit;basis=two more sink wirings beside setAnalyticsSink: setProtectionSink(e.SetProtectionRecordOnly) and setAssetOwnersSource(e.AssetOwners), function values the telemetry pass calls; this body reads nothing new, the same six sites; authority B,C,D,F retained; no new root read or write kind;rev3=census-ruling-region-ha-p1b3a;basis=Arm HA placement exactly once on the existing Service before activatorStart and edges publication, wiring AwakeApps and the PageOperator callback; existing six read sites unchanged, no new root authority.;rev3=census-ruling-stateless-replicas-1;basis=Final review I3: start the concrete coordinator's renewal worker with agent setup; existing closeReplicaCoordinator shutdown cancels and joins it before release. No new read sites or credentials. Merge origin/main c59715e7: retain main's armHAPlacement(svc, PageOperator) wiring beside the existing activator setup; stateless coordinator and shutdown wiring remain. Same read sites; no new root read or credential.;rev3=census-ruling-edge-held-streams;basis=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): in the edge-ready callback, calls act.SetHeldWakeHook(e.HeldWake) when act is non-nil (installing the non-blocking wake callback) and stores e.HeldStreamsForStatus in heldStreamsSource. Wiring of in-memory callbacks only; no read added.;rev3=census-ruling-region-ha-p1b3b-t;basis=Wire Service.SetDutyView to the live edge DutySnapshot in the ready callback. No new read; no new loop or cloud operation. B2 wires the registry as the persistent DutyStore before service startup; no new cloud or filesystem path. B3b: arm one journal-backed termination consumer before service startup using agentCtx and the shared confirmer; expose edge tick and join at edge shutdown. No new direct read sites.;rev3=census-ruling-agent-start-demo-1;basis=Passes the existing registry, data store and hibernation prefix into the demo worker, and the existing instance-control client into the demo before-exec hook. No alternate data store or polling loop. Merge resolution against origin/main 9bd45488 retains main's HA departure controller, lifecycle and duty wiring alongside the demo data store and worker; no read site added by the resolution.;rev3=census-ruling-region-ha-p3a;basis=P3a Task 3: install closed fixed admission before every launch source, bind activator/backend and edge, wire the real termination Started lifecycle and role reader after the change index; close before cancellation/child shutdown. No new external reads or cloud authority. Fix R1: move bind/lifecycle/edge-option wiring into wireAgentAdmission and worker listing into runWorkerBootPassAfterAdmission. Worker boot waits for admission before listing then uses unchanged bounded wakes and per-host serialization; whole Route read moves to the helper. No new storage, cloud, or root execution authority. Preserve merged main's agent wiring and census basis; the branch removes one whole Route use by moving worker iteration to the helper, with no added read kind.;rev3=census-ruling-stateless-replicas-2;basis=Slice 3b: arms a fleet-only worker using the existing registry, activator, backend and authenticated console transport. Owned worker stops and joins at shutdown. No new bucket reader. merge of origin/main 9b8b2c50: retain HA duty/departure lifecycle, wake-slot and existing agent wiring alongside the replica placement worker; no new read introduced by resolution. merge of origin/main 6be08467: Retain main demo configuration, admission, build and expiry wiring alongside the replica worker; merge-only body change, no additional read. merge of origin/main 7920cccf: Retain main box-role/group admission wiring and boot publication beside the owned replica worker and shutdown; main moves the boot registry List into runWorkerBootPassAfterAdmission, removing its inline whole Route site. No new read introduced by conflict resolution. |
| +- `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.;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. |
| + |
| +New dispositions, which census-propose wrote and the reviewer checks against the unit's reads and the diff: |
| + |
| +- new `internal/activator/replicaprobe.go:Service.ProbeCopy`: reads +registry:Account, +registry:App, +registry:FleetBoxes, +registry:HA ×2, +registry:Hibernate ×2, +registry:Incarnation ×2, +registry:Kind, +registry:Region ×3, +registry:ReplicaIncarnation ×3, +registry:ReplicaRevision, +registry:Stateless, +whole:Route ×6; written legacy, accepted-legacy, frozen |
| +- new `internal/edge/replicaprobe.go:Edge.replicaCopyMatches`: reads +registry:Account, +registry:App, +registry:Host, +registry:Region, +registry:ReplicaIncarnation, +registry:ReplicaRevision; written legacy, accepted-legacy, frozen |
| +- new `internal/edge/replicaprobe.go:Edge.serveReplicaProbe`: reads +registry:FleetBoxes, +registry:HA, +registry:Hibernate, +registry:Host, +registry:Kind, +whole:Route ×4; written legacy, accepted-legacy, frozen |
| +- new `internal/edge/replicaprober.go:Edge.syncReplicaProbes`: reads +whole:Route; written legacy, accepted-legacy, frozen |
| +- new `internal/edge/replicaprober.go:TunnelHub.probeReplica`: reads +file:ReadAll; written legacy, accepted-legacy, frozen |
| +- new `internal/edge/replicaprober.go:newReplicaProber`: reads +whole:Route; written legacy, accepted-legacy, frozen |
| +- new `internal/edge/replicaprober.go:replicaEvidenceMatches`: reads +registry:Account, +registry:App, +registry:GoodDigest ×2, +registry:GoodVersion, +registry:Host, +registry:Region, +registry:ServingVersion ×2, +whole:Route; written legacy, accepted-legacy, frozen |
| +- new `internal/edge/replicaprober.go:replicaProber.Snapshot`: reads +whole:Route ×2; written legacy, accepted-legacy, frozen |
| +- new `internal/edge/replicaprober.go:replicaProber.Stop`: reads +whole:Route; written legacy, accepted-legacy, frozen |
| +- new `internal/edge/replicaprober.go:replicaProber.Sync`: reads +registry:Account, +registry:App, +registry:FleetBoxes ×2, +registry:HA, +registry:Hibernate, +registry:Host ×4, +registry:Kind, +registry:Region, +registry:ReplicaIncarnation, +registry:ReplicaRevision, +whole:Route ×15; written legacy, accepted-legacy, frozen |
| +- new `internal/edge/replicaprober.go:replicaProber.reset`: reads +registry:Account, +registry:App, +registry:Region, +whole:Route ×3; written legacy, accepted-legacy, frozen |
| +- new `internal/edge/replicaprober.go:replicaProber.snapshotLocked`: reads +registry:Account, +registry:App, +registry:Copies, +registry:FleetBoxes, +registry:Host ×2, +registry:ReplicaIncarnation, +registry:ReplicaRevision; written legacy, accepted-legacy, frozen |
| +- new `internal/edge/replicaprober.go:replicaProber.snapshots`: reads +whole:Route ×3; written legacy, accepted-legacy, frozen |
| +- new `internal/edge/replicaprober.go:sameReplicaJob`: reads +registry:Account ×2, +registry:App ×2, +registry:Copies ×2, +registry:FleetBoxes ×2, +registry:GoodDigest ×2, +registry:GoodVersion ×2, +registry:Host, +registry:Region ×2, +registry:ReplicaIncarnation, +registry:ReplicaRevision, +registry:ServingVersion ×2, +whole:Route; written legacy, accepted-legacy, frozen |
| +- new `internal/edge/tunnel.go:tunnelWire.Read`: reads +file:Read ×2; written legacy, accepted-legacy, frozen |
| +- new `internal/host/replicahealth_linux.go:serveReplicaHealth`: reads +file:Lstat ×2, +file:Open; written legacy, accepted-legacy, frozen |
| + |
| +Seal: `59c0891618b9befae27ebe04d0a67b08c7f7658bca9f1c78bf6d05eb7a708e82` → `2c3d58a7cd1c3008e71f0c85ab41c886df496bc0974e1e9ccc9972ae7587c356`. |
| + |
| +Overlay: `internal/provision/testdata/plan14-root-reads-stateless-replicas-3.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`. |
diff --git a/internal/edge/edge.go b/internal/edge/edge.go| index b8ccca2c4..90612166e 100644 |
| --- a/internal/edge/edge.go |
| +++ b/internal/edge/edge.go |
| @@ -65,6 +65,7 @@ import ( |
| "github.com/carlosframework/platform/internal/ratelimit" |
| "github.com/carlosframework/platform/internal/registry" |
| "github.com/carlosframework/platform/internal/release" |
| + "github.com/carlosframework/platform/internal/replicas" |
| "github.com/carlosframework/platform/internal/reqrec" |
| "github.com/carlosframework/platform/internal/tunnelclient" |
| ) |
| @@ -114,6 +115,12 @@ type Activator interface { |
| // its backend. The host→backend map is swapped atomically, so reloads and |
| // zero-downtime deploys never drop a live connection. |
| type Edge struct { |
| + // ReplicaProbe is configured before the first syncReplicaProbes call. |
| + // Nil uses the private box landing over the existing tunnel transport. |
| + ReplicaProbe func(context.Context, string, string) (replicas.Copy, error) |
| + replicaMu sync.Mutex |
| + replicaProbes *replicaProber |
| + |
| demo demo.Config |
| devbox bool // installs front-door proxy hooks on every reload |
| reg *registry.Registry |
| @@ -4445,6 +4452,7 @@ func RunWithActivatorReady(args []string, act Activator, cache *Cache, ready fun |
| if err != nil { |
| log.Fatalf("edge: load routes: %v", err) |
| } |
| + defer e.stopReplicaProbes() |
| for _, opt := range opts { |
| opt(e) |
| } |
diff --git a/internal/edge/prober.go b/internal/edge/prober.go| index 030e65ab3..3463a34fa 100644 |
| --- a/internal/edge/prober.go |
| +++ b/internal/edge/prober.go |
| @@ -568,6 +568,19 @@ func (hp *hostProber) record(addr string, probeErr error) { |
| hp.mu.Unlock() |
| return |
| } |
| + transition, reason := st.recordProbe(probeErr, hp.failAt, hp.riseAt, time.Now()) |
| + hp.mu.Unlock() |
| + |
| + switch transition { |
| + case "down": |
| + log.Printf("edge: probe %s %s down (%s)", hp.spec.Host, addr, reason) |
| + case "up": |
| + log.Printf("edge: probe %s %s up", hp.spec.Host, addr) |
| + } |
| +} |
| + |
| +// recordProbe shares consecutive fail/rise counting without choosing initial health. |
| +func (st *upstreamState) recordProbe(probeErr error, failAt, riseAt int, now time.Time) (string, string) { |
| var transition, reason string |
| switch { |
| case probeErr == nil: |
| @@ -578,30 +591,23 @@ func (hp *hostProber) record(addr string, probeErr error) { |
| break |
| } |
| st.passes++ |
| - if st.passes >= hp.riseAt { |
| + if st.passes >= riseAt { |
| st.up = true |
| st.passes = 0 |
| st.fails = 0 |
| st.lastError = "" |
| - st.since = time.Now() |
| + st.since = now |
| transition = "up" |
| } |
| default: |
| st.passes = 0 |
| st.fails++ |
| st.lastError = probeErr.Error() |
| - if st.up && st.fails >= hp.failAt { |
| + if st.up && st.fails >= failAt { |
| st.up = false |
| - st.since = time.Now() |
| + st.since = now |
| transition, reason = "down", st.lastError |
| } |
| } |
| - hp.mu.Unlock() |
| - |
| - switch transition { |
| - case "down": |
| - log.Printf("edge: probe %s %s down (%s)", hp.spec.Host, addr, reason) |
| - case "up": |
| - log.Printf("edge: probe %s %s up", hp.spec.Host, addr) |
| - } |
| + return transition, reason |
| } |
diff --git a/internal/edge/replicaprober.go b/internal/edge/replicaprober.go| new file mode 100644 |
| index 000000000..5087c6989 |
| --- /dev/null |
| +++ b/internal/edge/replicaprober.go |
| @@ -0,0 +1,420 @@ |
| +package edge |
| + |
| +import ( |
| + "context" |
| + "encoding/hex" |
| + "encoding/json" |
| + "errors" |
| + "io" |
| + "net/http" |
| + "sync" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/registry" |
| + "github.com/carlosframework/platform/internal/replicas" |
| + "github.com/carlosframework/platform/internal/tunnelclient" |
| +) |
| + |
| +const ( |
| + replicaProbeInterval = time.Second |
| + replicaProbeFail = 2 |
| + replicaProbeRise = 2 |
| + // copy SR-3-C03 (provisional) |
| + replicaFailed = "this copy did not pass its health check" |
| + // copy SR-3-C04 (provisional) |
| + replicaDisconnected = "this box's tunnel is disconnected" |
| + // copy SR-3-C05 (provisional) |
| + replicaWaiting = "waiting for this copy to pass its health check" |
| + // copy SR-3-C06 (provisional) |
| + replicaStale = "this health answer belongs to an earlier instance or assignment" |
| +) |
| + |
| +// replicaProbeClock controls cadence and deadlines together. Tests advance both |
| +// without sleeping through 64 independent timeout windows. |
| +type replicaProbeClock interface { |
| + Now() time.Time |
| + Ticker(time.Duration) replicaProbeTicker |
| + Timeout(context.Context, time.Duration) (context.Context, context.CancelFunc) |
| +} |
| +type replicaProbeTicker interface { |
| + C() <-chan time.Time |
| + Stop() |
| +} |
| +type replicaRealClock struct{} |
| + |
| +func (replicaRealClock) Now() time.Time { return time.Now() } |
| +func (replicaRealClock) Ticker(d time.Duration) replicaProbeTicker { |
| + return replicaRealTicker{time.NewTicker(d)} |
| +} |
| +func (replicaRealClock) Timeout(ctx context.Context, d time.Duration) (context.Context, context.CancelFunc) { |
| + return context.WithTimeout(ctx, d) |
| +} |
| + |
| +type replicaRealTicker struct{ *time.Ticker } |
| + |
| +func (t replicaRealTicker) C() <-chan time.Time { return t.Ticker.C } |
| + |
| +type replicaProbeFunc func(context.Context, string, string) (replicas.Copy, error) |
| +type replicaSlot struct{ host, box string } |
| +type replicaJobKey struct { |
| + host, incarnation, box string |
| + revision uint64 |
| +} |
| +type replicaJob struct { |
| + key replicaJobKey |
| + route registry.Route |
| + channel string |
| + ctx context.Context |
| + cancel context.CancelFunc |
| + done chan struct{} |
| + // Everything below is guarded by replicaProber.mu. |
| + conn *tunnelConn |
| + count upstreamState |
| + sample replicas.Copy |
| + evidence replicas.Copy |
| +} |
| +type replicaProber struct { |
| + mu sync.Mutex |
| + hub *TunnelHub |
| + probe replicaProbeFunc |
| + clock replicaProbeClock |
| + jobs map[replicaSlot]*replicaJob |
| + routes map[string]registry.Route |
| + stopped bool |
| + wg sync.WaitGroup |
| +} |
| + |
| +func newReplicaProber(hub *TunnelHub, probe replicaProbeFunc, clock replicaProbeClock) *replicaProber { |
| + if clock == nil { |
| + clock = replicaRealClock{} |
| + } |
| + if probe == nil { |
| + probe = hub.probeReplica |
| + } |
| + return &replicaProber{hub: hub, probe: probe, clock: clock, jobs: make(map[replicaSlot]*replicaJob), routes: make(map[string]registry.Route)} |
| +} |
| + |
| +// Sync is deliberately not called by Reload until Task 3 supplies the fleet |
| +// arm's validated set. This additional fence keeps legacy rows inert even if |
| +// a caller accidentally supplies the complete route listing. |
| +func (p *replicaProber) Sync(routes []registry.Route) { |
| + p.mu.Lock() |
| + defer p.mu.Unlock() |
| + if p.stopped { |
| + return |
| + } |
| + want := make(map[replicaSlot]registry.Route) |
| + hosts := make(map[string]registry.Route) |
| + duplicate := make(map[string]bool) |
| + for _, rt := range routes { |
| + if !rt.ValidReplicaProjection() || rt.FleetBoxes == "" || rt.Account == "" || rt.App == "" || rt.HA || rt.Hibernate || (rt.Kind != "instance" && !rt.IsForward()) { |
| + continue |
| + } |
| + if _, ok := hosts[rt.Host]; ok { |
| + duplicate[rt.Host] = true |
| + } |
| + hosts[rt.Host] = rt |
| + } |
| + for host, rt := range hosts { |
| + if duplicate[host] { |
| + delete(hosts, host) |
| + continue |
| + } |
| + var boxes []string |
| + _ = json.Unmarshal([]byte(rt.FleetBoxes), &boxes) |
| + for _, box := range boxes { |
| + want[replicaSlot{host, box}] = rt |
| + } |
| + } |
| + for slot, j := range p.jobs { |
| + rt, ok := want[slot] |
| + if !ok || !sameReplicaJob(j, rt) { |
| + j.cancel() |
| + delete(p.jobs, slot) |
| + } |
| + } |
| + p.routes = hosts |
| + for slot, rt := range want { |
| + if p.jobs[slot] != nil { |
| + continue |
| + } |
| + fleet, _ := registry.FleetPlacement(rt.Region) |
| + ctx, cancel := context.WithCancel(context.Background()) |
| + j := &replicaJob{key: replicaJobKey{rt.Host, rt.ReplicaIncarnation, slot.box, rt.ReplicaRevision}, route: rt, channel: fleet + "/" + slot.box, ctx: ctx, cancel: cancel, done: make(chan struct{})} |
| + p.reset(j, nil, replicaWaiting) |
| + p.jobs[slot] = j |
| + p.wg.Add(1) |
| + go p.run(j) |
| + } |
| +} |
| +func sameReplicaJob(j *replicaJob, rt registry.Route) bool { |
| + r := j.route |
| + return j.key.host == rt.Host && j.key.incarnation == rt.ReplicaIncarnation && j.key.revision == rt.ReplicaRevision && r.Account == rt.Account && r.App == rt.App && r.Region == rt.Region && r.FleetBoxes == rt.FleetBoxes && r.Copies == rt.Copies && r.ServingVersion == rt.ServingVersion && r.GoodVersion == rt.GoodVersion && r.GoodDigest == rt.GoodDigest |
| +} |
| +func (p *replicaProber) reset(j *replicaJob, conn *tunnelConn, reason string) { |
| + j.conn = conn |
| + j.count = upstreamState{} |
| + j.evidence = replicas.Copy{} |
| + fleet, _ := registry.FleetPlacement(j.route.Region) |
| + j.sample = replicas.Copy{Host: j.key.host, Account: j.route.Account, App: j.route.App, Fleet: fleet, Box: j.key.box, Incarnation: j.key.incarnation, AssignmentRevision: j.key.revision, State: "unknown", Reason: reason} |
| + if reason == replicaDisconnected { |
| + j.sample.State = "down" |
| + } |
| +} |
| +func (p *replicaProber) connection(j *replicaJob) *tunnelConn { |
| + c := p.hub.probeConnection(j.channel) |
| + if c != j.conn { |
| + reason := replicaWaiting |
| + if c == nil { |
| + reason = replicaDisconnected |
| + } |
| + p.reset(j, c, reason) |
| + } else if c == nil { |
| + j.sample.State, j.sample.Reason = "down", replicaDisconnected |
| + } |
| + return c |
| +} |
| +func (p *replicaProber) run(j *replicaJob) { |
| + defer p.wg.Done() |
| + defer close(j.done) |
| + tick := p.clock.Ticker(replicaProbeInterval) |
| + defer tick.Stop() |
| + for { |
| + if j.ctx.Err() != nil { |
| + return |
| + } |
| + p.mu.Lock() |
| + conn := p.connection(j) |
| + p.mu.Unlock() |
| + var closed <-chan struct{} |
| + if conn != nil { |
| + closed = conn.closed |
| + ctx, cancel := p.clock.Timeout(j.ctx, replicaProbeTimeout) |
| + watchDone := make(chan struct{}) |
| + go func() { |
| + defer close(watchDone) |
| + select { |
| + case <-closed: |
| + cancel() |
| + case <-ctx.Done(): |
| + } |
| + }() |
| + c, err := p.probe(ctx, j.channel, j.key.host) |
| + p.record(j, conn, c, err, context.Cause(ctx)) |
| + cancel() |
| + <-watchDone |
| + } |
| + select { |
| + case <-j.ctx.Done(): |
| + return |
| + case <-tick.C(): |
| + case <-closed: |
| + p.mu.Lock() |
| + p.connection(j) |
| + p.mu.Unlock() |
| + // A closed notice stays closed. Wait for cadence before looking for |
| + // its successor; readers already exclude the closed connection. |
| + select { |
| + case <-j.ctx.Done(): |
| + return |
| + case <-tick.C(): |
| + } |
| + } |
| + } |
| +} |
| +func (p *replicaProber) record(j *replicaJob, conn *tunnelConn, c replicas.Copy, err, cause error) { |
| + p.mu.Lock() |
| + defer p.mu.Unlock() |
| + current := p.jobs[replicaSlot{j.key.host, j.key.box}] |
| + if current != j || j.ctx.Err() != nil { |
| + return |
| + } |
| + if p.hub.probeConnection(j.channel) != conn || conn.generation != j.conn.generation { |
| + p.connection(j) |
| + return |
| + } |
| + if errors.Is(cause, context.Canceled) || (cause == nil && errors.Is(err, context.Canceled)) { |
| + return |
| + } |
| + reason := "" |
| + if err != nil || cause != nil { |
| + reason = replicaFailed |
| + } else if !replicaEvidenceMatches(j, c) || !p.hub.matchReplicaBoot(conn, c.BootID) { |
| + current.count = upstreamState{} |
| + current.sample.Healthy = false |
| + current.sample.State, current.sample.Reason = "unknown", replicaStale |
| + return |
| + } else { |
| + old := current.evidence |
| + if old.Generation != c.Generation { |
| + current.count = upstreamState{} |
| + } |
| + current.evidence = c |
| + c.Socket = "" |
| + current.sample = c |
| + if !c.Healthy { |
| + reason = replicaFailed |
| + } |
| + } |
| + var failure error |
| + if reason != "" { |
| + failure = errors.New(reason) |
| + } |
| + current.count.recordProbe(failure, replicaProbeFail, replicaProbeRise, p.clock.Now()) |
| + current.sample.Healthy = current.count.up |
| + current.sample.ObservedAt = p.clock.Now() |
| + if current.count.up { |
| + current.sample.State, current.sample.Reason = "running", reason |
| + } else { |
| + current.sample.State = "unknown" |
| + current.sample.Reason = replicaWaiting |
| + if current.count.fails >= replicaProbeFail { |
| + current.sample.State, current.sample.Reason = "failed", replicaFailed |
| + } |
| + } |
| +} |
| +func replicaEvidenceMatches(j *replicaJob, c replicas.Copy) bool { |
| + r, old := j.route, j.evidence |
| + fleet, _ := registry.FleetPlacement(r.Region) |
| + digest, err := hex.DecodeString(c.Digest) |
| + if c.Host != r.Host || c.Account != r.Account || c.App != r.App || c.Fleet != fleet || c.Box != j.key.box || c.Incarnation != j.key.incarnation || c.AssignmentRevision != j.key.revision || c.BootID == "" || c.Generation == 0 || c.Version == "" || err != nil || len(digest) != 32 || c.State != "running" || c.WorkersRunning < 0 || c.WorkersDeclared < c.WorkersRunning { |
| + return false |
| + } |
| + // GoodDigest is the platform artifact digest too. A different version |
| + // may legitimately be serving during a rolling deployment. |
| + if r.ServingVersion != "" && c.Version != r.ServingVersion { |
| + return false |
| + } |
| + if r.GoodVersion == c.Version && r.GoodDigest != "" && c.Digest != r.GoodDigest { |
| + return false |
| + } |
| + if old.BootID != "" && (old.BootID != c.BootID || c.Generation < old.Generation || (c.Generation == old.Generation && (c.Version != old.Version || c.Digest != old.Digest))) { |
| + return false |
| + } |
| + return true |
| +} |
| + |
| +func (p *replicaProber) snapshotLocked(rt registry.Route) replicas.Snapshot { |
| + s := replicas.Snapshot{Host: rt.Host, Account: rt.Account, App: rt.App, Incarnation: rt.ReplicaIncarnation, Revision: rt.ReplicaRevision, Desired: rt.Copies} |
| + var boxes []string |
| + _ = json.Unmarshal([]byte(rt.FleetBoxes), &boxes) |
| + // FleetBoxes is already canonical and sorted. A single-host read visits |
| + // only its own assignments, regardless of the fleet's total app count. |
| + for _, box := range boxes { |
| + if j := p.jobs[replicaSlot{rt.Host, box}]; j != nil { |
| + p.connection(j) |
| + s.Copies = append(s.Copies, j.sample) |
| + } |
| + } |
| + return s |
| +} |
| +func (p *replicaProber) snapshots() map[string]replicas.Snapshot { |
| + p.mu.Lock() |
| + defer p.mu.Unlock() |
| + out := make(map[string]replicas.Snapshot, len(p.routes)) |
| + for host, rt := range p.routes { |
| + out[host] = p.snapshotLocked(rt) |
| + } |
| + return out |
| +} |
| +func (p *replicaProber) Snapshot(host string) replicas.Snapshot { |
| + p.mu.Lock() |
| + defer p.mu.Unlock() |
| + rt, ok := p.routes[host] |
| + if !ok { |
| + return replicas.Snapshot{} |
| + } |
| + return p.snapshotLocked(rt) |
| +} |
| +func (p *replicaProber) Live(host string) []replicas.Copy { |
| + var live []replicas.Copy |
| + for _, c := range p.Snapshot(host).Copies { |
| + if c.Healthy { |
| + live = append(live, c) |
| + } |
| + } |
| + return live |
| +} |
| + |
| +// Eject is for a pre-dispatch missing channel or a closed tunnel only. An |
| +// ordinary dispatched request error must be left to the health probes. |
| +func (p *replicaProber) Eject(host, box string) { |
| + p.mu.Lock() |
| + defer p.mu.Unlock() |
| + if j := p.jobs[replicaSlot{host, box}]; j != nil { |
| + j.count = upstreamState{} |
| + j.sample.Healthy = false |
| + j.sample.State, j.sample.Reason = "down", replicaDisconnected |
| + } |
| +} |
| +func (p *replicaProber) Stop() { |
| + p.mu.Lock() |
| + p.stopped = true |
| + for _, j := range p.jobs { |
| + j.cancel() |
| + } |
| + p.jobs = make(map[replicaSlot]*replicaJob) |
| + p.routes = make(map[string]registry.Route) |
| + p.mu.Unlock() |
| + p.wg.Wait() |
| +} |
| + |
| +// probeReplica uses the existing h2 transport and never follows a redirect or |
| +// mistakes an edge/login page for a Copy. The box probes GET / itself. |
| +func (h *TunnelHub) probeReplica(ctx context.Context, channel, host string) (replicas.Copy, error) { |
| + ctx, cancel := context.WithTimeout(ctx, replicaProbeTimeout) |
| + defer cancel() |
| + req, err := http.NewRequestWithContext(ctx, http.MethodGet, "https://"+host+replicaProbePath, nil) |
| + if err != nil { |
| + return replicas.Copy{}, err |
| + } |
| + req.Header.Set(tunnelclient.ReplicaProbeHeader, "1") |
| + resp, err := h.transportFor(channel).RoundTrip(req) |
| + if err != nil { |
| + return replicas.Copy{}, err |
| + } |
| + defer resp.Body.Close() |
| + if resp.StatusCode != http.StatusOK { |
| + return replicas.Copy{}, errors.New(replicaFailed) |
| + } |
| + raw, err := io.ReadAll(io.LimitReader(resp.Body, 64*1024+1)) |
| + if err != nil || len(raw) > 64*1024 { |
| + return replicas.Copy{}, errors.New(replicaFailed) |
| + } |
| + var c replicas.Copy |
| + if err := json.Unmarshal(raw, &c); err != nil { |
| + return replicas.Copy{}, errors.New(replicaFailed) |
| + } |
| + return c, nil |
| +} |
| + |
| +// syncReplicaProbes is the explicit Task 3 integration seam. Merely creating |
| +// an edge, reloading legacy routes or reading snapshots starts no job. |
| +func (e *Edge) syncReplicaProbes(routes []registry.Route) { |
| + if e.tunnels == nil { |
| + return |
| + } |
| + e.replicaMu.Lock() |
| + defer e.replicaMu.Unlock() |
| + if e.replicaProbes == nil { |
| + e.replicaProbes = newReplicaProber(e.tunnels, e.ReplicaProbe, nil) |
| + } |
| + e.replicaProbes.Sync(routes) |
| +} |
| +func (e *Edge) ReplicaSnapshots() map[string]replicas.Snapshot { |
| + e.replicaMu.Lock() |
| + p := e.replicaProbes |
| + e.replicaMu.Unlock() |
| + if p == nil { |
| + return map[string]replicas.Snapshot{} |
| + } |
| + return p.snapshots() |
| +} |
| +func (e *Edge) stopReplicaProbes() { |
| + e.replicaMu.Lock() |
| + p := e.replicaProbes |
| + e.replicaMu.Unlock() |
| + if p != nil { |
| + p.Stop() |
| + } |
| +} |
diff --git a/internal/edge/replicaprober_test.go b/internal/edge/replicaprober_test.go| new file mode 100644 |
| index 000000000..f99db4b63 |
| --- /dev/null |
| +++ b/internal/edge/replicaprober_test.go |
| @@ -0,0 +1,762 @@ |
| +package edge |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "fmt" |
| + "net" |
| + "net/http" |
| + "net/http/httptest" |
| + "strings" |
| + "sync" |
| + "sync/atomic" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/registry" |
| + "github.com/carlosframework/platform/internal/replicas" |
| + "github.com/carlosframework/platform/internal/tunnelclient" |
| +) |
| + |
| +func TestReplicaProbeFailureWithoutTunnelLoss(t *testing.T) { |
| + clock := newReplicaTestClock() |
| + hub, rt := replicaHubFixture(t, 1) |
| + var unhealthy atomic.Bool |
| + p := newReplicaProber(hub, func(context.Context, string, string) (replicas.Copy, error) { |
| + c := replicaTestCopy(rt, "box-00") |
| + c.Healthy = !unhealthy.Load() |
| + return c, nil |
| + }, clock) |
| + t.Cleanup(p.Stop) |
| + p.Sync([]registry.Route{rt}) |
| + replicaSettled(t, clock, 1) |
| + if len(p.Live(rt.Host)) != 0 { |
| + t.Fatal("copy started healthy") |
| + } |
| + clock.advance(time.Second) |
| + replicaSettled(t, clock, 2) |
| + if len(p.Live(rt.Host)) != 1 { |
| + t.Fatal("two passes did not admit") |
| + } |
| + unhealthy.Store(true) |
| + clock.advance(time.Second) |
| + replicaSettled(t, clock, 3) |
| + if len(p.Live(rt.Host)) != 1 { |
| + t.Fatal("one failure ejected") |
| + } |
| + clock.advance(time.Second) |
| + replicaSettled(t, clock, 4) |
| + healthyAfterTwoFailures := len(p.Live(rt.Host)) != 0 |
| + unhealthy.Store(false) |
| + clock.advance(time.Second) |
| + replicaSettled(t, clock, 5) |
| + if len(p.Live(rt.Host)) != 0 { |
| + t.Fatal("one pass readmitted") |
| + } |
| + clock.advance(time.Second) |
| + replicaSettled(t, clock, 6) |
| + healthyAfterTwoPasses := len(p.Live(rt.Host)) == 1 |
| + tunnelConnected := hub.State("pi/box-00") == "connected" |
| + // TestReplicaProbeFailureWithoutTunnelLoss |
| + if !tunnelConnected || healthyAfterTwoFailures || !healthyAfterTwoPasses { |
| + t.Fatal("probe state did not follow app health") |
| + } |
| +} |
| + |
| +type replicaTestTimer struct { |
| + at time.Time |
| + cancel context.CancelCauseFunc |
| +} |
| +type replicaTestTicker struct { |
| + clock *replicaTestClock |
| + ch chan time.Time |
| + every time.Duration |
| + next time.Time |
| +} |
| + |
| +func (t *replicaTestTicker) C() <-chan time.Time { return t.ch } |
| +func (t *replicaTestTicker) Stop() { |
| + t.clock.mu.Lock() |
| + delete(t.clock.tickers, t) |
| + t.clock.mu.Unlock() |
| +} |
| + |
| +type replicaTestClock struct { |
| + mu sync.Mutex |
| + now time.Time |
| + tickers map[*replicaTestTicker]bool |
| + timers map[*replicaTestTimer]bool |
| + completed int |
| + started int |
| +} |
| + |
| +func newReplicaTestClock() *replicaTestClock { |
| + return &replicaTestClock{now: time.Unix(100, 0), tickers: make(map[*replicaTestTicker]bool), timers: make(map[*replicaTestTimer]bool)} |
| +} |
| +func (c *replicaTestClock) Now() time.Time { c.mu.Lock(); defer c.mu.Unlock(); return c.now } |
| +func (c *replicaTestClock) Ticker(d time.Duration) replicaProbeTicker { |
| + c.mu.Lock() |
| + defer c.mu.Unlock() |
| + t := &replicaTestTicker{c, make(chan time.Time, 1), d, c.now.Add(d)} |
| + c.tickers[t] = true |
| + return t |
| +} |
| +func (c *replicaTestClock) Timeout(parent context.Context, d time.Duration) (context.Context, context.CancelFunc) { |
| + if d != time.Second { |
| + panic("replica probe timeout changed") |
| + } |
| + ctx, cancel := context.WithCancelCause(parent) |
| + c.mu.Lock() |
| + timer := &replicaTestTimer{c.now.Add(d), cancel} |
| + c.timers[timer] = true |
| + c.started++ |
| + c.mu.Unlock() |
| + var once sync.Once |
| + return ctx, func() { |
| + cancel(context.Canceled) |
| + once.Do(func() { c.mu.Lock(); delete(c.timers, timer); c.completed++; c.mu.Unlock() }) |
| + } |
| +} |
| +func (c *replicaTestClock) advance(d time.Duration) { |
| + c.mu.Lock() |
| + c.now = c.now.Add(d) |
| + for timer := range c.timers { |
| + if !timer.at.After(c.now) { |
| + timer.cancel(context.DeadlineExceeded) |
| + } |
| + } |
| + for tick := range c.tickers { |
| + if !tick.next.After(c.now) { |
| + select { |
| + case tick.ch <- c.now: |
| + default: |
| + } |
| + tick.next = c.now.Add(tick.every) |
| + } |
| + } |
| + c.mu.Unlock() |
| +} |
| +func replicaAwait(t *testing.T, what string, f func() bool) { |
| + t.Helper() |
| + deadline := time.Now().Add(5 * time.Second) |
| + for !f() { |
| + if time.Now().After(deadline) { |
| + t.Fatal("timed out: " + what) |
| + } |
| + time.Sleep(time.Millisecond) |
| + } |
| +} |
| +func replicaSettled(t *testing.T, clock *replicaTestClock, n int) { |
| + t.Helper() |
| + replicaAwait(t, "completed probes", func() bool { clock.mu.Lock(); defer clock.mu.Unlock(); return clock.completed >= n }) |
| +} |
| +func replicaHubFixture(t *testing.T, n int) (*TunnelHub, registry.Route) { |
| + t.Helper() |
| + h := NewTunnelHub("tunnel.example.com", nil) |
| + var boxes []string |
| + for i := 0; i < n; i++ { |
| + box := fmt.Sprintf("box-%02d", i) |
| + boxes = append(boxes, box) |
| + replicaConnect(h, "pi/"+box) |
| + } |
| + t.Cleanup(func() { |
| + for _, box := range boxes { |
| + h.CloseChannel("pi/" + box) |
| + } |
| + }) |
| + raw, _ := json.Marshal(boxes) |
| + rt := registry.Route{Host: "shop.example.com", Account: "bab", App: "shop", Region: "fleet/pi", Kind: "instance", Stateless: true, FleetBoxes: string(raw), Copies: n, ReplicaIncarnation: "life", ReplicaRevision: 7} |
| + return h, rt |
| +} |
| +func replicaConnect(h *TunnelHub, channel string) *tunnelConn { |
| + h.mu.Lock() |
| + defer h.mu.Unlock() |
| + if old := h.conns[channel]; old != nil { |
| + old.raw.Close() |
| + } |
| + a, b := net.Pipe() |
| + b.Close() |
| + wire := &tunnelWire{Conn: a, closed: make(chan struct{})} |
| + h.nextGeneration++ |
| + tc := &tunnelConn{raw: wire, generation: h.nextGeneration, closed: wire.closed} |
| + h.conns[channel] = tc |
| + return tc |
| +} |
| +func replicaTestCopy(rt registry.Route, box string) replicas.Copy { |
| + fleet, _ := registry.FleetPlacement(rt.Region) |
| + return replicas.Copy{Host: rt.Host, Account: rt.Account, App: rt.App, Fleet: fleet, Box: box, BootID: "boot", Incarnation: rt.ReplicaIncarnation, AssignmentRevision: rt.ReplicaRevision, Generation: 10, Version: "v1", Digest: strings.Repeat("a", 64), State: "running", Healthy: true} |
| +} |
| + |
| +func TestReplicaProbeRejectsOldIdentity(t *testing.T) { |
| + for _, field := range []string{"host", "account", "app", "fleet", "box", "lifetime", "revision", "boot", "version", "digest", "empty-digest", "generation", "state"} { |
| + t.Run(field, func(t *testing.T) { |
| + clock := newReplicaTestClock() |
| + hub, rt := replicaHubFixture(t, 1) |
| + var bad atomic.Bool |
| + p := newReplicaProber(hub, func(context.Context, string, string) (replicas.Copy, error) { |
| + c := replicaTestCopy(rt, "box-00") |
| + if bad.Load() { |
| + switch field { |
| + case "host": |
| + c.Host = "other.example.com" |
| + case "account": |
| + c.Account = "other" |
| + case "app": |
| + c.App = "other" |
| + case "fleet": |
| + c.Fleet = "other" |
| + case "box": |
| + c.Box = "other" |
| + case "lifetime": |
| + c.Incarnation = "old" |
| + case "revision": |
| + c.AssignmentRevision-- |
| + case "boot": |
| + c.BootID = "old" |
| + case "version": |
| + c.Version = "v0" |
| + case "digest": |
| + c.Digest = strings.Repeat("b", 64) |
| + case "empty-digest": |
| + c.Digest = "" |
| + case "generation": |
| + c.Generation-- |
| + case "state": |
| + c.State = "starting" |
| + } |
| + } |
| + return c, nil |
| + }, clock) |
| + t.Cleanup(p.Stop) |
| + p.Sync([]registry.Route{rt}) |
| + replicaSettled(t, clock, 1) |
| + clock.advance(time.Second) |
| + replicaSettled(t, clock, 2) |
| + bad.Store(true) |
| + clock.advance(time.Second) |
| + replicaSettled(t, clock, 3) |
| + if len(p.Live(rt.Host)) != 0 || p.Snapshot(rt.Host).Copies[0].Reason != replicaStale { |
| + t.Fatal("old identity admitted") |
| + } |
| + }) |
| + } |
| + t.Run("old tunnel generation", func(t *testing.T) { |
| + clock := newReplicaTestClock() |
| + hub, rt := replicaHubFixture(t, 1) |
| + entered, release := make(chan struct{}), make(chan struct{}) |
| + var calls atomic.Int32 |
| + p := newReplicaProber(hub, func(context.Context, string, string) (replicas.Copy, error) { |
| + if calls.Add(1) == 1 { |
| + close(entered) |
| + func() { |
| + select { |
| + case <-release: |
| + case <-time.After(5 * time.Second): |
| + t.Error("late callback was not released") |
| + } |
| + }() |
| + } |
| + return replicaTestCopy(rt, "box-00"), nil |
| + }, clock) |
| + t.Cleanup(p.Stop) |
| + p.Sync([]registry.Route{rt}) |
| + replicaAwait(t, "old probe entered", func() bool { |
| + select { |
| + case <-entered: |
| + return true |
| + default: |
| + return false |
| + } |
| + }) |
| + // Replace the map entry without closing the old notice to isolate the |
| + // generation acceptance gate from the close-notice cancellation gate. |
| + hub.mu.Lock() |
| + old := hub.conns["pi/box-00"] |
| + delete(hub.conns, "pi/box-00") |
| + hub.mu.Unlock() |
| + replicaConnect(hub, "pi/box-00") |
| + close(release) |
| + replicaSettled(t, clock, 1) |
| + p.mu.Lock() |
| + accepted := p.jobs[replicaSlot{rt.Host, "box-00"}].sample.Generation != 0 |
| + p.mu.Unlock() |
| + if accepted { |
| + t.Fatal("old connection supplied evidence") |
| + } |
| + clock.advance(time.Second) |
| + replicaSettled(t, clock, 2) |
| + if len(p.Live(rt.Host)) != 0 { |
| + t.Fatal("reconnect did not start unknown") |
| + } |
| + clock.advance(time.Second) |
| + replicaSettled(t, clock, 3) |
| + if len(p.Live(rt.Host)) != 1 { |
| + t.Fatal("reconnect did not rise") |
| + } |
| + old.raw.Close() |
| + }) |
| + t.Run("serving build changes", func(t *testing.T) { |
| + clock := newReplicaTestClock() |
| + hub, rt := replicaHubFixture(t, 1) |
| + var newer atomic.Bool |
| + p := newReplicaProber(hub, func(context.Context, string, string) (replicas.Copy, error) { |
| + c := replicaTestCopy(rt, "box-00") |
| + if newer.Load() { |
| + c.Generation++ |
| + c.Version = "v2" |
| + c.Digest = strings.Repeat("b", 64) |
| + } |
| + return c, nil |
| + }, clock) |
| + t.Cleanup(p.Stop) |
| + p.Sync([]registry.Route{rt}) |
| + replicaSettled(t, clock, 1) |
| + clock.advance(time.Second) |
| + replicaSettled(t, clock, 2) |
| + newer.Store(true) |
| + clock.advance(time.Second) |
| + replicaSettled(t, clock, 3) |
| + if len(p.Live(rt.Host)) != 0 { |
| + t.Fatal("new build inherited old health") |
| + } |
| + clock.advance(time.Second) |
| + replicaSettled(t, clock, 4) |
| + if len(p.Live(rt.Host)) != 1 || p.Live(rt.Host)[0].Version != "v2" { |
| + t.Fatal("new serving build never rose") |
| + } |
| + }) |
| +} |
| + |
| +func TestReplicaProbeConcurrentBound(t *testing.T) { |
| + clock := newReplicaTestClock() |
| + hub, rt := replicaHubFixture(t, 64) |
| + var blocked atomic.Bool |
| + var active, maxActive [64]atomic.Int32 |
| + var calls atomic.Int32 |
| + p := newReplicaProber(hub, func(ctx context.Context, channel, host string) (replicas.Copy, error) { |
| + var i int |
| + fmt.Sscanf(channel, "pi/box-%d", &i) |
| + n := active[i].Add(1) |
| + defer active[i].Add(-1) |
| + if n > maxActive[i].Load() { |
| + maxActive[i].Store(n) |
| + } |
| + calls.Add(1) |
| + if blocked.Load() { |
| + <-ctx.Done() |
| + return replicas.Copy{}, ctx.Err() |
| + } |
| + return replicaTestCopy(rt, fmt.Sprintf("box-%02d", i)), nil |
| + }, clock) |
| + t.Cleanup(p.Stop) |
| + p.Sync([]registry.Route{rt}) |
| + replicaSettled(t, clock, 64) |
| + if len(p.Live(rt.Host)) != 0 { |
| + t.Fatal("started healthy") |
| + } |
| + clock.advance(999 * time.Millisecond) |
| + if calls.Load() != 64 { |
| + t.Fatal("cadence faster than 1s") |
| + } |
| + clock.advance(time.Millisecond) |
| + replicaSettled(t, clock, 128) |
| + if len(p.Live(rt.Host)) != 64 { |
| + t.Fatal("rise exceeds 3s") |
| + } |
| + blocked.Store(true) |
| + for n := 0; n < 3; n++ { |
| + clock.advance(time.Second) |
| + want := int32(192 + 64*n) |
| + replicaAwait(t, "64 independent probes", func() bool { return calls.Load() >= want }) |
| + } |
| + if len(p.Live(rt.Host)) != 0 { |
| + t.Fatal("ejection exceeds 3s with 64 blocked copies") |
| + } |
| + blocked.Store(false) |
| + clock.advance(time.Second) |
| + replicaSettled(t, clock, 384) |
| + clock.advance(time.Second) |
| + replicaSettled(t, clock, 448) |
| + if len(p.Live(rt.Host)) != 64 { |
| + t.Fatal("recovery exceeds 3s") |
| + } |
| + hub.CloseChannel("pi/box-00") |
| + if len(p.Live(rt.Host)) != 63 { |
| + t.Fatal("closed tunnel not removed immediately") |
| + } |
| + for i := range maxActive { |
| + if maxActive[i].Load() != 1 { |
| + t.Fatalf("box %d concurrency=%d", i, maxActive[i].Load()) |
| + } |
| + } |
| +} |
| + |
| +func TestReplicaProbeCancellationAndReplacement(t *testing.T) { |
| + t.Run("client cancellation", func(t *testing.T) { |
| + clock := newReplicaTestClock() |
| + hub, rt := replicaHubFixture(t, 1) |
| + var canceled atomic.Bool |
| + p := newReplicaProber(hub, func(context.Context, string, string) (replicas.Copy, error) { |
| + if canceled.Load() { |
| + return replicas.Copy{}, context.Canceled |
| + } |
| + return replicaTestCopy(rt, "box-00"), nil |
| + }, clock) |
| + t.Cleanup(p.Stop) |
| + p.Sync([]registry.Route{rt}) |
| + replicaSettled(t, clock, 1) |
| + clock.advance(time.Second) |
| + replicaSettled(t, clock, 2) |
| + canceled.Store(true) |
| + for n := 3; n <= 6; n++ { |
| + clock.advance(time.Second) |
| + replicaSettled(t, clock, n) |
| + } |
| + if len(p.Live(rt.Host)) != 1 { |
| + t.Fatal("client cancellation ejected healthy copy") |
| + } |
| + }) |
| + t.Run("late retired job", func(t *testing.T) { |
| + clock := newReplicaTestClock() |
| + hub, rt := replicaHubFixture(t, 1) |
| + entered, release := make(chan struct{}), make(chan struct{}) |
| + var calls atomic.Int32 |
| + oldRT := rt |
| + p := newReplicaProber(hub, func(context.Context, string, string) (replicas.Copy, error) { |
| + n := calls.Add(1) |
| + if n == 3 { |
| + close(entered) |
| + func() { |
| + select { |
| + case <-release: |
| + case <-time.After(5 * time.Second): |
| + t.Error("late callback was not released") |
| + } |
| + }() |
| + return replicaTestCopy(oldRT, "box-00"), nil |
| + } |
| + c := replicaTestCopy(oldRT, "box-00") |
| + if n >= 4 { |
| + c.AssignmentRevision++ |
| + } |
| + return c, nil |
| + }, clock) |
| + t.Cleanup(p.Stop) |
| + p.Sync([]registry.Route{rt}) |
| + replicaSettled(t, clock, 1) |
| + clock.advance(time.Second) |
| + replicaSettled(t, clock, 2) |
| + p.mu.Lock() |
| + old := p.jobs[replicaSlot{rt.Host, "box-00"}] |
| + p.mu.Unlock() |
| + p.Sync([]registry.Route{rt}) |
| + p.mu.Lock() |
| + same := p.jobs[replicaSlot{rt.Host, "box-00"}] == old |
| + p.mu.Unlock() |
| + if !same || len(p.Live(rt.Host)) != 1 { |
| + t.Fatal("unchanged Sync discarded healthy job") |
| + } |
| + clock.advance(time.Second) |
| + replicaAwait(t, "late request entered", func() bool { |
| + select { |
| + case <-entered: |
| + return true |
| + default: |
| + return false |
| + } |
| + }) |
| + rt.ReplicaRevision++ |
| + p.Sync([]registry.Route{rt}) |
| + replicaSettled(t, clock, 3) |
| + if len(p.Live(rt.Host)) != 0 { |
| + t.Fatal("replacement inherited health") |
| + } |
| + clock.advance(time.Second) |
| + replicaSettled(t, clock, 4) |
| + if len(p.Live(rt.Host)) != 1 { |
| + t.Fatal("replacement did not become healthy") |
| + } |
| + // Simulate a response that read its uncancelled cause just before |
| + // Sync retired the job, but only acquired the result lock afterward. |
| + p.record(old, hub.probeConnection("pi/box-00"), replicaTestCopy(oldRT, "box-00"), nil, nil) |
| + if p.Snapshot(rt.Host).Copies[0].AssignmentRevision != rt.ReplicaRevision { |
| + t.Fatal("stale job published late evidence") |
| + } |
| + close(release) |
| + replicaSettled(t, clock, 5) |
| + replicaAwait(t, "old job ended", func() bool { |
| + select { |
| + case <-old.done: |
| + return true |
| + default: |
| + return false |
| + } |
| + }) |
| + live := p.Live(rt.Host) |
| + if len(live) != 1 || live[0].AssignmentRevision != rt.ReplicaRevision { |
| + t.Fatal("retired job changed or ejected its healthy replacement") |
| + } |
| + }) |
| +} |
| + |
| +func TestReplicaProbeStartsUnknown(t *testing.T) { |
| + clock := newReplicaTestClock() |
| + hub, rt := replicaHubFixture(t, 1) |
| + var calls atomic.Int32 |
| + p := newReplicaProber(hub, func(ctx context.Context, _, _ string) (replicas.Copy, error) { |
| + calls.Add(1) |
| + <-ctx.Done() |
| + return replicas.Copy{}, ctx.Err() |
| + }, clock) |
| + t.Cleanup(p.Stop) |
| + p.Sync([]registry.Route{rt}) |
| + replicaAwait(t, "first probe in flight", func() bool { return calls.Load() == 1 }) |
| + if len(p.Live(rt.Host)) != 0 || p.Snapshot(rt.Host).Copies[0].Healthy { |
| + t.Fatal("copy started healthy before any answer") |
| + } |
| +} |
| + |
| +func TestReplicaProbeSnapshotAndSync(t *testing.T) { |
| + clock := newReplicaTestClock() |
| + hub, rt := replicaHubFixture(t, 1) |
| + p := newReplicaProber(hub, func(context.Context, string, string) (replicas.Copy, error) { |
| + return replicaTestCopy(rt, "box-00"), nil |
| + }, clock) |
| + t.Cleanup(p.Stop) |
| + legacy := rt |
| + legacy.FleetBoxes = "" |
| + legacy.Copies = 0 |
| + legacy.ReplicaRevision = 0 |
| + legacy.ReplicaIncarnation = "" |
| + p.Sync([]registry.Route{legacy}) |
| + if len(p.snapshots()) != 0 { |
| + t.Fatal("legacy row started probes") |
| + } |
| + p.Sync([]registry.Route{rt}) |
| + replicaSettled(t, clock, 1) |
| + clock.advance(time.Second) |
| + replicaSettled(t, clock, 2) |
| + snapshots := p.snapshots() |
| + s := snapshots[rt.Host] |
| + s.Copies[0].Healthy = false |
| + s.Copies[0].BootID = "forged" |
| + delete(snapshots, rt.Host) |
| + if len(p.Live(rt.Host)) != 1 || p.Live(rt.Host)[0].BootID != "boot" { |
| + t.Fatal("caller mutated prober state") |
| + } |
| + p.Eject(rt.Host, "box-00") |
| + if len(p.Live(rt.Host)) != 0 { |
| + t.Fatal("Eject kept copy live") |
| + } |
| + clock.advance(time.Second) |
| + replicaSettled(t, clock, 3) |
| + if len(p.Live(rt.Host)) != 0 { |
| + t.Fatal("Eject readmitted after one pass") |
| + } |
| + clock.advance(time.Second) |
| + replicaSettled(t, clock, 4) |
| + if len(p.Live(rt.Host)) != 1 { |
| + t.Fatal("Eject never recovered") |
| + } |
| + p.Sync(nil) |
| + if len(p.snapshots()) != 0 { |
| + t.Fatal("removed assignment retained snapshot") |
| + } |
| + p.Stop() |
| + p.Sync([]registry.Route{rt}) |
| + if len(p.snapshots()) != 0 { |
| + t.Fatal("Sync restarted a stopped prober") |
| + } |
| +} |
| + |
| +func replicaRealTunnel(t *testing.T, h http.Handler) (*TunnelHub, func()) { |
| + t.Helper() |
| + hub := NewTunnelHub("tunnel.example.com", nil) |
| + hub.SetDynamicAuth(map[string]string{"pi/box-00": sha256Hex("probe-token")}) |
| + server := httptest.NewServer(hub) |
| + stop := startFakeRemoteHost(t, server.URL, "pi/box-00", "probe-token", h) |
| + t.Cleanup(func() { stop(); hub.CloseChannel("pi/box-00"); server.Close() }) |
| + waitForTunnelState(t, hub, "pi/box-00", "connected", 5*time.Second) |
| + return hub, stop |
| +} |
| + |
| +func TestReplicaProbeStatusRangeHub(t *testing.T) { |
| + var status atomic.Int32 |
| + status.Store(200) |
| + var hits atomic.Int32 |
| + box, act := replicaLanding(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + hits.Add(1) |
| + if r.URL.Path != "/" { |
| + t.Error("probe followed redirect") |
| + } |
| + w.Header().Set("Location", "/login") |
| + w.WriteHeader(int(status.Load())) |
| + })) |
| + // Match the tunnel label while retaining the 1a actual-serving-socket fixture. |
| + box.box = "box-00" |
| + act.copy.Box = "box-00" |
| + act.copy.Digest = strings.Repeat("a", 64) |
| + rt, _ := box.reg.Get("shop.example.com") |
| + rt.FleetBoxes = `["box-00"]` |
| + rt.Copies = 1 |
| + if err := box.reg.Upsert(*rt); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := box.Reload(); err != nil { |
| + t.Fatal(err) |
| + } |
| + var boxMu sync.Mutex |
| + hub, _ := replicaRealTunnel(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { boxMu.Lock(); defer boxMu.Unlock(); box.ServeHTTP(w, r) })) |
| + for _, code := range []int{200, 302, 404, 499, 500, 503} { |
| + t.Run(fmt.Sprint(code), func(t *testing.T) { |
| + status.Store(int32(code)) |
| + before := hits.Load() |
| + c, err := hub.probeReplica(t.Context(), "pi/box-00", rt.Host) |
| + if err != nil || c.Healthy != replicas.HealthyStatus(code) || hits.Load() != before+1 { |
| + t.Fatalf("code=%d copy=%+v err=%v hits=%d", code, c, err, hits.Load()-before) |
| + } |
| + }) |
| + } |
| + for _, bad := range []int{-1, 0, 99, 100, 199, 600} { |
| + if replicas.HealthyStatus(bad) { |
| + t.Fatalf("invalid status %d healthy", bad) |
| + } |
| + } |
| +} |
| + |
| +func TestReplicaProbeAdapterRefusesNonCopy(t *testing.T) { |
| + var mode atomic.Int32 |
| + hub, _ := replicaRealTunnel(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + if r.Method != "GET" || r.URL.Path != replicaProbePath || r.Header.Get(tunnelclient.ReplicaProbeHeader) != "1" { |
| + t.Error("bad private probe request") |
| + } |
| + switch mode.Load() { |
| + case 0: |
| + w.Header().Set("Location", "/login") |
| + w.WriteHeader(302) |
| + case 1: |
| + _, _ = w.Write([]byte("<html>login</html>")) |
| + case 2: |
| + _, _ = w.Write([]byte(strings.Repeat("x", 65537))) |
| + case 3: |
| + _, _ = w.Write([]byte(`{} {}`)) |
| + } |
| + })) |
| + for m := int32(0); m < 4; m++ { |
| + mode.Store(m) |
| + if _, err := hub.probeReplica(t.Context(), "pi/box-00", "shop.example.com"); err == nil { |
| + t.Fatalf("mode %d accepted", m) |
| + } |
| + } |
| +} |
| + |
| +func TestReplicaProbeTunnelNoticeAndEdgeSnapshot(t *testing.T) { |
| + _, rt := replicaHubFixture(t, 1) |
| + hub, stopRemote := replicaRealTunnel(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + _ = json.NewEncoder(w).Encode(replicaTestCopy(rt, "box-00")) |
| + })) |
| + first := hub.probeConnection("pi/box-00") |
| + if first == nil || first.generation == 0 { |
| + t.Fatal("missing connection generation") |
| + } |
| + e, err := New(openReg(t), nil) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(e.probers.Stop) |
| + t.Cleanup(e.stopReplicaProbes) |
| + e.EnableTunnels(hub) |
| + if len(e.ReplicaSnapshots()) != 0 || e.replicaProbes != nil { |
| + t.Fatal("snapshot read started probing") |
| + } |
| + var calls atomic.Int32 |
| + e.ReplicaProbe = func(ctx context.Context, channel, host string) (replicas.Copy, error) { |
| + calls.Add(1) |
| + return hub.probeReplica(ctx, channel, host) |
| + } |
| + e.syncReplicaProbes([]registry.Route{rt}) |
| + replicaAwait(t, "edge snapshot became healthy", func() bool { s := e.ReplicaSnapshots()[rt.Host]; return len(s.Copies) == 1 && s.Copies[0].Healthy }) |
| + if calls.Load() < 2 { |
| + t.Fatal("injectable probe not used") |
| + } |
| + hub.CloseChannel("pi/box-00") |
| + if e.ReplicaSnapshots()[rt.Host].Copies[0].Healthy { |
| + t.Fatal("closed tunnel still live") |
| + } |
| + replicaAwait(t, "real reconnect", func() bool { c := hub.probeConnection("pi/box-00"); return c != nil && c != first }) |
| + next := hub.probeConnection("pi/box-00") |
| + if next.generation <= first.generation { |
| + t.Fatal("connection generation reused") |
| + } |
| + if e.ReplicaSnapshots()[rt.Host].Copies[0].Healthy { |
| + t.Fatal("reconnect retained health") |
| + } |
| + stopRemote() |
| + first = next |
| + replicaAwait(t, "peer EOF notice", func() bool { |
| + select { |
| + case <-first.closed: |
| + return true |
| + default: |
| + return false |
| + } |
| + }) |
| + if e.ReplicaSnapshots()[rt.Host].Copies[0].Healthy { |
| + t.Fatal("closed peer kept healthy snapshot") |
| + } |
| +} |
| + |
| +func TestReplicaProbeBootPinSurvivesAssignment(t *testing.T) { |
| + clock := newReplicaTestClock() |
| + hub, rt := replicaHubFixture(t, 1) |
| + base := rt |
| + var changed atomic.Bool |
| + p := newReplicaProber(hub, func(context.Context, string, string) (replicas.Copy, error) { |
| + c := replicaTestCopy(base, "box-00") |
| + if changed.Load() { |
| + c.AssignmentRevision++ |
| + c.BootID = "other-boot" |
| + } |
| + return c, nil |
| + }, clock) |
| + t.Cleanup(p.Stop) |
| + p.Sync([]registry.Route{rt}) |
| + replicaSettled(t, clock, 1) |
| + clock.advance(time.Second) |
| + replicaSettled(t, clock, 2) |
| + changed.Store(true) |
| + rt.ReplicaRevision++ |
| + p.Sync([]registry.Route{rt}) |
| + replicaSettled(t, clock, 3) |
| + clock.advance(time.Second) |
| + replicaSettled(t, clock, 4) |
| + if len(p.Live(rt.Host)) != 0 || p.Snapshot(rt.Host).Copies[0].Reason != replicaStale { |
| + t.Fatal("assignment replacement erased tunnel boot pin") |
| + } |
| +} |
| + |
| +func TestReplicaProbeAssignmentBuildEvidence(t *testing.T) { |
| + for _, kind := range []string{"serving-version", "artifact-digest"} { |
| + t.Run(kind, func(t *testing.T) { |
| + clock := newReplicaTestClock() |
| + hub, rt := replicaHubFixture(t, 1) |
| + if kind == "serving-version" { |
| + rt.ServingVersion = "v2" |
| + } else { |
| + rt.GoodVersion = "v1" |
| + rt.GoodDigest = strings.Repeat("b", 64) |
| + } |
| + p := newReplicaProber(hub, func(context.Context, string, string) (replicas.Copy, error) { |
| + return replicaTestCopy(rt, "box-00"), nil |
| + }, clock) |
| + t.Cleanup(p.Stop) |
| + p.Sync([]registry.Route{rt}) |
| + replicaSettled(t, clock, 1) |
| + clock.advance(time.Second) |
| + replicaSettled(t, clock, 2) |
| + if len(p.Live(rt.Host)) != 0 || p.Snapshot(rt.Host).Copies[0].Reason != replicaStale { |
| + t.Fatal("assignment build evidence was ignored") |
| + } |
| + }) |
| + } |
| +} |
diff --git a/internal/edge/tunnel.go b/internal/edge/tunnel.go| index 667561ec3..2108b1c0f 100644 |
| --- a/internal/edge/tunnel.go |
| +++ b/internal/edge/tunnel.go |
| @@ -72,9 +72,30 @@ func pingCadence(dynamic bool) (every, timeout time.Duration) { |
| return tunnelPingEvery, tunnelPingTimeout |
| } |
| +// tunnelWire closes its notice on EOF/read failure or a local close. The |
| +// HTTP/2 reader observes peer closure before the periodic ping does. |
| +type tunnelWire struct { |
| + net.Conn |
| + closed chan struct{} |
| + once sync.Once |
| +} |
| + |
| +func (c *tunnelWire) ended() { c.once.Do(func() { close(c.closed) }) } |
| +func (c *tunnelWire) Read(b []byte) (int, error) { |
| + n, err := c.Conn.Read(b) |
| + if err != nil { |
| + c.ended() |
| + } |
| + return n, err |
| +} |
| +func (c *tunnelWire) Close() error { c.ended(); return c.Conn.Close() } |
| + |
| type tunnelConn struct { |
| - cc *http2.ClientConn |
| - raw net.Conn |
| + generation uint64 |
| + probeBoot string // first valid platform answer on this connection; guarded by hub.mu |
| + closed <-chan struct{} |
| + cc *http2.ClientConn |
| + raw net.Conn |
| // dynamic records that this conn authenticated against the registry-backed |
| // (fleet) credential source rather than the static env map — the one fact |
| // ServeHTTP knows and pingLoop needs for pingCadence. |
| @@ -86,10 +107,11 @@ type tunnelConn struct { |
| } |
| type TunnelHub struct { |
| - host string // reserved hostname this hub answers on |
| - clients map[string]string // channel name -> bearer token (static env config, plaintext) |
| - mu sync.Mutex |
| - conns map[string]*tunnelConn |
| + host string // reserved hostname this hub answers on |
| + clients map[string]string // channel name -> bearer token (static env config, plaintext) |
| + mu sync.Mutex |
| + nextGeneration uint64 |
| + conns map[string]*tunnelConn |
| // dynamicAuth is the second, registry-backed credential source: channel |
| // "<fleet>/<label>" -> sha256 hex of its bearer token. Guarded by mu |
| // alongside conns since SetDynamicAuth's rotation path (below) touches |
| @@ -220,6 +242,8 @@ func (h *TunnelHub) ServeHTTP(w http.ResponseWriter, r *http.Request) { |
| conn.Close() |
| return |
| } |
| + wire := &tunnelWire{Conn: conn, closed: make(chan struct{})} |
| + conn = wire |
| tr := &http2.Transport{} |
| cc, err := tr.NewClientConn(conn) |
| if err != nil { |
| @@ -253,7 +277,8 @@ func (h *TunnelHub) ServeHTTP(w http.ResponseWriter, r *http.Request) { |
| if old := h.conns[name]; old != nil { |
| old.raw.Close() // a re-register replaces the previous channel |
| } |
| - h.conns[name] = &tunnelConn{cc: cc, raw: conn, dynamic: viaDynamic, caps: r.Header.Get(tunnelclient.CapsHeader)} |
| + h.nextGeneration++ |
| + h.conns[name] = &tunnelConn{generation: h.nextGeneration, closed: wire.closed, cc: cc, raw: conn, dynamic: viaDynamic, caps: r.Header.Get(tunnelclient.CapsHeader)} |
| h.mu.Unlock() |
| log.Printf("edge: tunnel %s: connected from %s", name, conn.RemoteAddr()) |
| go h.pingLoop(name, cc, conn, viaDynamic) |
| @@ -543,3 +568,32 @@ func (b *reservedBody) Close() error { |
| b.r.release(relBody) |
| return nil |
| } |
| + |
| +// probeConnection identifies the live connection used to judge a probe. A |
| +// closed notice excludes it immediately, without waiting for ping cleanup. |
| +func (h *TunnelHub) probeConnection(name string) *tunnelConn { |
| + if h == nil { |
| + return nil |
| + } |
| + c := h.channel(name) |
| + if c == nil || c.generation == 0 { |
| + return nil |
| + } |
| + select { |
| + case <-c.closed: |
| + return nil |
| + default: |
| + return c |
| + } |
| +} |
| + |
| +// matchReplicaBoot keeps boot evidence on the connection, including across |
| +// assignment job replacements. The caller has already checked generation. |
| +func (h *TunnelHub) matchReplicaBoot(c *tunnelConn, boot string) bool { |
| + h.mu.Lock() |
| + defer h.mu.Unlock() |
| + if c.probeBoot == "" { |
| + c.probeBoot = boot |
| + } |
| + return c.probeBoot == boot |
| +} |
diff --git a/internal/host/agent.go b/internal/host/agent.go| index d9c4e863a..e28c924a8 100644 |
| --- a/internal/host/agent.go |
| +++ b/internal/host/agent.go |
| @@ -1104,8 +1104,8 @@ func runAgent(args []string, buildClaims ClaimFactory) { |
| 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{} } |
| + // Read the current hub view on each private socket request. |
| + readReplicaHealth := e.ReplicaSnapshots |
| healthWG.Add(1) |
| go func() { |
| defer healthWG.Done() |
diff --git a/internal/provision/testdata/plan14-root-reads-chain.tsv b/internal/provision/testdata/plan14-root-reads-chain.tsv| index bf4021847..4ef599357 100644 |
| --- a/internal/provision/testdata/plan14-root-reads-chain.tsv |
| +++ b/internal/provision/testdata/plan14-root-reads-chain.tsv |
| @@ -82,3 +82,4 @@ plan14-root-reads-region-ha-followups.tsv cfb026f1f9d59f325937cbddf26df2d94d5240 |
| plan14-root-reads-region-ha-p3a.tsv f44d209a054eee55fdee54227d419b74c34a9b2fc174c7a0bb74d5c2711a68bb |
| plan14-root-reads-stateless-coordinator-route.tsv 7974cb078e82272605cbc8ef6809c9ae5e0b02edc22ca843cd2ef4b38d9e44e9 |
| plan14-root-reads-stateless-replicas-2.tsv 59c0891618b9befae27ebe04d0a67b08c7f7658bca9f1c78bf6d05eb7a708e82 |
| +plan14-root-reads-stateless-replicas-3.tsv 2c3d58a7cd1c3008e71f0c85ab41c886df496bc0974e1e9ccc9972ae7587c356 |
diff --git a/internal/provision/testdata/plan14-root-reads-stateless-replicas-3.tsv b/internal/provision/testdata/plan14-root-reads-stateless-replicas-3.tsv| new file mode 100644 |
| index 000000000..2414b1dff |
| --- /dev/null |
| +++ b/internal/provision/testdata/plan14-root-reads-stateless-replicas-3.tsv |
| @@ -0,0 +1,45 @@ |
| +# Census overlay stateless-replicas-3, written by census-propose (#369). census-ruling-stateless-replicas-3, approved on #280 before the merge; the approval card is docs/superpowers/notes/census-proposal-stateless-replicas-3.md. |
| +# 2 body, 1 sites, 5 envelope: each changed unit re-frozen at its existing disposition with its claim appended. |
| +# 16 new dispositions: 0 reads re-frozen at their disposition with the claim, 16 new units frozen accepted-legacy, 0 quiet units retired while they read nothing, 0 other. |
| +@legacy a02e5c799c0ab4fefc6cbd35bc424a93c61924373619e65ef0af15d99d97bd12 internal/edge/edge.go RunWithActivatorReady legacy accepted-legacy accepted-legacy;rev3=J4;basis=root-input;rev3=census-ruling-certwarm-wake;basis=registers the cert warm's nudge on OnReload and on the home map's new served-hosts wake (#386); nudge only sends on a buffered channel; no read added, same 5 sites;rev3=census-ruling-edge-roll-blip;basis=the :80/:443 (and dev) listeners are bound on the calling goroutine with net.Listen via listen()/listenAddr (same empty-address defaults as ListenAndServe) before the serve goroutines, which now call Serve/ServeTLS on them, and one log line names the bound addresses; no read added, same 5 sites;rev3=census-ruling-edge-held-streams;basis=the edge in the agent (carlos-edge.service, user carlos): the inline home-map arming (newHomeMap, one boot Refresh, Store, run) moves unchanged into the new Edge.ArmHomeMap and is called here as e.ArmHomeMap(); same refresh, same timeout, same order. The reads are moved, none added.;rev3=census-ruling-agent-start-demo-1;basis=Logs the combined explicit wildcard parents through demoWildcardDomains; no new watcher or read loop.;rev3=census-ruling-region-ha-p3a;basis=P3a Task 3: invoke the local admission Close before HTTP/HTTPS draining and door shutdown in both dev and normal listeners. Preserve merged main's startup behavior and its census basis; the same five read sites, no new reads.;rev3=census-ruling-stateless-replicas-3;basis=Task 1b: defer stopping and joining the edge's replica jobs at shutdown. Existing five direct read sites unchanged; no new reader or authority. data-literal@129,data-literal@148,data-literal@284,data-literal@417,file:Open@1013 141655c4967b15b262faaa0f21a9e3514e8844162ef6c62db699e78638456c10 |
| +@legacy eef846cad40472c4151369c696b1da1835b1e24c5b3d317d81667571039ffcc8 internal/activator/replicaprobe.go Service.ProbeCopy legacy accepted-legacy accepted-legacy;rev3=census-ruling-stateless-replicas-3;basis=Task 1a: read the local registry assignment and the already-awake entry's launch/worker evidence under the held-leg predicate; compare account, app, fleet, box membership and lifetime; no bucket call, wake, authority acquisition or activity update. Added registry field and whole Route reads are the existing local projection, not tenant-selected paths. registry:Account@1564,registry:App@1581,registry:FleetBoxes@306,registry:HA@402,registry:HA@891,registry:Hibernate@386,registry:Hibernate@874,registry:Incarnation@819,registry:Incarnation@838,registry:Kind@361,registry:Region@1135,registry:Region@792,registry:Region@806,registry:ReplicaIncarnation@1658,registry:ReplicaIncarnation@741,registry:ReplicaIncarnation@767,registry:ReplicaRevision@1703,registry:Stateless@857,whole:Route@1083,whole:Route@1089,whole:Route@296,whole:Route@683,whole:Route@714,whole:Route@719 efe551a9cdf45284360710a083d19813120343f843ae9db9d3b4636d5f96d57c |
| +@legacy 1852ab27b5e9593b9d9bc0f7c604e1f97d35a60368cdb6c7835a31307b90c13c internal/edge/replicaprobe.go Edge.replicaCopyMatches legacy accepted-legacy accepted-legacy;rev3=census-ruling-stateless-replicas-3;basis=Task 1a: compare Copy identity against the loaded Route's host, account, app, fleet, incarnation and assignment revision; local box must remain a member. Only in-memory registry field reads; no file or bucket reads. registry:Account@213,registry:App@251,registry:Host@170,registry:Region@115,registry:ReplicaIncarnation@325,registry:ReplicaRevision@374 503766598b5be534178a0c843ad160082961a96577c7c591416f9921712614ce |
| +@legacy 840c48158ddb0f0befdefe2ad0cf10e06b74719639a1a6e48b1f49318c142946 internal/edge/replicaprobe.go Edge.serveReplicaProbe legacy accepted-legacy accepted-legacy;rev3=census-ruling-stateless-replicas-3;basis=Task 1a: verify the loaded assigned route, admit a held leg without waking, and GET the platform-captured serving generation's Unix socket under a one-second deadline. Recheck evidence after the response, drain at most 4 KiB and close. Route uses are already-loaded data; no root execution, bucket read or caller-chosen dial path. registry:FleetBoxes@390,registry:HA@459,registry:Hibernate@443,registry:Host@346,registry:Kind@365,whole:Route@1025,whole:Route@1215,whole:Route@2194,whole:Route@706 71e7e09ba2eea40c306362f2a17ed8324491da4560cc7896a84b309bcb39669a |
| +@legacy 25360f01e12d3e11dc94e974d2a499b43446540fc95132bbb97e89ce6d8bc0a9 internal/edge/replicaprober.go Edge.syncReplicaProbes legacy accepted-legacy accepted-legacy;rev3=census-ruling-stateless-replicas-3;basis=Task 1b: explicit integration seam passes supplied routes to the hub prober only when a tunnel hub exists. Not called from Reload or live routing in this slice. Whole Route use is in-memory; no registry query or bucket read. whole:Route@266 067356c5f648c50deed9ff3216dc2f4e61377f2de5328c86bd88d4bea4ae7175 |
| +@legacy 9e62a31cf6e58105bcd5f2c17836a0cdcab581d29b9065c57beb3f5eb444ad81 internal/edge/replicaprober.go TunnelHub.probeReplica legacy accepted-legacy accepted-legacy;rev3=census-ruling-stateless-replicas-3;basis=Task 1b: file:ReadAll is io.ReadAll of an HTTP response body from the existing authenticated tunnel transport, limited to 64 KiB plus an overflow byte and closed. Sends a fresh private GET with no visitor credentials, rejects non-200/non-JSON responses, never follows redirects. No filesystem path is opened. file:ReadAll@618 7514dbfa020b4da77546960850b279972a00dd8ec4404af719651925b23297ca |
| +@legacy 53d7ac393dafdce750c86672f955dda2f3cdc7a1880b812edac521e83e96fc75 internal/edge/replicaprober.go newReplicaProber legacy accepted-legacy accepted-legacy;rev3=census-ruling-stateless-replicas-3;basis=Task 1b: allocate empty in-memory job and route maps; choose the existing tunnel transport adapter and clock. Whole Route is a map value type, not an external read. Construction starts no job. whole:Route@306 8090869d116edd4340609068c605baefe9e9ac7a71d9c882d65508ae01c79043 |
| +@legacy 0424c3cb96d5aa4b97ab58a07da1cda564730bc8eee3cb407d6f171bf736dba1 internal/edge/replicaprober.go replicaEvidenceMatches legacy accepted-legacy accepted-legacy;rev3=census-ruling-stateless-replicas-3;basis=Task 1b: compare authenticated platform Copy evidence to the assigned route and pinned connection/job evidence. GoodDigest is the serving platform executable digest, never the canonical manifest hash. Reads only supplied Route fields; no file, bucket or manifest fetch. registry:Account@225,registry:App@247,registry:GoodDigest@823,registry:GoodDigest@857,registry:GoodVersion@793,registry:Host@202,registry:Region@135,registry:ServingVersion@713,registry:ServingVersion@752,whole:Route@80 9cd81c96fe9ae311ebfe451e8cfaf22e7183735d15e028b2f872557d7eac3e89 |
| +@legacy 0efc29f0410bb2f503b25f1fad71f8cfa6867ab7c3d3a3256ccd53ecaaedc0cd internal/edge/replicaprober.go replicaProber.Snapshot legacy accepted-legacy accepted-legacy;rev3=census-ruling-stateless-replicas-3;basis=Task 1b: return a detached snapshot for the requested host from the already-held route/job maps. Whole Route copies remain in memory; no new external reader. whole:Route@113,whole:Route@193 171de8351bf2af47663c62e149b96907c1ff3366f3a9441d36f1eda3375cf5ca |
| +@legacy 490f7edbfba9ddab00090b74647128ab08aa82e5d12b013b8fe215ea56e8e23a internal/edge/replicaprober.go replicaProber.Stop legacy accepted-legacy accepted-legacy;rev3=census-ruling-stateless-replicas-3;basis=Task 1b: permanently stop, cancel and join owned jobs and clear their in-memory route map. Whole Route use is the map value type; no external read or lifecycle action on applications. whole:Route@155 ca2248300f84a7bbd7400c6f60b44c682adbf4387251979e241445e06fad8877 |
| +@legacy feec5daa9a82886213d1527cf5b0da3a1126750be674cf6c58226fae839bb41d internal/edge/replicaprober.go replicaProber.Sync legacy accepted-legacy accepted-legacy;rev3=census-ruling-stateless-replicas-3;basis=Task 1b: validate supplied stateless set rows, reject duplicates and invalid/legacy/HA/hibernating rows, preserve unchanged job keys, and cancel/replace changed host-lifetime-revision-box jobs. Registry fields and whole Route values come from the caller's snapshot only; no query, bucket polling, app wake or routing integration. registry:Account@331,registry:App@351,registry:FleetBoxes@308,registry:FleetBoxes@688,registry:HA@367,registry:Hibernate@376,registry:Host@1158,registry:Host@473,registry:Host@501,registry:Host@529,registry:Kind@393,registry:Region@1051,registry:ReplicaIncarnation@1167,registry:ReplicaRevision@1200,whole:Route@1221,whole:Route@1228,whole:Route@262,whole:Route@467,whole:Route@523,whole:Route@540,whole:Route@569,whole:Route@610,whole:Route@745,whole:Route@776,whole:Route@829,whole:Route@871,whole:Route@925,whole:Route@934,whole:Route@963 9ed9fcc15f6f5ad1c2bd7d64fcc56410923004bbc77c932a9d5180fbb649683d |
| +@legacy 3f60aa60f8627deaa1d5666be72f5204282f038024dd4c1c8270b00e139a5019 internal/edge/replicaprober.go replicaProber.reset legacy accepted-legacy accepted-legacy;rev3=census-ruling-stateless-replicas-3;basis=Task 1b: reset a copy to unknown on connection change and build its identity from the job's captured route; disconnected copies are down. Reads only in-memory Route fields; no external input or file read. registry:Account@258,registry:App@280,registry:Region@189,whole:Route@191,whole:Route@260,whole:Route@282 a3fe9112c25e9f9b968ee8eff4ba7c1746db259142636f986c6a5b8798da4ff7 |
| +@legacy b03cc484ccdcb390d96f60909b23e3889e913095f8db9694f35a841e77f8c9b8 internal/edge/replicaprober.go replicaProber.snapshotLocked legacy accepted-legacy accepted-legacy;rev3=census-ruling-stateless-replicas-3;basis=Task 1b: build one host's detached snapshot from its canonical assignment boxes and job samples, excluding closed/replaced tunnel generations immediately. Registry field reads are the stored in-memory route; no filesystem or bucket access. registry:Account@126,registry:App@143,registry:Copies@226,registry:FleetBoxes@284,registry:Host@108,registry:Host@513,registry:ReplicaIncarnation@164,registry:ReplicaRevision@197 6e61edffbcab8ad36f1dd0909badddde6b9b24a9b070ebe10c877b453b228f04 |
| +@legacy f5ad3e69bbbe118330cabbead7698b7bf2cbe3e6d54e8628217c642b27a5126b internal/edge/replicaprober.go replicaProber.snapshots legacy accepted-legacy accepted-legacy;rev3=census-ruling-stateless-replicas-3;basis=Task 1b: copy all current host snapshots under the prober lock for the private health socket. Whole Route values are the owned map; returned slices/maps cannot mutate health state. No new external reads. whole:Route@150,whole:Route@184,whole:Route@224 be3aafcac789af7434db8ec1cf0b884b242d82eb1c24c7aca2795ec578741e23 |
| +@legacy 04f425d87c4d9194d8d8c6f644c1be6b55386df5b3c528fd5c5a71086c06afb6 internal/edge/replicaprober.go sameReplicaJob legacy accepted-legacy accepted-legacy;rev3=census-ruling-stateless-replicas-3;basis=Task 1b: compare captured and supplied route identity, assignment and optional platform serving-build evidence to decide job preservation. Pure in-memory comparisons; no authority or external reads. registry:Account@194,registry:Account@207,registry:App@221,registry:App@230,registry:Copies@298,registry:Copies@310,registry:FleetBoxes@265,registry:FleetBoxes@281,registry:GoodDigest@399,registry:GoodDigest@415,registry:GoodVersion@364,registry:GoodVersion@381,registry:Host@97,registry:Region@240,registry:Region@252,registry:ReplicaIncarnation@129,registry:ReplicaRevision@172,registry:ServingVersion@323,registry:ServingVersion@343,whole:Route@69 a12dc37f2e9a77e1e965c9a99103decedae5e5bd3c615c972d81a3f539465ba0 |
| +@legacy 5af61b9be2ebcc76b4871899e03d72ff5f5c5e8a86da58e9ccb435025f024165 internal/edge/tunnel.go tunnelWire.Read legacy accepted-legacy accepted-legacy;rev3=census-ruling-stateless-replicas-3;basis=Task 1b: the scanner's file:Read sites are net.Conn.Read on the existing authenticated reverse-channel connection, not filesystem reads. Notify closure on reader failure so copy health excludes closed connections immediately. No pathname, root-owned file or new network destination is introduced. file:Read@21,file:Read@62 eff57b35dc5f4f7e2f54e08b07e07b0a21d571c41704be0a3d1997db362b8234 |
| +@legacy 84e1fa64113c54c580f5f77b91da2456f49432aeae923f0ebf3b4d92e7e60c1b internal/host/replicahealth_linux.go serveReplicaHealth legacy accepted-legacy accepted-legacy;rev3=census-ruling-stateless-replicas-3;basis=Task 1a: Lstat checks the fixed agent-owned /run/carlos/.replicas directory and health.sock; Open opens that directory read-only for flock. Require directory ownership and mode 0700, socket 0600, preserve live/non-socket/ambiguous existing paths, and only remove proven stale sockets under the lock. Read-only snapshot handler, bounded shutdown and listener-owned unlink; not mounted into tenant namespaces. No root read of tenant-controlled input. file:Lstat@252,file:Lstat@906,file:Open@650 1ff1e05ec8222c2adf684421e40eb55c7590beba28a725e5035b08da04042cb2 |
| +@legacy 7543220573485e822d13d2cf145e49bf557d9c0b4937327f0bfcba23e52a59a9 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.;rev3=census-ruling-stateless-replicas-3;basis=Task 1a: pass the already-resolved Route to the reserved replica-probe handler after acceptHop and existing admissionRefuses, requiring tunnel context plus private marker and refusing door/backhaul ingress. Added whole Route use only; scrub marker before forwarding; HA calls remain unchanged. file:ReadAll@15522,registry:App@21679,registry:Gate@14496,registry:Gate@26070,registry:Gate@26130,registry:Gate@26188,registry:Host@26173,registry:ImportGate@33573,registry:Kind@20541,registry:Kind@23979,registry:Kind@33515,registry:Kind@33544,whole:Route@14391,whole:Route@14502,whole:Route@17319,whole:Route@18103,whole:Route@18561,whole:Route@18753,whole:Route@20544,whole:Route@21605,whole:Route@21671,whole:Route@21682,whole:Route@21935,whole:Route@22030,whole:Route@22106,whole:Route@22150,whole:Route@22452,whole:Route@22482,whole:Route@23982,whole:Route@24267,whole:Route@26073,whole:Route@26133,whole:Route@26176,whole:Route@26191,whole:Route@27109,whole:Route@29172,whole:Route@33518,whole:Route@33547,whole:Route@33576,whole:Route@33608,whole:Route@35456,whole:Route@5576,whole:Route@5671 d86bb163dfe6c165cad91eb2a4713f3f862d6128a8ec59808e6dc638c3d44a49 |
| +internal/edge/edge.go RunWithActivatorReady legacy accepted-legacy accepted-legacy;rev3=J4;basis=root-input;rev3=census-ruling-certwarm-wake;basis=registers the cert warm's nudge on OnReload and on the home map's new served-hosts wake (#386); nudge only sends on a buffered channel; no read added, same 5 sites;rev3=census-ruling-edge-roll-blip;basis=the :80/:443 (and dev) listeners are bound on the calling goroutine with net.Listen via listen()/listenAddr (same empty-address defaults as ListenAndServe) before the serve goroutines, which now call Serve/ServeTLS on them, and one log line names the bound addresses; no read added, same 5 sites;rev3=census-ruling-edge-held-streams;basis=the edge in the agent (carlos-edge.service, user carlos): the inline home-map arming (newHomeMap, one boot Refresh, Store, run) moves unchanged into the new Edge.ArmHomeMap and is called here as e.ArmHomeMap(); same refresh, same timeout, same order. The reads are moved, none added.;rev3=census-ruling-agent-start-demo-1;basis=Logs the combined explicit wildcard parents through demoWildcardDomains; no new watcher or read loop.;rev3=census-ruling-region-ha-p3a;basis=P3a Task 3: invoke the local admission Close before HTTP/HTTPS draining and door shutdown in both dev and normal listeners. Preserve merged main's startup behavior and its census basis; the same five read sites, no new reads.;rev3=census-ruling-stateless-replicas-3;basis=Task 1b: defer stopping and joining the edge's replica jobs at shutdown. Existing five direct read sites unchanged; no new reader or authority. data-literal@129,data-literal@148,data-literal@284,data-literal@417,file:Open@1013 141655c4967b15b262faaa0f21a9e3514e8844162ef6c62db699e78638456c10 |
| +internal/host/agent.go runAgent authority B,C,D,F rev3=census-ruling-self-serve-moves-1;basis=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): builds the box's lifetime judge once (newBoxJudge, nil with host claims on) and hands it to the seed placement, the moves and runs workers and every loop it starts; read sites unchanged, offsets moved; B,C,D,F authority retained; self-serve moves 1 Task 8: derives the box's lifetimes switch from the judge once (lifetimes := boxJudge != nil) and hands it to the edges file loop; read sites unchanged, offsets moved;rev3=census-ruling-plans-4d-lapse;basis=arms two more plans hooks from the same snapshot: e.SetPlanDisabledFor(planDisabledFor) beside SetPlanGovernedFor, and svc.SetDisabledFor(planDisabledRoute) beside SetMaxRunFor (plans 4d); the reads live in those units (plans-4d-units decision); read sites unchanged, offsets moved;rev3=census-ruling-rootfs-apps-2;basis=main's body as of the merge of origin/main 9b81d97b (with main's plan rate ceiling, edge request records, regional box names, self-serve moves plan 1, plans 4d-1 lapse and its other later changes under main's own census rulings) plus the rootfs placement wiring in the activator start: an agentRootfs built from eb.NestedOK, CARLOS_DEPLOYMENT_SINGLE_TENANT, CARLOS_POOLS, the claim flag, swapArming's answer, the control client's /ready/rootfs and, on a fleet box whose identity resolved, fleetOwnerCheck over the deploy store main already opens for the fleet label (fleetStore), then arm and armedRootfs.Store; this body reads nothing new itself; the closures it wires read later, at a rootfs wake and each status tick: GET /ready/rootfs over the control socket, NestedOK's checks, and release.FleetOwnerKey for the judged row's own account and this box's fleet from the deploy store;rev3=census-ruling-instance-egress-sizes-328-329;basis=#328 plan 2 Tasks 7 and 11, #329 plan 3 Task 7 and plan 1 Task 7's policy cache: the control client is built once and handed to eb.Control, to the status tick (egressStatus) and to a new egressNudgeLoop goroutine; armSizeSource(svc, "/sys/fs/cgroup") after the activator Service; armPolicyCache() after armChangeIndex; statusLoop takes egressStatus. The reads are those units' own (decision rows); this body reads nothing new: the same five sites, offsets moved, in the agent; B,C,D,F authority retained.;rev3=census-ruling-remote-instance-metrics;basis=builds the metrics loop's owners closure (metricsOwners over the agent's registry, the activator and cgm.Leftover) when an activator exists and hands it to metricsLoop; reads nothing new itself;rev3=census-ruling-edge-asset-cache-3;basis=adds file:Statfs. runAgent keeps its authority (B,C,D,F). The new site is assetcache.Statfs, an exported assetcache.FS interface value (var Statfs FS = statfsFS{}), not a function value and not a call in runAgent: the ready hook passes it to armEdgeAssetCache as the store's filesystem, and armEdgeAssetCache calls its Space method on the configured data directory (dataDir(): $CARLOS_DATA_DIR, else /data), which calls unix.Statfs there (statfsFS.Space, accepted legacy at census-ruling-edge-asset-cache-2). No request-supplied pathname reaches it.;rev3=census-ruling-remote-metrics-nested;basis=main's body (merged origin/main acfa4f80, under main's own census rulings) plus: snapshots the nested layout (snapshotNestedUnits over /sys/fs/cgroup/carlos.slice/carlos-instances.slice) once at start, before the activator, and hands the metrics loop a unitSources struct (stamped units, routeHostNames, that root and the snapshot); reads nothing new itself;rev3=census-ruling-region-ha-p1a;basis=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): wires region HA P1a into the activator: cfg.Record = haRecordFacts(openDeployStore, boxJudge) (the box's lifetime judge this body already builds with newBoxJudge, nil with host claims on; CI fix) and cfg.Self = lease.CurrentSelf; eb.Lifetimes (the process's lifetime index), eb.Registry, eb.StartupSwept (seedSweptAtStart.Load), eb.FilesStore from newProductionFilesStore (now lease.NewFilesStore, rootaws-loaded, a log line on failure) and lease.SetObligationDir(<data>/.ha-owed) (logged on failure; HA acquires then refuse); this body reads nothing new itself, the same five sites; the reads are those units' own (haRecordFacts and lease's SetObligationDir are new rows on this card); merge of origin/main d7ae1d76: main's own later changes to this body are kept as main has them, under main's rulings (census-ruling-remote-instance-metrics: the metricsOwners closure for metricsLoop; census-ruling-edge-asset-cache-3: the +file:Statfs site, assetcache.Statfs handed to the asset ready hook); this branch's change is the same as above;rev3=census-ruling-region-ha-p1b1;basis=region HA P1b-1: builds one termfence.Confirmer (Self from lease.CurrentSelf at each call, EC2 DescribeInstances method only, client from rootaws.LoadDefaultConfig with retries off, built lazily on first use) and sets eb.OwnerTerminated; this body reads nothing new itself, the same six sites;rev3=census-ruling-rootfs-apps-3;basis=rootfs Plan 3 Task 7: the startup Sweep literal hands its answer to startupSwept, which logs as before and, only on a clean sweep, marks rootfs admission swept (MarkRootfsSwept); same Sweep call, no read added;rev3=census-ruling-managed-fleets-1b;basis=managed fleets 1b (controller ruling after branch review R1, and Paul's R2 ruling): sets svc.Fleet = fleetWakeFor(os.Getenv, identity, identErr, fleetStore) from the identity it already resolves once and the deployment store the fleet loops already opened, and logs an ERROR naming the identity error when the box is on a fleet with an invalid identity. fleetWakeFor reads CARLOS_REGION and CARLOS_FLEET from the same environment. Read sites unchanged (6). Agent, not root; a platform box is unchanged.;rev3=census-ruling-rootfs-apps-6;basis=rootfs Plan 6 Task 12: one call more beside armRunsPass, armInteractivePass(svc, reg, rolloutSink, boxJudge), in the same activator Configure hook, handing it the same box judge; fix round 1 (Astra P2, shutdown): after svc.Shutdown(ctx), shutdownInteractive(ctx) ends and joins every interactive session under the same shutdown budget; the worker's own reads are its units' (interactive.go); this body reads nothing new, the same six sites; merge of origin/main 6f1f6ca6: main's svc.Fleet = fleetWakeFor(...) and its invalid-identity ERROR line are kept as main has them (census-ruling-managed-fleets-1b); this branch's change is the same as above; read sites unchanged (6);rev3=census-ruling-fix-set-aside-exdev;basis=set-aside EXDEV fix: one field more on the agent ExecBackend literal, RawInstanceDir: layout.RawInstanceDir (a pure path join: <dataDir>/.instances/<InstanceID(host)>), so the start rule set-aside moves a copy out through the raw directory instead of through the nosymfollow bind; this body reads nothing new, the same six sites;rev3=census-ruling-durability-3a-escrow;basis=durability 3a Task 3: one more assignment beside eb.FilesStore: eb.EscrowKey = haEscrowKey(os.Getenv("CARLOS_SECRETS_KEY")), the agent's own environment parsed by appconfig.ParsePrivateKey as the moves pass parses it (unset or unparseable: a log line and nil, and HA publication refuses on the box). No path is opened or read, no read site added; the same six sites, offsets moved; B,C,D,F authority retained. Durability 3a Task 4: one more goroutine beside configSyncLoop: go escrowLoop(agentCtx, reg, svc), the escrow sweep every 30 s over the same registry and Service. This body reads nothing new itself; the same six sites, offsets moved; B,C,D,F authority retained. Durability 3a Task 5: one more call beside eb.EscrowKey: wireRawSecretPages(eb, PageOperator, metricsBoxLabel(os.Getenv, readMachineID())), which sets eb.OnRawSecret to page an operator (alerting.Page through PageOperator, LevelIncident) on its own goroutine with a 20 s timeout; metricsBoxLabel and readMachineID are the reads this body already makes for the moves refusal log; no new read site; the same six sites, offsets moved; B,C,D,F authority retained. Merge of origin/main 90c4d3aa: main's own later changes to this body are kept as main has them, under main's rulings; this branch's change is the same as above. Merge of origin/main 00bf5b8c (fleet set-aside EXDEV fix): main's change to this body is kept as main has it, under its own census ruling; this branch's change is unchanged.;rev3=census-ruling-probe-burst-limit;basis=two more sink wirings beside setAnalyticsSink: setProtectionSink(e.SetProtectionRecordOnly) and setAssetOwnersSource(e.AssetOwners), function values the telemetry pass calls; this body reads nothing new, the same six sites; authority B,C,D,F retained; no new root read or write kind;rev3=census-ruling-region-ha-p1b3a;basis=Arm HA placement exactly once on the existing Service before activatorStart and edges publication, wiring AwakeApps and the PageOperator callback; existing six read sites unchanged, no new root authority.;rev3=census-ruling-stateless-replicas-1;basis=Final review I3: start the concrete coordinator's renewal worker with agent setup; existing closeReplicaCoordinator shutdown cancels and joins it before release. No new read sites or credentials. Merge origin/main c59715e7: retain main's armHAPlacement(svc, PageOperator) wiring beside the existing activator setup; stateless coordinator and shutdown wiring remain. Same read sites; no new root read or credential.;rev3=census-ruling-edge-held-streams;basis=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): in the edge-ready callback, calls act.SetHeldWakeHook(e.HeldWake) when act is non-nil (installing the non-blocking wake callback) and stores e.HeldStreamsForStatus in heldStreamsSource. Wiring of in-memory callbacks only; no read added.;rev3=census-ruling-region-ha-p1b3b-t;basis=Wire Service.SetDutyView to the live edge DutySnapshot in the ready callback. No new read; no new loop or cloud operation. B2 wires the registry as the persistent DutyStore before service startup; no new cloud or filesystem path. B3b: arm one journal-backed termination consumer before service startup using agentCtx and the shared confirmer; expose edge tick and join at edge shutdown. No new direct read sites.;rev3=census-ruling-agent-start-demo-1;basis=Passes the existing registry, data store and hibernation prefix into the demo worker, and the existing instance-control client into the demo before-exec hook. No alternate data store or polling loop. Merge resolution against origin/main 9bd45488 retains main's HA departure controller, lifecycle and duty wiring alongside the demo data store and worker; no read site added by the resolution.;rev3=census-ruling-region-ha-p3a;basis=P3a Task 3: install closed fixed admission before every launch source, bind activator/backend and edge, wire the real termination Started lifecycle and role reader after the change index; close before cancellation/child shutdown. No new external reads or cloud authority. Fix R1: move bind/lifecycle/edge-option wiring into wireAgentAdmission and worker listing into runWorkerBootPassAfterAdmission. Worker boot waits for admission before listing then uses unchanged bounded wakes and per-host serialization; whole Route read moves to the helper. No new storage, cloud, or root execution authority. Preserve merged main's agent wiring and census basis; the branch removes one whole Route use by moving worker iteration to the helper, with no added read kind.;rev3=census-ruling-stateless-replicas-2;basis=Slice 3b: arms a fleet-only worker using the existing registry, activator, backend and authenticated console transport. Owned worker stops and joins at shutdown. No new bucket reader. merge of origin/main 9b8b2c50: retain HA duty/departure lifecycle, wake-slot and existing agent wiring alongside the replica placement worker; no new read introduced by resolution. merge of origin/main 6be08467: Retain main demo configuration, admission, build and expiry wiring alongside the replica worker; merge-only body change, no additional read. merge of origin/main 7920cccf: Retain main box-role/group admission wiring and boot publication beside the owned replica worker and shutdown; main moves the boot registry List into runWorkerBootPassAfterAdmission, removing its inline whole Route site. No new read introduced by conflict resolution.;rev3=census-ruling-stateless-replicas-3;basis=Task 1a+1b: run the private replica-health Unix server with existing retry shape, cancel/join it at shutdown and supply Edge.ReplicaSnapshots in the ready hook. Existing five direct read sites unchanged; no console reader, polling loop or new credentials. file:Exec@18226,file:Open@1517,file:Statfs@47936,registry:App@11938,whole:Route@11930 adf756ed67a87596d02e2e15109658d5dfd33fcdf695f2512acfb416fe44bdf1 |
| +internal/activator/replicaprobe.go Service.ProbeCopy legacy accepted-legacy accepted-legacy;rev3=census-ruling-stateless-replicas-3;basis=Task 1a: read the local registry assignment and the already-awake entry's launch/worker evidence under the held-leg predicate; compare account, app, fleet, box membership and lifetime; no bucket call, wake, authority acquisition or activity update. Added registry field and whole Route reads are the existing local projection, not tenant-selected paths. registry:Account@1564,registry:App@1581,registry:FleetBoxes@306,registry:HA@402,registry:HA@891,registry:Hibernate@386,registry:Hibernate@874,registry:Incarnation@819,registry:Incarnation@838,registry:Kind@361,registry:Region@1135,registry:Region@792,registry:Region@806,registry:ReplicaIncarnation@1658,registry:ReplicaIncarnation@741,registry:ReplicaIncarnation@767,registry:ReplicaRevision@1703,registry:Stateless@857,whole:Route@1083,whole:Route@1089,whole:Route@296,whole:Route@683,whole:Route@714,whole:Route@719 efe551a9cdf45284360710a083d19813120343f843ae9db9d3b4636d5f96d57c |
| +internal/edge/replicaprobe.go Edge.replicaCopyMatches legacy accepted-legacy accepted-legacy;rev3=census-ruling-stateless-replicas-3;basis=Task 1a: compare Copy identity against the loaded Route's host, account, app, fleet, incarnation and assignment revision; local box must remain a member. Only in-memory registry field reads; no file or bucket reads. registry:Account@213,registry:App@251,registry:Host@170,registry:Region@115,registry:ReplicaIncarnation@325,registry:ReplicaRevision@374 503766598b5be534178a0c843ad160082961a96577c7c591416f9921712614ce |
| +internal/edge/replicaprobe.go Edge.serveReplicaProbe legacy accepted-legacy accepted-legacy;rev3=census-ruling-stateless-replicas-3;basis=Task 1a: verify the loaded assigned route, admit a held leg without waking, and GET the platform-captured serving generation's Unix socket under a one-second deadline. Recheck evidence after the response, drain at most 4 KiB and close. Route uses are already-loaded data; no root execution, bucket read or caller-chosen dial path. registry:FleetBoxes@390,registry:HA@459,registry:Hibernate@443,registry:Host@346,registry:Kind@365,whole:Route@1025,whole:Route@1215,whole:Route@2194,whole:Route@706 71e7e09ba2eea40c306362f2a17ed8324491da4560cc7896a84b309bcb39669a |
| +internal/edge/replicaprober.go Edge.syncReplicaProbes legacy accepted-legacy accepted-legacy;rev3=census-ruling-stateless-replicas-3;basis=Task 1b: explicit integration seam passes supplied routes to the hub prober only when a tunnel hub exists. Not called from Reload or live routing in this slice. Whole Route use is in-memory; no registry query or bucket read. whole:Route@266 067356c5f648c50deed9ff3216dc2f4e61377f2de5328c86bd88d4bea4ae7175 |
| +internal/edge/replicaprober.go TunnelHub.probeReplica legacy accepted-legacy accepted-legacy;rev3=census-ruling-stateless-replicas-3;basis=Task 1b: file:ReadAll is io.ReadAll of an HTTP response body from the existing authenticated tunnel transport, limited to 64 KiB plus an overflow byte and closed. Sends a fresh private GET with no visitor credentials, rejects non-200/non-JSON responses, never follows redirects. No filesystem path is opened. file:ReadAll@618 7514dbfa020b4da77546960850b279972a00dd8ec4404af719651925b23297ca |
| +internal/edge/replicaprober.go newReplicaProber legacy accepted-legacy accepted-legacy;rev3=census-ruling-stateless-replicas-3;basis=Task 1b: allocate empty in-memory job and route maps; choose the existing tunnel transport adapter and clock. Whole Route is a map value type, not an external read. Construction starts no job. whole:Route@306 8090869d116edd4340609068c605baefe9e9ac7a71d9c882d65508ae01c79043 |
| +internal/edge/replicaprober.go replicaEvidenceMatches legacy accepted-legacy accepted-legacy;rev3=census-ruling-stateless-replicas-3;basis=Task 1b: compare authenticated platform Copy evidence to the assigned route and pinned connection/job evidence. GoodDigest is the serving platform executable digest, never the canonical manifest hash. Reads only supplied Route fields; no file, bucket or manifest fetch. registry:Account@225,registry:App@247,registry:GoodDigest@823,registry:GoodDigest@857,registry:GoodVersion@793,registry:Host@202,registry:Region@135,registry:ServingVersion@713,registry:ServingVersion@752,whole:Route@80 9cd81c96fe9ae311ebfe451e8cfaf22e7183735d15e028b2f872557d7eac3e89 |
| +internal/edge/replicaprober.go replicaProber.Snapshot legacy accepted-legacy accepted-legacy;rev3=census-ruling-stateless-replicas-3;basis=Task 1b: return a detached snapshot for the requested host from the already-held route/job maps. Whole Route copies remain in memory; no new external reader. whole:Route@113,whole:Route@193 171de8351bf2af47663c62e149b96907c1ff3366f3a9441d36f1eda3375cf5ca |
| +internal/edge/replicaprober.go replicaProber.Stop legacy accepted-legacy accepted-legacy;rev3=census-ruling-stateless-replicas-3;basis=Task 1b: permanently stop, cancel and join owned jobs and clear their in-memory route map. Whole Route use is the map value type; no external read or lifecycle action on applications. whole:Route@155 ca2248300f84a7bbd7400c6f60b44c682adbf4387251979e241445e06fad8877 |
| +internal/edge/replicaprober.go replicaProber.Sync legacy accepted-legacy accepted-legacy;rev3=census-ruling-stateless-replicas-3;basis=Task 1b: validate supplied stateless set rows, reject duplicates and invalid/legacy/HA/hibernating rows, preserve unchanged job keys, and cancel/replace changed host-lifetime-revision-box jobs. Registry fields and whole Route values come from the caller's snapshot only; no query, bucket polling, app wake or routing integration. registry:Account@331,registry:App@351,registry:FleetBoxes@308,registry:FleetBoxes@688,registry:HA@367,registry:Hibernate@376,registry:Host@1158,registry:Host@473,registry:Host@501,registry:Host@529,registry:Kind@393,registry:Region@1051,registry:ReplicaIncarnation@1167,registry:ReplicaRevision@1200,whole:Route@1221,whole:Route@1228,whole:Route@262,whole:Route@467,whole:Route@523,whole:Route@540,whole:Route@569,whole:Route@610,whole:Route@745,whole:Route@776,whole:Route@829,whole:Route@871,whole:Route@925,whole:Route@934,whole:Route@963 9ed9fcc15f6f5ad1c2bd7d64fcc56410923004bbc77c932a9d5180fbb649683d |
| +internal/edge/replicaprober.go replicaProber.reset legacy accepted-legacy accepted-legacy;rev3=census-ruling-stateless-replicas-3;basis=Task 1b: reset a copy to unknown on connection change and build its identity from the job's captured route; disconnected copies are down. Reads only in-memory Route fields; no external input or file read. registry:Account@258,registry:App@280,registry:Region@189,whole:Route@191,whole:Route@260,whole:Route@282 a3fe9112c25e9f9b968ee8eff4ba7c1746db259142636f986c6a5b8798da4ff7 |
| +internal/edge/replicaprober.go replicaProber.snapshotLocked legacy accepted-legacy accepted-legacy;rev3=census-ruling-stateless-replicas-3;basis=Task 1b: build one host's detached snapshot from its canonical assignment boxes and job samples, excluding closed/replaced tunnel generations immediately. Registry field reads are the stored in-memory route; no filesystem or bucket access. registry:Account@126,registry:App@143,registry:Copies@226,registry:FleetBoxes@284,registry:Host@108,registry:Host@513,registry:ReplicaIncarnation@164,registry:ReplicaRevision@197 6e61edffbcab8ad36f1dd0909badddde6b9b24a9b070ebe10c877b453b228f04 |
| +internal/edge/replicaprober.go replicaProber.snapshots legacy accepted-legacy accepted-legacy;rev3=census-ruling-stateless-replicas-3;basis=Task 1b: copy all current host snapshots under the prober lock for the private health socket. Whole Route values are the owned map; returned slices/maps cannot mutate health state. No new external reads. whole:Route@150,whole:Route@184,whole:Route@224 be3aafcac789af7434db8ec1cf0b884b242d82eb1c24c7aca2795ec578741e23 |
| +internal/edge/replicaprober.go sameReplicaJob legacy accepted-legacy accepted-legacy;rev3=census-ruling-stateless-replicas-3;basis=Task 1b: compare captured and supplied route identity, assignment and optional platform serving-build evidence to decide job preservation. Pure in-memory comparisons; no authority or external reads. registry:Account@194,registry:Account@207,registry:App@221,registry:App@230,registry:Copies@298,registry:Copies@310,registry:FleetBoxes@265,registry:FleetBoxes@281,registry:GoodDigest@399,registry:GoodDigest@415,registry:GoodVersion@364,registry:GoodVersion@381,registry:Host@97,registry:Region@240,registry:Region@252,registry:ReplicaIncarnation@129,registry:ReplicaRevision@172,registry:ServingVersion@323,registry:ServingVersion@343,whole:Route@69 a12dc37f2e9a77e1e965c9a99103decedae5e5bd3c615c972d81a3f539465ba0 |
| +internal/edge/tunnel.go tunnelWire.Read legacy accepted-legacy accepted-legacy;rev3=census-ruling-stateless-replicas-3;basis=Task 1b: the scanner's file:Read sites are net.Conn.Read on the existing authenticated reverse-channel connection, not filesystem reads. Notify closure on reader failure so copy health excludes closed connections immediately. No pathname, root-owned file or new network destination is introduced. file:Read@21,file:Read@62 eff57b35dc5f4f7e2f54e08b07e07b0a21d571c41704be0a3d1997db362b8234 |
| +internal/host/replicahealth_linux.go serveReplicaHealth legacy accepted-legacy accepted-legacy;rev3=census-ruling-stateless-replicas-3;basis=Task 1a: Lstat checks the fixed agent-owned /run/carlos/.replicas directory and health.sock; Open opens that directory read-only for flock. Require directory ownership and mode 0700, socket 0600, preserve live/non-socket/ambiguous existing paths, and only remove proven stale sockets under the lock. Read-only snapshot handler, bounded shutdown and listener-owned unlink; not mounted into tenant namespaces. No root read of tenant-controlled input. file:Lstat@252,file:Lstat@906,file:Open@650 1ff1e05ec8222c2adf684421e40eb55c7590beba28a725e5035b08da04042cb2 |
| +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.;rev3=census-ruling-stateless-replicas-3;basis=Task 1a: pass the already-resolved Route to the reserved replica-probe handler after acceptHop and existing admissionRefuses, requiring tunnel context plus private marker and refusing door/backhaul ingress. Added whole Route use only; scrub marker before forwarding; HA calls remain unchanged. file:ReadAll@15522,registry:App@21679,registry:Gate@14496,registry:Gate@26070,registry:Gate@26130,registry:Gate@26188,registry:Host@26173,registry:ImportGate@33573,registry:Kind@20541,registry:Kind@23979,registry:Kind@33515,registry:Kind@33544,whole:Route@14391,whole:Route@14502,whole:Route@17319,whole:Route@18103,whole:Route@18561,whole:Route@18753,whole:Route@20544,whole:Route@21605,whole:Route@21671,whole:Route@21682,whole:Route@21935,whole:Route@22030,whole:Route@22106,whole:Route@22150,whole:Route@22452,whole:Route@22482,whole:Route@23982,whole:Route@24267,whole:Route@26073,whole:Route@26133,whole:Route@26176,whole:Route@26191,whole:Route@27109,whole:Route@29172,whole:Route@33518,whole:Route@33547,whole:Route@33576,whole:Route@33608,whole:Route@35456,whole:Route@5576,whole:Route@5671 d86bb163dfe6c165cad91eb2a4713f3f862d6128a8ec59808e6dc638c3d44a49 |
| +@coverage internal/activator c5b02ec2a8b43a6ec7472b2f70d2d2a7d81a6e9fea126d398aca21ae46b5ca6f |
| +@coverage internal/edge ea8a3dfd94d2808459293ac0778aa57456f8d82f15ec8e1b20f4e5607b605aa4 |
| +@coverage internal/host ccb007a6a9705c2fbce61d04e59998a61d18696412e2926a748b7aa315647f53 |
| +@coverage internal/replicas 2c780322923afa8a3c3ec017f57d2b165858f21d38225fd16ef52d1402e5316a |
| +@coverage internal/tunnelclient a5bd418d97ee5e5d2bb9550dd35e2456b1c06fc541b82fe1e40a5594ed6fba30 |