feat: balance replica requests with safe failover
Add per-request selection from probed healthy copies, with one pass of safe failover and a three-second header bound per attempt. Preserve the existing tunnel upgrade admission and expire stale health samples. Record the selected box and attempt count without changing legacy record fields. Leave Reload and FleetArmVerdict integration for Task 3.
Co-Authored-By: Codex (gpt-6-astra) <noreply@openai.com>
docs/superpowers/notes/census-proposal-stateless-replicas-3.md+4 −2internal/edge/answered.go+5 −3internal/edge/edge.go+14 −18internal/edge/replica_retry_test.go+204 −0internal/edge/replicaprober.go+1 −1internal/edge/replicaprober_test.go+9 −2internal/edge/replicaproxy.go+205 −0internal/edge/replicaproxy_test.go+330 −0internal/edge/reqrecords.go+5 −1internal/edge/reqrecords_test.go+19 −0internal/edge/tunnel.go+17 −0internal/provision/testdata/plan14-root-reads-chain.tsv+1 −1internal/provision/testdata/plan14-root-reads-stateless-replicas-3.tsv+6 −3internal/replicas/retry.go+7 −0internal/replicas/retry_test.go+16 −0internal/reqrec/recorder.go+9 −0internal/reqrec/replica_test.go+48 −0
Intent
<task-notification> <task-id>b5md8g1w9</task-id> <tool-use-id>toolu_01WMfvT3JfV8QN9Ha1RPrfA1</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/195ef15b-aac6-42d6-b49b-41ffb7a4abbc/tasks/b5md8g1w9.output</output-file> <status>completed</status> <summary>Background command "Wait for Task 1 fix round 1" completed (exit code 0)</summary> </task-notification>
<task-notification> <task-id>afab174efc8489de3</task-id> <tool-use-id>toolu_01Mb6FHRRVr9jpP2omt8zQbm</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/195ef15b-aac6-42d6-b49b-41ffb7a4abbc/tasks/afab174efc8489de3.output</output-file> <status>completed</status> <summary>Agent "Task 1 census re-review" finished</summary> <note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note> <result>**Verdict: APPROVE** **Seal:** `59c08916…a5eb7a708e82` → `04715476748eb88cc85ac2ab86e859343fa2657ae77027de1837773ae37f5ed0`. It matches the chain line, and `make census-card` says the census is clean. The core census tests pass: `TestPlan14RootReadCensus`, `TestCensusScopeIsTheRootBinary`, `TestCensusRebaseCarriesDispositions`, `TestPlan14J4DeclaredMatchesTheCensus` and `TestPlan14RootReadCensusRejectsDrift`. 13 fixture tests fail, the same ones as last round. Each fails only on "read-only file system" for `~/.cache/go-build`, which is the sandbox's cache, not the branch. **Findings:** - **F1 fixed:** `internal/edge/replicaprobe.go:63` now dials through `unixdial.Checked`. The test at `internal/edge/replicaprobe_test.go:250-283` refuses both the control socket and a symlinked socket: each returns unhealthy with zero app hits. The claim now says where the socket path comes from (`Gen.Socket`, from the registry row on some layouts) and names both checks. - **Other changed units, all approved:** - Edge and host envelopes re-pinned; nothing reads anything new. - `serveReplicaProbe` and `runAgent`: body changes only. - `replicaProber.Sync`, `sameReplicaJob` and `replicaProber.reset`: in-memory changes only. - `replicaProber.record`: new to the census. It checks identity and the boot ID before ignoring a revision mismatch, and records the boot ID only from an accepted result. - `replicaIdentityMatches`, `replicaEvidenceMatches` and `matchReplicaBoot`: pure comparisons. Dropping the per-host build-stamp checks removes a health filter, not a check root depends on. - **N4 (not blocking, not a census issue), `internal/edge/replicaprober.go:250-251`:** when a box reports a different revision, the prober leaves the old sample and its timestamp untouched. A box that never catches up keeps its last healthy sample indefinitely, so Plan 3 routing should age samples by `ObservedAt`. - **N1 to N3** from the first review still stand and remain deferred. The verdict is appended under "## Re-review (9eeafd07)" in `/home/paulca/amadan.net/carlos/platform/.claude/worktrees/stateless-replicas-3/.superpowers/sdd/2026-11-01-stateless-replicas-3-routing/task-1-census-review.md`.</result> <usage><subagent_tokens>85696</subagent_tokens><tool_uses>13</tool_uses><duration_ms>160399</duration_ms></usage> </task-notification>
<task-notification> <task-id>ac6001126cd327345</task-id> <tool-use-id>toolu_01JAhet4xkiFXJdRgJC8bpVR</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/195ef15b-aac6-42d6-b49b-41ffb7a4abbc/tasks/ac6001126cd327345.output</output-file> <status>completed</status> <summary>Agent "Task 1 scoped re-review" finished</summary> <note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note> <result>All findings are addressed, with no new Critical or Important breakage. The full write-up is in `/home/paulca/amadan.net/carlos/platform/.claude/worktrees/stateless-replicas-3/.superpowers/sdd/2026-11-01-stateless-replicas-3-routing/task-1-rereview-1.md`. - **I1 (Q13):** ADDRESSED. The job key is now (host, incarnation, box) at `internal/edge/replicaprober.go:60-62` and `:146`. `sameReplicaJob` was trimmed (`:150-153`), survivors only refresh their route (`:132-137`), and a skewed revision returns neutral after the identity checks (`:244-252`). Tests are at `replicaprober_test.go:776-909`. - **I2 (Q14):** ADDRESSED. There are no per-host build stamp checks left in `replicaEvidenceMatches` (`replicaprober.go:290-306`), and `TestReplicaProbeMixedBuildsStayLive` (`replicaprober_test.go:750-774`) covers two copies on different builds. - **I3 (Q15):** ADDRESSED by evidence, with no reorder needed. Steering answers only `/` (`steeringprobe.go:110`) and the notice handler only takes POST to `/.carlos/burst-notice` (`burst_notice.go:496`). The landing stays at `edge.go:1987`, after `admissionRefuses` (`:1983`) and after the tunnel-hostname branch (`:1928`). The witness test is at `replicaprobe_test.go:302-325`. - **I4 (census F1):** ADDRESSED. The probe dials through `unixdial.Checked` (`replicaprobe.go:63`), and tests cover both the control socket and a symlink (`replicaprobe_test.go:250-283`). The new seal is `04715476…f5ed0` and the claim is updated (`task-1-claims.tsv:5`). Approving that seal is still the census re-reviewer's job. - **M2:** ADDRESSED. The landing uses `replicaFailed` (`replicaprobe.go:85`). - **M3:** ADDRESSED. The non-Linux build returns nil (`replicahealth_other.go:13`), and the retry logs once and backs off to a 30 s cap (`internal/host/replicahealth.go:29-46`). - **M5:** ADDRESSED. A request-construction error now returns 503 (`replicaprobe.go:66-70`). - **⚠️ (a):** ADDRESSED (moot). Nothing on the hub compares GoodDigest with Gen.Digest any more; the box checks its own digest (`activator/replicaprobe.go:48`, `edge/replicaprobe.go:80`). - **⚠️ (b):** ADDRESSED. The Plan 2 writer citations check out: `provision/reconcile.go:573` and `:605`, `provision/replicaassignment.go:203`, `registry/replicas.go:87-93`. - **New breakage, Minor:** M3 removed the SR-3-C07 string from code, but the copy deck still lists it as pending (`docs/superpowers/plans/2026-11-01-stateless-replicas-copy.md:68`). That row needs retiring before Plan 3 copy is marked built, or `TestStatelessReplicaCopyIsApplied` will fail. - **New breakage, Minor:** the "box" and "boot" cases in `TestReplicaProbeRevisionSkewChangesNothing` (`replicaprober_test.go:893-908`) prove nothing, because the "lifetime" case before them already leaves the reason as stale. Only the lifetime case actually shows identity is checked before the skew return. - **Deferred:** under Q13, a surviving copy whose app is failing stays Live while its box's revision lags behind the hub's. Separately, survivor samples keep their old revision, so Task 3 must not filter `Live` by revision equality.</result> <usage><subagent_tokens>98092</subagent_tokens><tool_uses>18</tool_uses><duration_ms>169646</duration_ms></usage> </task-notification>
Attributed to this commit: 15.1 g CO₂e (1,727,151 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| index d3dde6271..f07cb874e 100644 |
| --- a/docs/superpowers/notes/census-proposal-stateless-replicas-3.md |
| +++ b/docs/superpowers/notes/census-proposal-stateless-replicas-3.md |
| @@ -5,16 +5,18 @@ Ruling `census-ruling-stateless-replicas-3`. The independent reviewer approves o |
| | 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/edge/reqrecords.go` `requestResponse` | body | unchanged (4) | Task 2: copy the final replica box and attempt count from the existing per-request outcome into additive reqrec.Response fields. Existing four Route reads unchanged; no new external read, path, credential or authority. The observer still records one client response at the hub; ordinary requests retain zero fields. | |
| | `internal/host/agent.go` `runAgent` | body | unchanged (5) | Task 1 fix round 1 M3: retain the private snapshot source and cancel/join ownership, but use the replica-health-specific retry loop. It logs its first failure only and retains the existing exponential backoff capped at 30 seconds; unsupported builds return nil. Existing five direct read sites unchanged; no new credentials, bucket reader or app lifecycle action. | |
| | `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`. |
| +Envelopes re-pinned: `internal/activator`, `internal/edge`, `internal/host`, `internal/replicas`, `internal/reqrec`, `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/edge/reqrecords.go` `requestResponse`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-edge-request-records;identity=the edge inside the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos);basis=new: a pure constructor: copies the account (release.RouteAccount of the route), app, host and environment of the route row the edge already resolved for this request, and the request's method, path, raw query, User-Agent, client address and GeoIP country (from the request context), with the status, into a reqrec.Response; the recorder masks the path, keeps only the query's names, and stores the client address only as its /24 (IPv6 /48) prefix and a day-salted hash before anything is stored; the account and app come from the route row, never the Host header; it reads no file, no store and no box state, writes nothing, and makes no decision; the class of Edge.emitEdgeError and UsageMeter.Record (J1 root-route) |
| - `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. |
| @@ -38,6 +40,6 @@ New dispositions, which census-propose wrote and the reviewer checks against the |
| - 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` → `04715476748eb88cc85ac2ab86e859343fa2657ae77027de1837773ae37f5ed0`. |
| +Seal: `59c0891618b9befae27ebe04d0a67b08c7f7658bca9f1c78bf6d05eb7a708e82` → `00eef8089c6cd9ba4725c22c618e871d3b038c958b3db906e1fc6af49ef9a65f`. |
| 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/answered.go b/internal/edge/answered.go| index f83e19692..d4c6315b9 100644 |
| --- a/internal/edge/answered.go |
| +++ b/internal/edge/answered.go |
| @@ -27,9 +27,11 @@ type answeredKey struct{} |
| // 502/503/504 the edge produced, why (an apperr.Cause*, or causeClientGone). |
| // The observing defer in ServeHTTP reads both once the response is written. |
| type outcome struct { |
| - answered bool |
| - cause string |
| - start time.Time // when the edge began serving, so a proxy failure knows how long the client waited |
| + replicaBox string |
| + replicaAttempts int |
| + answered bool |
| + cause string |
| + start time.Time // when the edge began serving, so a proxy failure knows how long the client waited |
| // genHost and gen name the generation whose connection pool carried the |
| // request (genproxy.go), set only by an activator-managed route with |
| // generations on. The cache tags what it stores with them (spec §7.2). |
diff --git a/internal/edge/edge.go b/internal/edge/edge.go| index 90612166e..eb863ff68 100644 |
| --- a/internal/edge/edge.go |
| +++ b/internal/edge/edge.go |
| @@ -3668,15 +3668,7 @@ func multiProxy(host string, p *proberSet, hold localHold) *httputil.ReverseProx |
| // disconnected one fails fast into the stdlib proxy's 502 rather than hanging. |
| func tunnelProxy(name string, hub *TunnelHub) *httputil.ReverseProxy { |
| return &httputil.ReverseProxy{ |
| - Rewrite: func(pr *httputil.ProxyRequest) { |
| - setForwarded(pr) |
| - setGeo(pr, true) // geoip spec §8.3: after hop-header removal, from the request's one answer |
| - pr.Out.URL.Scheme = "https" |
| - pr.Out.URL.Host = pr.In.Host // h2 :authority = the real hostname |
| - pr.Out.Host = pr.In.Host |
| - scrubInboundPurgeHeader(pr) |
| - scrubTunnelMarkers(pr) |
| - }, |
| + Rewrite: tunnelRewrite, |
| Transport: hub.transportFor(name), |
| ErrorHandler: func(w http.ResponseWriter, r *http.Request, err error) { |
| if tunnelUpgradeError(w, r, err, hub) { |
| @@ -3821,15 +3813,7 @@ func fleetBoxOf(t registry.Route) (string, bool) { |
| // boxLabel is that label (fleetBoxOf). |
| func fleetProxy(fleet, boxLabel string, authoritative bool, hub *TunnelHub) *httputil.ReverseProxy { |
| return &httputil.ReverseProxy{ |
| - Rewrite: func(pr *httputil.ProxyRequest) { |
| - setForwarded(pr) |
| - setGeo(pr, true) // geoip spec §8.3: after hop-header removal, from the request's one answer |
| - pr.Out.URL.Scheme = "https" |
| - pr.Out.URL.Host = pr.In.Host // h2 :authority = the real hostname |
| - pr.Out.Host = pr.In.Host |
| - scrubInboundPurgeHeader(pr) |
| - scrubTunnelMarkers(pr) |
| - }, |
| + Rewrite: tunnelRewrite, |
| Transport: roundTripperFunc(func(req *http.Request) (*http.Response, error) { |
| name := fleetChannelFor(fleet, boxLabel, authoritative, hub) |
| if name == "" { |
| @@ -4850,3 +4834,15 @@ func envOr(key, fallback string) string { |
| } |
| return fallback |
| } |
| + |
| +// tunnelRewrite preserves the public host and the hub's trusted forwarding |
| +// metadata for all tunnel dispatchers, after ReverseProxy removes hop headers. |
| +func tunnelRewrite(pr *httputil.ProxyRequest) { |
| + setForwarded(pr) |
| + setGeo(pr, true) |
| + pr.Out.URL.Scheme = "https" |
| + pr.Out.URL.Host = pr.In.Host |
| + pr.Out.Host = pr.In.Host |
| + scrubInboundPurgeHeader(pr) |
| + scrubTunnelMarkers(pr) |
| +} |
diff --git a/internal/edge/replica_retry_test.go b/internal/edge/replica_retry_test.go| new file mode 100644 |
| index 000000000..cb150043b |
| --- /dev/null |
| +++ b/internal/edge/replica_retry_test.go |
| @@ -0,0 +1,204 @@ |
| +package edge |
| + |
| +import ( |
| + "context" |
| + "io" |
| + "net/http" |
| + "strings" |
| + "sync/atomic" |
| + "testing" |
| + "time" |
| +) |
| + |
| +func TestReplicaPostIsNotReplayedAfterDispatch(t *testing.T) { |
| + for _, key := range []string{"", "key"} { |
| + t.Run("idempotency="+key, func(t *testing.T) { |
| + var n atomic.Int32 |
| + handler := func(w http.ResponseWriter, r *http.Request) { |
| + io.Copy(io.Discard, r.Body) |
| + n.Add(1) |
| + panic(http.ErrAbortHandler) |
| + } |
| + hub, p, rt := replicaProxyFixture(t, handler, handler) |
| + req, out := withOutcome(replicaDispatchRequest(t, "POST", strings.NewReader("increment"))) |
| + req.Header.Set("Idempotency-Key", key) |
| + _, proxyErr := replicaProxy(rt.Host, "pi", p, hub).Transport.RoundTrip(req) |
| + increments, attempts := int(n.Load()), out.replicaAttempts |
| + // TestReplicaPostIsNotReplayedAfterDispatch |
| + if increments != 1 || attempts != 1 || proxyErr == nil { |
| + t.Fatal("ambiguous POST was repeated") |
| + } |
| + if len(p.Live(rt.Host)) != 2 { |
| + t.Fatal("ambiguous dispatched error ejected copy") |
| + } |
| + }) |
| + } |
| + t.Run("missing channel preserves body", func(t *testing.T) { |
| + hub, _, _ := replicaProxyFixture(t) |
| + body := &replicaReadCounter{Reader: strings.NewReader("payload")} |
| + req := replicaDispatchRequest(t, "POST", body) |
| + _, dispatched, err := hub.replicaRoundTrip("pi/missing", req) |
| + if dispatched || err == nil || body.reads != 0 || body.closed { |
| + t.Fatal("missing channel consumed body") |
| + } |
| + }) |
| +} |
| + |
| +type replicaReadCounter struct { |
| + io.Reader |
| + reads int |
| + closed bool |
| +} |
| + |
| +func (r *replicaReadCounter) Read(b []byte) (int, error) { r.reads++; return r.Reader.Read(b) } |
| +func (r *replicaReadCounter) Close() error { r.closed = true; return nil } |
| + |
| +func TestReplicaGetRetryBeforeHeaders(t *testing.T) { |
| + for _, method := range []string{"GET", "HEAD"} { |
| + t.Run(method, func(t *testing.T) { |
| + var calls atomic.Int32 |
| + hub, p, rt := replicaProxyFixture(t, func(w http.ResponseWriter, r *http.Request) { calls.Add(1); panic(http.ErrAbortHandler) }, func(w http.ResponseWriter, r *http.Request) { calls.Add(1); w.WriteHeader(204) }) |
| + req, out := withOutcome(replicaDispatchRequest(t, method, nil)) |
| + resp, err := replicaProxy(rt.Host, "pi", p, hub).Transport.RoundTrip(req) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + resp.Body.Close() |
| + if calls.Load() != 2 || out.replicaAttempts != 2 || out.replicaBox != "box-01" { |
| + t.Fatalf("retry metadata: %+v, %d", out, calls.Load()) |
| + } |
| + }) |
| + } |
| + t.Run("one pass", func(t *testing.T) { |
| + var calls atomic.Int32 |
| + f := func(w http.ResponseWriter, r *http.Request) { calls.Add(1); panic(http.ErrAbortHandler) } |
| + h, p, rt := replicaProxyFixture(t, f, f) |
| + _, err := replicaProxy(rt.Host, "pi", p, h).Transport.RoundTrip(replicaDispatchRequest(t, "GET", nil)) |
| + if err == nil || calls.Load() != 2 { |
| + t.Fatalf("unbounded retry: %d %v", calls.Load(), err) |
| + } |
| + }) |
| + t.Run("one shot body", func(t *testing.T) { |
| + var calls atomic.Int32 |
| + f := func(w http.ResponseWriter, r *http.Request) { |
| + calls.Add(1) |
| + io.Copy(io.Discard, r.Body) |
| + panic(http.ErrAbortHandler) |
| + } |
| + h, p, rt := replicaProxyFixture(t, f, f) |
| + req := replicaDispatchRequest(t, "GET", io.NopCloser(strings.NewReader("once"))) |
| + _, err := replicaProxy(rt.Host, "pi", p, h).Transport.RoundTrip(req) |
| + if err == nil || calls.Load() != 1 { |
| + t.Fatal("one shot body replayed") |
| + } |
| + }) |
| + t.Run("cancellation", func(t *testing.T) { |
| + var calls atomic.Int32 |
| + ctx, cancel := context.WithCancel(context.Background()) |
| + defer cancel() |
| + f := func(w http.ResponseWriter, r *http.Request) { calls.Add(1); cancel(); <-r.Context().Done() } |
| + h, p, rt := replicaProxyFixture(t, f, f) |
| + req := replicaDispatchRequest(t, "GET", nil).WithContext(ctx) |
| + _, err := replicaProxy(rt.Host, "pi", p, h).Transport.RoundTrip(req) |
| + if err == nil || calls.Load() != 1 { |
| + t.Fatal("canceled request retried") |
| + } |
| + }) |
| + t.Run("three second bound", func(t *testing.T) { |
| + h, p, rt := replicaProxyFixture(t, func(w http.ResponseWriter, r *http.Request) { <-r.Context().Done() }, func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(204) }) |
| + start := time.Now() |
| + resp, err := replicaProxy(rt.Host, "pi", p, h).Transport.RoundTrip(replicaDispatchRequest(t, "GET", nil)) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + resp.Body.Close() |
| + if d := time.Since(start); d < 3*time.Second || d > 5*time.Second { |
| + t.Fatalf("attempt bound: %s", d) |
| + } |
| + }) |
| +} |
| + |
| +func TestReplicaPreDispatchPostRetry(t *testing.T) { |
| + var calls atomic.Int32 |
| + h, p, rt := replicaProxyFixture(t, func(http.ResponseWriter, *http.Request) { t.Error("missing channel reached") }, func(w http.ResponseWriter, r *http.Request) { |
| + calls.Add(1) |
| + b, err := io.ReadAll(r.Body) |
| + if err != nil || string(b) != "once" { |
| + t.Errorf("body %q %v", b, err) |
| + } |
| + w.WriteHeader(204) |
| + }) |
| + // Model a captured Live set followed by loss of A before channel lookup. |
| + dispatch := NewTunnelHub("tunnel.example.com", nil) |
| + dispatch.conns["pi/box-01"] = h.channel("pi/box-01") |
| + body := &replicaReadCounter{Reader: strings.NewReader("once")} |
| + req, out := withOutcome(replicaDispatchRequest(t, "POST", body)) |
| + resp, err := replicaProxy(rt.Host, "pi", p, dispatch).Transport.RoundTrip(req) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + resp.Body.Close() |
| + if calls.Load() != 1 || out.replicaAttempts != 2 || out.replicaBox != "box-01" || len(p.Live(rt.Host)) != 1 { |
| + t.Fatal("missing channel did not retry POST and eject") |
| + } |
| +} |
| + |
| +func TestReplicaResponseStartedRefusesRetry(t *testing.T) { |
| + var calls atomic.Int32 |
| + h, p, rt := replicaProxyFixture(t, func(w http.ResponseWriter, r *http.Request) { |
| + calls.Add(1) |
| + w.WriteHeader(http.StatusEarlyHints) |
| + panic(http.ErrAbortHandler) |
| + }, func(w http.ResponseWriter, r *http.Request) { calls.Add(1) }) |
| + _, err := replicaProxy(rt.Host, "pi", p, h).Transport.RoundTrip(replicaDispatchRequest(t, "GET", nil)) |
| + if err == nil || calls.Load() != 1 { |
| + t.Fatal("response-started request repeated") |
| + } |
| +} |
| + |
| +func TestReplicaGetRetryReproducibleBody(t *testing.T) { |
| + var calls atomic.Int32 |
| + f := func(w http.ResponseWriter, r *http.Request) { |
| + b, err := io.ReadAll(r.Body) |
| + if err != nil || string(b) != "twice" { |
| + t.Errorf("reproduced body: %q %v", b, err) |
| + } |
| + if calls.Add(1) == 1 { |
| + panic(http.ErrAbortHandler) |
| + } |
| + w.WriteHeader(204) |
| + } |
| + h, p, rt := replicaProxyFixture(t, f, f) |
| + resp, err := replicaProxy(rt.Host, "pi", p, h).Transport.RoundTrip(replicaDispatchRequest(t, "GET", strings.NewReader("twice"))) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + resp.Body.Close() |
| + if calls.Load() != 2 { |
| + t.Fatal("reproducible body did not retry") |
| + } |
| +} |
| + |
| +func TestReplicaRetrySkipsNewlyUnhealthyCopy(t *testing.T) { |
| + var p *replicaProber |
| + h, prober, rt := replicaProxyFixture(t, func(w http.ResponseWriter, r *http.Request) { |
| + p.Eject("shop.example.com", "box-01") |
| + panic(http.ErrAbortHandler) |
| + }, func(http.ResponseWriter, *http.Request) { t.Error("ejected retry candidate was dispatched") }) |
| + p = prober |
| + req, out := withOutcome(replicaDispatchRequest(t, "GET", nil)) |
| + _, err := replicaProxy(rt.Host, "pi", p, h).Transport.RoundTrip(req) |
| + if err == nil || out.replicaAttempts != 1 { |
| + t.Fatal("retried outside the live set") |
| + } |
| +} |
| + |
| +func TestReplicaNoHealthyCopiesAfterMissingChannels(t *testing.T) { |
| + _, p, rt := replicaProxyFixture(t, func(http.ResponseWriter, *http.Request) { t.Error("dispatched") }) |
| + h := NewTunnelHub("tunnel.example.com", nil) |
| + body := &replicaReadCounter{Reader: strings.NewReader("once")} |
| + _, err := replicaProxy(rt.Host, "pi", p, h).Transport.RoundTrip(replicaDispatchRequest(t, "POST", body)) |
| + if err != errReplicaUnavailable || body.reads != 0 || !body.closed { |
| + t.Fatal("missing set was not closed and reported unavailable") |
| + } |
| +} |
diff --git a/internal/edge/replicaprober.go b/internal/edge/replicaprober.go| index f519fe940..f3509529e 100644 |
| --- a/internal/edge/replicaprober.go |
| +++ b/internal/edge/replicaprober.go |
| @@ -340,7 +340,7 @@ func (p *replicaProber) Snapshot(host string) replicas.Snapshot { |
| func (p *replicaProber) Live(host string) []replicas.Copy { |
| var live []replicas.Copy |
| for _, c := range p.Snapshot(host).Copies { |
| - if c.Healthy { |
| + if c.Healthy && !c.ObservedAt.IsZero() && p.clock.Now().Sub(c.ObservedAt) <= replicaProbeFail*replicaProbeInterval+replicaProbeTimeout { |
| live = append(live, c) |
| } |
| } |
diff --git a/internal/edge/replicaprober_test.go b/internal/edge/replicaprober_test.go| index 0048e1668..29089cd36 100644 |
| --- a/internal/edge/replicaprober_test.go |
| +++ b/internal/edge/replicaprober_test.go |
| @@ -416,13 +416,20 @@ func TestReplicaProbeCancellationAndReplacement(t *testing.T) { |
| replicaSettled(t, clock, 1) |
| clock.advance(time.Second) |
| replicaSettled(t, clock, 2) |
| + before := p.Snapshot(rt.Host).Copies[0] |
| canceled.Store(true) |
| for n := 3; n <= 6; n++ { |
| clock.advance(time.Second) |
| replicaSettled(t, clock, n) |
| + if n <= 5 && len(p.Live(rt.Host)) != 1 { |
| + t.Fatal("client cancellation ejected a fresh healthy copy") |
| + } |
| } |
| - if len(p.Live(rt.Host)) != 1 { |
| - t.Fatal("client cancellation ejected healthy copy") |
| + if p.Snapshot(rt.Host).Copies[0] != before { |
| + t.Fatal("client cancellation changed the accepted sample") |
| + } |
| + if len(p.Live(rt.Host)) != 0 { |
| + t.Fatal("canceled probes kept an expired sample selectable") |
| } |
| }) |
| t.Run("late retired job", func(t *testing.T) { |
diff --git a/internal/edge/replicaproxy.go b/internal/edge/replicaproxy.go| new file mode 100644 |
| index 000000000..73e0e715f |
| --- /dev/null |
| +++ b/internal/edge/replicaproxy.go |
| @@ -0,0 +1,205 @@ |
| +package edge |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "io" |
| + "net/http" |
| + "net/http/httptrace" |
| + "net/http/httputil" |
| + "net/textproto" |
| + "sync" |
| + "sync/atomic" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/apperr" |
| + "github.com/carlosframework/platform/internal/replicas" |
| +) |
| + |
| +const ( |
| + replicaAttemptTimeout = 3 * time.Second |
| + // copy SR-3-C01 (provisional) |
| + replicaUnavailable = "no healthy copy is available. try again shortly" |
| + // copy SR-3-C02 (provisional) |
| + replicaNotRepeated = "the connection to this copy ended before it answered. this request was not repeated" |
| +) |
| + |
| +var errReplicaUnavailable = errors.New(replicaUnavailable) |
| + |
| +type replicaUnrepeatedError struct{ error } |
| + |
| +func (e *replicaUnrepeatedError) Unwrap() error { return e.error } |
| + |
| +type replicaTransport struct { |
| + host, fleet string |
| + p *replicaProber |
| + hub *TunnelHub |
| + cursor atomic.Uint64 |
| +} |
| + |
| +func replicaProxy(host, fleet string, p *replicaProber, hub *TunnelHub) *httputil.ReverseProxy { |
| + return &httputil.ReverseProxy{ |
| + Rewrite: tunnelRewrite, |
| + Transport: &replicaTransport{host: host, fleet: fleet, p: p, hub: hub}, |
| + ErrorHandler: func(w http.ResponseWriter, r *http.Request, err error) { |
| + if errors.Is(err, errReplicaUnavailable) { |
| + noteCause(r, apperr.CauseFleetDark) |
| + w.Header().Set("Retry-After", "2") |
| + http.Error(w, replicaUnavailable, http.StatusServiceUnavailable) |
| + return |
| + } |
| + if tunnelUpgradeError(w, r, err, hub) { |
| + return |
| + } |
| + var unrepeated *replicaUnrepeatedError |
| + if errors.As(err, &unrepeated) { |
| + noteCause(r, tunnelCause(r, err)) |
| + http.Error(w, replicaNotRepeated, http.StatusBadGateway) |
| + return |
| + } |
| + defaultProxyError(tunnelCause)(w, r, err) |
| + }, |
| + } |
| +} |
| + |
| +func (t *replicaTransport) RoundTrip(req *http.Request) (*http.Response, error) { |
| + // Capture once: a request never cycles around or expands its retry budget. |
| + live := t.p.Live(t.host) |
| + body := replicaBody(req.Body) |
| + owned := false |
| + defer func() { |
| + if !owned && body != nil { |
| + body.Close() |
| + } |
| + }() |
| + if len(live) == 0 { |
| + return nil, errReplicaUnavailable |
| + } |
| + start := (t.cursor.Add(1) - 1) % uint64(len(live)) |
| + last := errReplicaUnavailable |
| + attempts := 0 |
| + var dispatched bool |
| + var started atomic.Bool |
| + for i := 0; i < len(live); i++ { |
| + if err := req.Context().Err(); err != nil { |
| + return nil, err |
| + } |
| + candidate := live[(int(start)+i)%len(live)] |
| + if i > 0 { |
| + stillLive := false |
| + for _, c := range t.p.Live(t.host) { |
| + if c.Box == candidate.Box && c.Incarnation == candidate.Incarnation { |
| + stillLive = true |
| + break |
| + } |
| + } |
| + if !stillLive { |
| + continue |
| + } |
| + } |
| + if i > 0 && dispatched && body != nil { |
| + if req.GetBody == nil { |
| + return nil, &replicaUnrepeatedError{last} |
| + } |
| + next, err := req.GetBody() |
| + if err != nil { |
| + return nil, err |
| + } |
| + body = replicaBody(next) |
| + owned = false |
| + } |
| + box := candidate.Box |
| + attempts++ |
| + if o := outcomeFrom(req); o != nil { |
| + o.replicaBox = box |
| + o.replicaAttempts = attempts |
| + } |
| + // The deadline ends at headers. Cancellation stays attached until the |
| + // response body (or upgraded connection) closes, without a stream TTL. |
| + ctx, cancel := context.WithCancel(req.Context()) |
| + timer := time.AfterFunc(replicaAttemptTimeout, cancel) |
| + ctx = httptrace.WithClientTrace(ctx, &httptrace.ClientTrace{ |
| + Got1xxResponse: func(int, textproto.MIMEHeader) error { started.Store(true); return nil }, |
| + }) |
| + attempt := req.Clone(ctx) |
| + attempt.Body = body |
| + // Only this loop may reproduce a body. ClientConn itself has no retry |
| + // loop; never expose GetBody to a lower transport or an upgrade helper. |
| + attempt.GetBody = nil |
| + resp, didDispatch, err := t.hub.replicaRoundTrip(t.fleet+"/"+box, attempt) |
| + dispatched = didDispatch |
| + owned = owned || dispatched |
| + stopped := timer.Stop() |
| + if err == nil && stopped && ctx.Err() == nil { |
| + if rw, ok := resp.Body.(io.ReadWriteCloser); ok { |
| + resp.Body = &replicaResponseConn{ReadWriteCloser: rw, cancel: cancel} |
| + } else { |
| + resp.Body = &replicaResponseBody{ReadCloser: resp.Body, cancel: cancel} |
| + } |
| + return resp, nil |
| + } |
| + // Even if the timer won at the headers boundary, a returned response |
| + // ends retry authority. No status, including 500 or 101, is failover. |
| + responseStarted := started.Load() || resp != nil |
| + if resp != nil && resp.Body != nil { |
| + resp.Body.Close() |
| + } |
| + cancel() |
| + if err == nil { |
| + err = context.DeadlineExceeded |
| + } |
| + last = err |
| + if dispatched && body != nil { |
| + body.Close() |
| + } |
| + if !dispatched || t.hub.probeConnection(t.fleet+"/"+box) == nil { |
| + t.p.Eject(t.host, box) |
| + } |
| + if !replicas.RetryAllowed(req.Method, dispatched, responseStarted) { |
| + return nil, &replicaUnrepeatedError{last} |
| + } |
| + } |
| + if !dispatched && len(t.p.Live(t.host)) == 0 { |
| + return nil, errReplicaUnavailable |
| + } |
| + return nil, last |
| +} |
| + |
| +// A one-shot wrapper hides optional replay interfaces and closes once even |
| +// when the h2 writer and the failed-attempt cleanup finish concurrently. |
| +type replicaRequestBody struct { |
| + io.ReadCloser |
| + once sync.Once |
| + err error |
| +} |
| + |
| +func (b *replicaRequestBody) Close() error { |
| + b.once.Do(func() { b.err = b.ReadCloser.Close() }) |
| + return b.err |
| +} |
| +func replicaBody(b io.ReadCloser) io.ReadCloser { |
| + if b == nil || b == http.NoBody { |
| + return nil |
| + } |
| + return &replicaRequestBody{ReadCloser: b} |
| +} |
| + |
| +type replicaResponseBody struct { |
| + io.ReadCloser |
| + cancel context.CancelFunc |
| +} |
| + |
| +func (b *replicaResponseBody) Close() error { defer b.cancel(); return b.ReadCloser.Close() } |
| + |
| +type replicaResponseConn struct { |
| + io.ReadWriteCloser |
| + cancel context.CancelFunc |
| +} |
| + |
| +func (b *replicaResponseConn) Close() error { defer b.cancel(); return b.ReadWriteCloser.Close() } |
| +func (b *replicaResponseConn) CloseWrite() error { |
| + if c, ok := b.ReadWriteCloser.(interface{ CloseWrite() error }); ok { |
| + return c.CloseWrite() |
| + } |
| + return nil |
| +} |
diff --git a/internal/edge/replicaproxy_test.go b/internal/edge/replicaproxy_test.go| new file mode 100644 |
| index 000000000..e05896faf |
| --- /dev/null |
| +++ b/internal/edge/replicaproxy_test.go |
| @@ -0,0 +1,330 @@ |
| +package edge |
| + |
| +import ( |
| + "context" |
| + "fmt" |
| + "io" |
| + "math" |
| + "net" |
| + "net/http" |
| + "net/http/httptest" |
| + "sync/atomic" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/registry" |
| + "github.com/carlosframework/platform/internal/tunnelclient" |
| + "golang.org/x/net/http2" |
| +) |
| + |
| +// Real h2 ClientConns keep the dispatch boundary in the fixture. |
| +func replicaProxyFixture(t *testing.T, handlers ...http.HandlerFunc) (*TunnelHub, *replicaProber, registry.Route) { |
| + t.Helper() |
| + hub, rt := replicaHubFixture(t, len(handlers)) |
| + clock := newReplicaTestClock() |
| + p := newReplicaProber(hub, nil, clock) |
| + p.routes[rt.Host] = rt |
| + for i, handler := range handlers { |
| + box := fmt.Sprintf("box-%02d", i) |
| + channel := "pi/" + box |
| + hub.CloseChannel(channel) |
| + a, b := net.Pipe() |
| + done := make(chan struct{}) |
| + go func() { |
| + defer close(done) |
| + tunnelclient.ServeWith(b, tunnelclient.Mark(handler), tunnelclient.DefaultLimits) |
| + }() |
| + wire := &tunnelWire{Conn: a, closed: make(chan struct{})} |
| + cc, err := (&http2.Transport{}).NewClientConn(wire) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + hub.mu.Lock() |
| + hub.nextGeneration++ |
| + tc := &tunnelConn{raw: wire, cc: cc, closed: wire.closed, generation: hub.nextGeneration, caps: tunnelclient.CapUpgrade} |
| + hub.conns[channel] = tc |
| + hub.mu.Unlock() |
| + c := replicaTestCopy(rt, box) |
| + c.ObservedAt = clock.Now() |
| + p.jobs[replicaSlot{rt.Host, box}] = &replicaJob{key: replicaJobKey{rt.Host, rt.ReplicaIncarnation, box}, route: rt, channel: channel, conn: tc, sample: c} |
| + t.Cleanup(func() { |
| + cc.Close() |
| + b.Close() |
| + select { |
| + case <-done: |
| + case <-time.After(5 * time.Second): |
| + t.Error("h2 fixture did not stop") |
| + } |
| + }) |
| + } |
| + return hub, p, rt |
| +} |
| + |
| +func replicaDispatchRequest(t *testing.T, method string, body io.Reader) *http.Request { |
| + t.Helper() |
| + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) |
| + t.Cleanup(cancel) |
| + r, err := http.NewRequestWithContext(ctx, method, "https://shop.example.com/", body) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return r |
| +} |
| + |
| +func TestReplicaRoundRobinAndEjection(t *testing.T) { |
| + var counts [2]atomic.Int32 |
| + hub, p, rt := replicaProxyFixture(t, |
| + func(w http.ResponseWriter, r *http.Request) { counts[0].Add(1); io.WriteString(w, "A") }, |
| + func(w http.ResponseWriter, r *http.Request) { counts[1].Add(1); io.WriteString(w, "B") }) |
| + proxy := replicaProxy(rt.Host, "pi", p, hub) |
| + srv := httptest.NewServer(proxy) |
| + defer srv.Close() |
| + client := srv.Client() |
| + client.Timeout = 10 * time.Second |
| + for i := 0; i < 1000; i++ { |
| + resp, err := client.Get(srv.URL) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + io.Copy(io.Discard, resp.Body) |
| + resp.Body.Close() |
| + } |
| + if d := counts[0].Load() - counts[1].Load(); d < -1 || d > 1 { |
| + t.Fatalf("unbalanced: %v %v", counts[0].Load(), counts[1].Load()) |
| + } |
| + transport := proxy.Transport.(*replicaTransport) |
| + transport.cursor.Store(math.MaxUint64) |
| + for i := 0; i < 4; i++ { |
| + resp, err := client.Get(srv.URL) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + io.Copy(io.Discard, resp.Body) |
| + resp.Body.Close() |
| + } |
| + p.Eject(rt.Host, "box-00") |
| + for i := 0; i < 3; i++ { |
| + resp, err := client.Get(srv.URL) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + b, _ := io.ReadAll(resp.Body) |
| + resp.Body.Close() |
| + if string(b) != "B" { |
| + t.Fatalf("after eject: %s", b) |
| + } |
| + } |
| +} |
| + |
| +func TestReplicaNoHealthyCopies(t *testing.T) { |
| + hub, p, rt := replicaProxyFixture(t, func(http.ResponseWriter, *http.Request) { t.Error("unhealthy copy dispatched") }) |
| + p.Eject(rt.Host, "box-00") |
| + w := httptest.NewRecorder() |
| + replicaProxy(rt.Host, "pi", p, hub).ServeHTTP(w, replicaDispatchRequest(t, "GET", nil)) |
| + if w.Code != 503 || w.Header().Get("Retry-After") != "2" || w.Body.String() != "no healthy copy is available. try again shortly\n" { |
| + t.Fatalf("%d %v %q", w.Code, w.Header(), w.Body.String()) |
| + } |
| +} |
| + |
| +func TestReplicaSamplesAgeOut(t *testing.T) { |
| + hub, p, rt := replicaProxyFixture(t, func(http.ResponseWriter, *http.Request) {}) |
| + _ = hub |
| + clock := p.clock.(*replicaTestClock) |
| + // Revision skew preserves the accepted sample, not indefinite selection. |
| + r := p.routes[rt.Host] |
| + r.ReplicaRevision++ |
| + p.routes[rt.Host] = r |
| + clock.advance(3 * time.Second) |
| + if len(p.Live(rt.Host)) != 1 { |
| + t.Fatal("fresh boundary sample lost or revision filtered") |
| + } |
| + clock.advance(time.Nanosecond) |
| + if len(p.Live(rt.Host)) != 0 { |
| + t.Fatal("stale sample selectable") |
| + } |
| +} |
| + |
| +func TestReplicaStreamingAndUpgradeLoss(t *testing.T) { |
| + t.Run("stream", func(t *testing.T) { |
| + var attempts atomic.Int32 |
| + hub, p, rt := replicaProxyFixture(t, func(w http.ResponseWriter, r *http.Request) { |
| + attempts.Add(1) |
| + io.WriteString(w, "first\n") |
| + w.(http.Flusher).Flush() |
| + <-r.Context().Done() |
| + }, func(w http.ResponseWriter, r *http.Request) { attempts.Add(1); io.WriteString(w, "B") }) |
| + proxy := replicaProxy(rt.Host, "pi", p, hub) |
| + srv := httptest.NewServer(proxy) |
| + defer srv.Close() |
| + client := srv.Client() |
| + client.Timeout = 10 * time.Second |
| + resp, err := client.Get(srv.URL) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + b := make([]byte, 6) |
| + if _, err := io.ReadFull(resp.Body, b); err != nil { |
| + t.Fatal(err) |
| + } |
| + hub.CloseChannel("pi/box-00") |
| + _, err = io.ReadAll(resp.Body) |
| + resp.Body.Close() |
| + if err == nil || attempts.Load() != 1 { |
| + t.Fatalf("stream replay: %v %d", err, attempts.Load()) |
| + } |
| + resp, err = client.Get(srv.URL) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + b, err = io.ReadAll(resp.Body) |
| + resp.Body.Close() |
| + if err != nil || string(b) != "B" { |
| + t.Fatalf("reconnect: %q %v", b, err) |
| + } |
| + }) |
| + t.Run("500", func(t *testing.T) { |
| + var calls atomic.Int32 |
| + h, p, rt := replicaProxyFixture(t, func(w http.ResponseWriter, r *http.Request) { calls.Add(1); w.WriteHeader(500) }, func(w http.ResponseWriter, r *http.Request) { calls.Add(1) }) |
| + resp, err := replicaProxy(rt.Host, "pi", p, h).Transport.RoundTrip(replicaDispatchRequest(t, "GET", nil)) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + resp.Body.Close() |
| + if resp.StatusCode != 500 || calls.Load() != 1 { |
| + t.Fatal("HTTP failure retried") |
| + } |
| + }) |
| +} |
| + |
| +func replicaUpgradeAdmission(h *TunnelHub, rt registry.Route) upgradeAdmission { |
| + ten := tenancy{Arm: ArmForward, Account: rt.Account, App: rt.App, Fleet: "pi"} |
| + e := &Edge{} |
| + ups := map[string]upstream{rt.Host: {route: rt, tenancy: ten}} |
| + e.upstreams.Store(&ups) |
| + h.edge = e |
| + return upgradeAdmission{Host: rt.Host, Path: "/socket", Tenancy: ten} |
| +} |
| + |
| +func TestReplicaStreamingAndUpgradeLossUpgrade(t *testing.T) { |
| + var calls atomic.Int32 |
| + f := func(w http.ResponseWriter, r *http.Request) { |
| + calls.Add(1) |
| + conn, rw, err := w.(http.Hijacker).Hijack() |
| + if err != nil { |
| + t.Error(err) |
| + return |
| + } |
| + defer conn.Close() |
| + io.WriteString(rw, "HTTP/1.1 101 Switching Protocols\r\nConnection: Upgrade\r\nUpgrade: websocket\r\n\r\n") |
| + rw.Flush() |
| + io.Copy(conn, conn) |
| + } |
| + h, p, rt := replicaProxyFixture(t, f, f) |
| + adm := replicaUpgradeAdmission(h, rt) |
| + proxy := replicaProxy(rt.Host, "pi", p, h) |
| + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + proxy.ServeHTTP(w, r.WithContext(withUpgradeAdmission(r.Context(), adm))) |
| + })) |
| + defer srv.Close() |
| + c, br, resp, _, err := rawUpgrade(srv.URL, rt.Host) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer c.Close() |
| + if resp.StatusCode != 101 { |
| + t.Fatalf("upgrade status %d", resp.StatusCode) |
| + } |
| + // The header deadline must not become an upgraded stream lifetime. |
| + time.Sleep(replicaAttemptTimeout + 20*time.Millisecond) |
| + io.WriteString(c, "ping\n") |
| + if line, err := br.ReadString('\n'); err != nil || line != "ping\n" { |
| + t.Fatalf("upgrade expired: %q %v", line, err) |
| + } |
| + old := h.channel("pi/box-00") |
| + h.CloseChannel("pi/box-00") |
| + if _, err := br.ReadByte(); err == nil || calls.Load() != 1 { |
| + t.Fatal("101 was replayed") |
| + } |
| + waitOpen(t, h.edge, old, 0, "lost upgrade") |
| + c2, _, resp, _, err := rawUpgrade(srv.URL, rt.Host) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer c2.Close() |
| + if resp.StatusCode != 101 || calls.Load() != 2 { |
| + t.Fatal("upgrade reconnect did not select survivor") |
| + } |
| + c2.Close() |
| + waitOpen(t, h.edge, h.channel("pi/box-01"), 0, "client closed") |
| +} |
| + |
| +func TestReplicaUpgradeReservationCleanup(t *testing.T) { |
| + h, _, rt := replicaProxyFixture(t, func(w http.ResponseWriter, r *http.Request) { panic(http.ErrAbortHandler) }) |
| + adm := replicaUpgradeAdmission(h, rt) |
| + req := replicaDispatchRequest(t, "GET", nil) |
| + req = req.WithContext(withUpgradeAdmission(req.Context(), adm)) |
| + req.Header.Set("Connection", "Upgrade") |
| + req.Header.Set("Upgrade", "websocket") |
| + _, dispatched, err := h.replicaRoundTrip("pi/box-00", req) |
| + // The parent context is still live: only transport cleanup can release. |
| + if err == nil || !dispatched || heldFor(h.edge, rt.Host) != 0 { |
| + t.Fatal("failed upgrade retained its reservation") |
| + } |
| +} |
| + |
| +func TestReplicaUpgradeAdmissionEveryAttempt(t *testing.T) { |
| + for _, mode := range []string{"capability", "cap", "tenancy", "no admission"} { |
| + t.Run(mode, func(t *testing.T) { |
| + var calls atomic.Int32 |
| + h, p, rt := replicaProxyFixture(t, func(w http.ResponseWriter, r *http.Request) { calls.Add(1); panic(http.ErrAbortHandler) }, func(w http.ResponseWriter, r *http.Request) { t.Error("refused upgrade reached second copy") }) |
| + adm := replicaUpgradeAdmission(h, rt) |
| + tc := h.channel("pi/box-01") |
| + switch mode { |
| + case "capability": |
| + tc.caps = "" |
| + case "cap": |
| + h.edge.open.perConn = map[*tunnelConn]int{tc: h.upgradeCap} |
| + case "tenancy": |
| + adm.Tenancy.App = "another" |
| + } |
| + req := replicaDispatchRequest(t, "GET", nil) |
| + if mode != "no admission" { |
| + req = req.WithContext(withUpgradeAdmission(req.Context(), adm)) |
| + } |
| + req.Header.Set("Connection", "Upgrade") |
| + req.Header.Set("Upgrade", "websocket") |
| + _, err := replicaProxy(rt.Host, "pi", p, h).Transport.RoundTrip(req) |
| + if err == nil || heldFor(h.edge, rt.Host) != 0 { |
| + t.Fatal("admission bypass or leaked reservation") |
| + } |
| + want := int32(1) |
| + if mode == "tenancy" || mode == "no admission" { |
| + want = 0 |
| + } |
| + if calls.Load() != want { |
| + t.Fatalf("first copy calls %d want %d", calls.Load(), want) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestReplicaClientResponseMeteredOnce(t *testing.T) { |
| + h, p, rt := replicaProxyFixture(t, func(w http.ResponseWriter, r *http.Request) { panic(http.ErrAbortHandler) }, func(w http.ResponseWriter, r *http.Request) { io.WriteString(w, "served") }) |
| + e := edgeWithBackend(t, http.NotFoundHandler()) |
| + // Fixture-only installation; Reload and FleetArmVerdict belong to Task 3. |
| + ups := map[string]upstream{rt.Host: {route: rt, proxy: replicaProxy(rt.Host, "pi", p, h), viaTunnel: true}} |
| + e.upstreams.Store(&ups) |
| + meter := NewUsageMeter() |
| + e.EnableUsage(meter) |
| + records := &memRecorder{} |
| + e.EnableRequestRecords(records) |
| + w := httptest.NewRecorder() |
| + e.ServeHTTP(w, httptest.NewRequest("GET", "http://"+rt.Host+"/", nil)) |
| + row := meter.Drain().Rows[rt.Host] |
| + if w.Code != 200 || w.Body.String() != "served" || row.Requests != 1 || row.BytesOut != 6 { |
| + t.Fatalf("response/meter: %d %q %+v", w.Code, w.Body.String(), row) |
| + } |
| + if len(records.resp) != 1 || records.resp[0].Attempts != 2 || records.resp[0].SelectedBox != "box-01" { |
| + t.Fatalf("records: %+v", records.resp) |
| + } |
| +} |
diff --git a/internal/edge/reqrecords.go b/internal/edge/reqrecords.go| index d30585f56..456e79ebe 100644 |
| --- a/internal/edge/reqrecords.go |
| +++ b/internal/edge/reqrecords.go |
| @@ -40,12 +40,16 @@ func (e *Edge) EnableRequestRecords(rec RequestRecorder) { |
| // is the route's as it was when this request was served. |
| func requestResponse(rt registry.Route, r *http.Request, status int) reqrec.Response { |
| geoAns, _ := geoAnswerFrom(r.Context()) |
| - return reqrec.Response{ |
| + x := reqrec.Response{ |
| Acct: release.RouteAccount(rt), App: rt.App, Host: rt.Host, Environment: rt.Environment, |
| Method: r.Method, Path: r.URL.Path, RawQuery: r.URL.RawQuery, |
| UA: r.Header.Get("User-Agent"), ClientIP: clientIP(r), Country: geoAns.Country, |
| Status: status, |
| } |
| + if o := outcomeFrom(r); o != nil { |
| + x.SelectedBox, x.Attempts = o.replicaBox, o.replicaAttempts |
| + } |
| + return x |
| } |
| // observeRecords files one Response for a completed response. It runs inside |
diff --git a/internal/edge/reqrecords_test.go b/internal/edge/reqrecords_test.go| index f1effb46e..3a66a8ad2 100644 |
| --- a/internal/edge/reqrecords_test.go |
| +++ b/internal/edge/reqrecords_test.go |
| @@ -151,3 +151,22 @@ func TestEnableRequestRecordsNil(t *testing.T) { |
| e.EnableRequestRecords(nil) |
| e.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest("GET", "http://app.test/x", nil)) |
| } |
| + |
| +func TestReplicaRequestRecordSelection(t *testing.T) { |
| + h, p, rt := replicaProxyFixture(t, func(w http.ResponseWriter, r *http.Request) { panic(http.ErrAbortHandler) }, func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(404) }) |
| + req, _ := withOutcome(replicaDispatchRequest(t, "GET", nil)) |
| + rec := &memRecorder{} |
| + e := &Edge{} |
| + e.EnableRequestRecords(rec) |
| + w := httptest.NewRecorder() |
| + ob := &countingWriter{ResponseWriter: w} |
| + replicaProxy(rt.Host, "pi", p, h).ServeHTTP(ob, req) |
| + e.observeRecords(rt, true, req, ob, outcomeFrom(req)) |
| + if len(rec.resp) != 1 || rec.resp[0].SelectedBox != "box-01" || rec.resp[0].Attempts != 2 || rec.resp[0].WokeKnown { |
| + t.Fatalf("records: %+v", rec.resp) |
| + } |
| + legacy := requestResponse(rt, replicaDispatchRequest(t, "GET", nil), 200) |
| + if legacy.SelectedBox != "" || legacy.Attempts != 0 { |
| + t.Fatal("legacy tagged as replica") |
| + } |
| +} |
diff --git a/internal/edge/tunnel.go b/internal/edge/tunnel.go| index 5810a41bd..48d9b7ca5 100644 |
| --- a/internal/edge/tunnel.go |
| +++ b/internal/edge/tunnel.go |
| @@ -598,3 +598,20 @@ func (h *TunnelHub) matchReplicaBoot(c *tunnelConn, boot string, learn bool) boo |
| } |
| return c.probeBoot == "" || c.probeBoot == boot |
| } |
| + |
| +// replicaRoundTrip reports false only before touching the body or calling a |
| +// transport. ClientConn.RoundTrip (unlike http2.Transport) never retries. All |
| +// errors after entering that boundary are ambiguous, including stream resets |
| +// and upgrade admission failures; none proves an app did not act. |
| +func (h *TunnelHub) replicaRoundTrip(channel string, req *http.Request) (*http.Response, bool, error) { |
| + tc := h.channel(channel) |
| + if tc == nil { |
| + return nil, false, fmt.Errorf("tunnel %q not connected", channel) |
| + } |
| + if isUpgradeRequest(req) { |
| + resp, err := h.roundTripUpgrade(channel, req) |
| + return resp, true, err |
| + } |
| + resp, err := tc.cc.RoundTrip(req) |
| + return resp, true, err |
| +} |
diff --git a/internal/provision/testdata/plan14-root-reads-chain.tsv b/internal/provision/testdata/plan14-root-reads-chain.tsv| index 3c9d0438f..ae7f319fd 100644 |
| --- a/internal/provision/testdata/plan14-root-reads-chain.tsv |
| +++ b/internal/provision/testdata/plan14-root-reads-chain.tsv |
| @@ -82,4 +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 04715476748eb88cc85ac2ab86e859343fa2657ae77027de1837773ae37f5ed0 |
| +plan14-root-reads-stateless-replicas-3.tsv 00eef8089c6cd9ba4725c22c618e871d3b038c958b3db906e1fc6af49ef9a65f |
diff --git a/internal/provision/testdata/plan14-root-reads-stateless-replicas-3.tsv b/internal/provision/testdata/plan14-root-reads-stateless-replicas-3.tsv| index 47627e6b4..67b505b90 100644 |
| --- a/internal/provision/testdata/plan14-root-reads-stateless-replicas-3.tsv |
| +++ b/internal/provision/testdata/plan14-root-reads-stateless-replicas-3.tsv |
| @@ -1,7 +1,8 @@ |
| # 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. |
| +# 3 body, 1 sites, 6 envelope: each changed unit re-frozen at its existing disposition with its claim appended. |
| # 17 new dispositions: 0 reads re-frozen at their disposition with the claim, 17 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 d1fceb749957ef6abc6e2c02bdfae532fcdaba22eb152dc0acbfe00051699e16 internal/edge/reqrecords.go requestResponse legacy accepted-legacy accepted-legacy;rev3=census-ruling-edge-request-records;identity=the edge inside the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos);basis=new: a pure constructor: copies the account (release.RouteAccount of the route), app, host and environment of the route row the edge already resolved for this request, and the request's method, path, raw query, User-Agent, client address and GeoIP country (from the request context), with the status, into a reqrec.Response; the recorder masks the path, keeps only the query's names, and stores the client address only as its /24 (IPv6 /48) prefix and a day-salted hash before anything is stored; the account and app come from the route row, never the Host header; it reads no file, no store and no box state, writes nothing, and makes no decision; the class of Edge.emitEdgeError and UsageMeter.Record (J1 root-route);rev3=census-ruling-stateless-replicas-3;basis=Task 2: copy the final replica box and attempt count from the existing per-request outcome into additive reqrec.Response fields. Existing four Route reads unchanged; no new external read, path, credential or authority. The observer still records one client response at the hub; ordinary requests retain zero fields. registry:App@190,registry:Environment@226,registry:Host@204,whole:Route@180 0eb4f75b1d48476ac610f69e0c3621a44995eb6c4ebf63d002c95a3496ad7c0e |
| @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 14804d70792904629f6a6c21a6c46994a723b86dee0c5b60ebf5bb8c8721aa55 internal/edge/replicaprobe.go Edge.serveReplicaProbe legacy accepted-legacy accepted-legacy;rev3=census-ruling-stateless-replicas-3;basis=Task 1 fix round 1 I4/F1: the dialled pathname comes from the serving Gen.Socket and, for shared/foreign layouts, can originate in the registry row Socket. Dial through unixdial.Checked: refuse the instance-control directory before connect and require getpeername to match the dialled path before sending HTTP, including symlink refusal. Existing Route reads unchanged. M5 handles request construction errors before RoundTrip; M2 uses the shared reason constant. Authenticated private landing, held-leg admission, one-second bound and post-response identity checks remain. registry:FleetBoxes@390,registry:HA@459,registry:Hibernate@443,registry:Host@346,registry:Kind@365,whole:Route@1025,whole:Route@1215,whole:Route@2268,whole:Route@706 8b158b6a5f414bc8290e9b13b0c27da2002920e837b7c9e98aea0771c98bac5e |
| @@ -21,6 +22,7 @@ |
| @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/edge/reqrecords.go requestResponse legacy accepted-legacy accepted-legacy;rev3=census-ruling-edge-request-records;identity=the edge inside the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos);basis=new: a pure constructor: copies the account (release.RouteAccount of the route), app, host and environment of the route row the edge already resolved for this request, and the request's method, path, raw query, User-Agent, client address and GeoIP country (from the request context), with the status, into a reqrec.Response; the recorder masks the path, keeps only the query's names, and stores the client address only as its /24 (IPv6 /48) prefix and a day-salted hash before anything is stored; the account and app come from the route row, never the Host header; it reads no file, no store and no box state, writes nothing, and makes no decision; the class of Edge.emitEdgeError and UsageMeter.Record (J1 root-route);rev3=census-ruling-stateless-replicas-3;basis=Task 2: copy the final replica box and attempt count from the existing per-request outcome into additive reqrec.Response fields. Existing four Route reads unchanged; no new external read, path, credential or authority. The observer still records one client response at the hub; ordinary requests retain zero fields. registry:App@190,registry:Environment@226,registry:Host@204,whole:Route@180 0eb4f75b1d48476ac610f69e0c3621a44995eb6c4ebf63d002c95a3496ad7c0e |
| 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 1 fix round 1 M3: retain the private snapshot source and cancel/join ownership, but use the replica-health-specific retry loop. It logs its first failure only and retains the existing exponential backoff capped at 30 seconds; unsupported builds return nil. Existing five direct read sites unchanged; no new credentials, bucket reader or app lifecycle action. file:Exec@18226,file:Open@1517,file:Statfs@47850,registry:App@11938,whole:Route@11930 916ecf4ddcec9c37f1233710a3e8dbba4d0c8b952d60b6a4831d45258b7591bc |
| 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 |
| @@ -41,7 +43,8 @@ internal/edge/tunnel.go tunnelWire.Read legacy accepted-legacy accepted-legacy;r |
| 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 b5ebd4ef870dbf9ced5337ff30a0c1039b0db4ba03f136780a74d9d22550696a |
| +@coverage internal/edge ab38d53cf6d787b4747b0c8ad33e1e0b25cd9c8cfc786e8cc6a87e2e78915eee |
| @coverage internal/host 8202b947824702b5897bdb32875ea7ab1386bd0b8f077f5ec1d506c2038f565a |
| -@coverage internal/replicas 2c780322923afa8a3c3ec017f57d2b165858f21d38225fd16ef52d1402e5316a |
| +@coverage internal/replicas 550a02209630a661b8d786822fd51607a4d0481af9ea79e91d270faa1a70d942 |
| +@coverage internal/reqrec 384ce988cf87bb60daac7b64f4f398f79b6e09d475698263c5c5b0f36a512ae9 |
| @coverage internal/tunnelclient a5bd418d97ee5e5d2bb9550dd35e2456b1c06fc541b82fe1e40a5594ed6fba30 |
diff --git a/internal/replicas/retry.go b/internal/replicas/retry.go| new file mode 100644 |
| index 000000000..83f8adf4d |
| --- /dev/null |
| +++ b/internal/replicas/retry.go |
| @@ -0,0 +1,7 @@ |
| +package replicas |
| + |
| +// RetryAllowed judges dispatch evidence, independently of body replayability. |
| +// Once any response reached the client, no request may be repeated. |
| +func RetryAllowed(method string, dispatched, responseStarted bool) bool { |
| + return !responseStarted && (!dispatched || method == "GET" || method == "HEAD") |
| +} |
diff --git a/internal/replicas/retry_test.go b/internal/replicas/retry_test.go| new file mode 100644 |
| index 000000000..f7d12ce0f |
| --- /dev/null |
| +++ b/internal/replicas/retry_test.go |
| @@ -0,0 +1,16 @@ |
| +package replicas |
| + |
| +import "testing" |
| + |
| +func TestReplicaRetryAllowed(t *testing.T) { |
| + for _, method := range []string{"GET", "HEAD", "POST", "PUT", "PATCH", "DELETE", "OPTIONS", "get"} { |
| + for _, dispatched := range []bool{false, true} { |
| + for _, started := range []bool{false, true} { |
| + want := !started && (!dispatched || method == "GET" || method == "HEAD") |
| + if got := RetryAllowed(method, dispatched, started); got != want { |
| + t.Errorf("RetryAllowed(%q,%v,%v)=%v want %v", method, dispatched, started, got, want) |
| + } |
| + } |
| + } |
| + } |
| +} |
diff --git a/internal/reqrec/recorder.go b/internal/reqrec/recorder.go| index be4f97346..0eb90a970 100644 |
| --- a/internal/reqrec/recorder.go |
| +++ b/internal/reqrec/recorder.go |
| @@ -92,6 +92,11 @@ func methodIndex(m string) int { |
| // Response is one response the edge served. It carries raw request data; the |
| // recorder redacts it before anything leaves. |
| type Response struct { |
| + // Replica selection is absent for ordinary requests. Attempts includes |
| + // pre-dispatch missing channels; SelectedBox names the last selection. |
| + SelectedBox string |
| + Attempts int |
| + |
| Acct, App, Host, Method, Path, RawQuery, UA, ClientIP, Country string |
| // Environment is the route's environment when the request was served |
| // (registry.Route.Environment), "" for none. A route can change later, |
| @@ -415,6 +420,10 @@ func (r *Recorder) fields(x Response, kind Kind) map[string]string { |
| } |
| set(f, "qnames", QueryNames(x.RawQuery)) |
| set(f, "env", x.Environment) |
| + set(f, "selected_box", truncate(escapeControls(strings.ToValidUTF8(x.SelectedBox, "\ufffd")), 128)) |
| + if x.Attempts > 0 { |
| + f["attempts"] = strconv.Itoa(x.Attempts) |
| + } |
| set(f, "country", x.Country) |
| set(f, "client", ClientPrefix(x.ClientIP)) |
| if key := ClientKey(x.ClientIP); key != "" { |
diff --git a/internal/reqrec/replica_test.go b/internal/reqrec/replica_test.go| new file mode 100644 |
| index 000000000..07bff4fd0 |
| --- /dev/null |
| +++ b/internal/reqrec/replica_test.go |
| @@ -0,0 +1,48 @@ |
| +package reqrec |
| + |
| +import ( |
| + "encoding/json" |
| + "reflect" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/applog" |
| +) |
| + |
| +func TestReplicaRecordWireFields(t *testing.T) { |
| + s := &memSink{} |
| + now := time.Unix(100, 0).UTC() |
| + r := NewRecorder(s, nil, func() time.Time { return now }) |
| + x := Response{Acct: "bab", App: "shop", Method: "GET", Path: "/", Status: 404, When: now} |
| + r.Response(x) |
| + old, _ := json.Marshal(s.recs[0]) |
| + if string(old) != `{"kind":"notfound","method":"GET","path":"/","status":"404","ua":"empty"}` { |
| + t.Fatalf("legacy record changed: %s", old) |
| + } |
| + x.SelectedBox = "box-01" |
| + x.Attempts = 2 |
| + r.Response(x) |
| + f := s.recs[1] |
| + if f["selected_box"] != "box-01" || f["attempts"] != "2" { |
| + t.Fatalf("selection absent: %v", f) |
| + } |
| + // The sink/chunk and console/CLI decoders carry the generic Fields map. |
| + records := []applog.Record{{TS: now, Fields: f}} |
| + wire, err := applog.EncodeChunk(records) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + decoded, err := applog.DecodeChunk(wire) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if !reflect.DeepEqual(decoded, records) { |
| + t.Fatalf("wire lost fields: %+v", decoded) |
| + } |
| + delete(f, "selected_box") |
| + delete(f, "attempts") |
| + b, _ := json.Marshal(f) |
| + if string(b) != string(old) { |
| + t.Fatal("replica metadata changed legacy fields") |
| + } |
| +} |