Merge remote-tracking branch 'origin/main' into billing-usage
28 files changed,
+3,109
−14
docs/superpowers/notes/census-proposal-region-ha-p1b2.md+39 −0docs/superpowers/plans/2026-10-29-region-ha-p1b2-forwarding.md+192 −0docs/superpowers/plans/CODEX-PLAN-REGION-HA-P1B2-BRIEF-1.md+41 −0docs/superpowers/plans/CODEX-PLAN-REGION-HA-P1B2-BRIEF-2.md+50 −0docs/superpowers/plans/CODEX-PLAN-REGION-HA-P1B2-BRIEF-3.md+53 −0docs/superpowers/plans/CODEX-PLAN-REGION-HA-P1B2-R1.md+47 −0docs/superpowers/plans/CODEX-PLAN-REGION-HA-P1B2-R2.md+70 −0docs/superpowers/plans/CODEX-PLAN-REGION-HA-P1B2-R3.md+64 −0docs/superpowers/plans/CODEX-REVIEW-BRIEF-REGION-HA-P1B2-BRANCH-1.md+30 −0docs/superpowers/plans/CODEX-REVIEW-REGION-HA-P1B2-BRANCH-1-RECHECK.md+9 −0docs/superpowers/plans/CODEX-REVIEW-REGION-HA-P1B2-BRANCH-1.md+23 −0internal/activator/activator.go+17 −5internal/activator/hacache.go+183 −0internal/activator/haforward.go+220 −0internal/activator/haforward_test.go+519 −0internal/edge/assetcatch.go+3 −0internal/edge/backhaul_e2e_test.go+3 −3internal/edge/cookiescope.go+9 −2internal/edge/edge.go+44 −3internal/edge/forwardha.go+230 −0internal/edge/forwardha_test.go+962 −0internal/edge/holderview.go+59 −0internal/edge/holderview_test.go+135 −0internal/edge/homemap.go+12 −0internal/edge/regional.go+2 −1internal/host/haforward_wiring_test.go+61 −0internal/provision/testdata/plan14-root-reads-chain.tsv+1 −0internal/provision/testdata/plan14-root-reads-region-ha-p1b2.tsv+31 −0
CI failed — run details
diff --git a/docs/superpowers/notes/census-proposal-region-ha-p1b2.md b/docs/superpowers/notes/census-proposal-region-ha-p1b2.md| new file mode 100644 |
| index 000000000..4e875ed7e |
| --- /dev/null |
| +++ b/docs/superpowers/notes/census-proposal-region-ha-p1b2.md |
| @@ -0,0 +1,39 @@ |
| +# Census approval: region-ha-p1b2 |
| + |
| +Ruling `census-ruling-region-ha-p1b2`. The independent reviewer approves or rejects every change below, 9 with a new disposition; nothing goes to the census owner (Paul, #280, 2026-10-26). |
| + |
| +| unit | change | read sites | what changed | |
| +|---|---|---|---| |
| +| `internal/activator/activator.go` `Service.doWake` | body | unchanged (84) | region HA P1b-2: a successful acquire drops the host's holder-cache entry; same reads | |
| +| `internal/activator/activator.go` `type Service` | body | unchanged (0) | region HA P1b-2: gains the holder cache and its single-flight state; no read | |
| +| `internal/edge/cookiescope.go` `Edge.responseModifier` | body | unchanged (2) | region HA P1b-2: strips an app-supplied X-Carlos-Holder (header, announced trailer name, trailer values at body close) so only the platform names a lease holder; same reads | |
| +| `internal/edge/edge.go` `Edge.ServeHTTP` | body | unchanged (27) | region HA P1b-2 (N-HA10): one call, frontForwardHA, right after the route lookup's !ok block and before the login POST; same reads | |
| +| `internal/activator/activator.go` `Service.serve` | sites | +whole:Route ×2 | region HA P1b-2: a verified HA hop this box cannot serve gets the holder diagnostic; two new whole:Route sites pass the route to answerForwarded/noteNoHolder; no new kind of read | |
| + |
| +Envelopes re-pinned: `internal/activator`, `internal/edge`. |
| + |
| +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/activator/activator.go` `Service.doWake`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-292fix;basis=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): main's body (census ruling 292's legacy start mark and lease give-back; census ruling owed's pending record) with the seeded change ruled under census-ruling-seeded-instances (the refreshed row checked against the row the wake began from, twice; the seed's first upload recorded after the wake), and now one more line on a failed start: a start its pre-exec gate refused (launchNotStarted: the exec gate, the pending record or its recheck answered no before root was asked) is recorded as known not started (stopObservation.notStarted) instead of uncertain, only when the wake has started nothing else (wakeStartedNothing); otherwise it goes through cleanupFailedWake and its proofs. A refusal before its lease (step 1), which has started nothing, is recorded the same way. Read sites unchanged; no new read and no root decision;rev3=census-ruling-wake-latency-1;identity=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos);basis=marks the end of each wake step on the woken instance's journal timer (wakeSteps: a.now() and a slice append, journal only); no read added, no step reordered;rev3=census-ruling-region-ha-p1a;basis=the agent as carlos: (1) after the restore it asks the backend for the replication class an HA restore imported from the host's published wake state (restoredReplication(rt)) and, if it differs, logs it and sets rt.Replication and the entry's route to it; (2) an HA lease of the stream class replicates with a 1 s monitor interval (SetMonitorInterval); (3) after Replicate, an HA replica opens the entry's files publisher (openEntryFiles(ctx, e, rt)) and starts it, and a publisher that will not open fails the wake through cleanupFailedWake; (4) every cleanupFailedWake call passes e; (5) final fix F1: the two start-error arms that gave the lease straight back (a start its pre-exec gate refused with nothing started, and the default arm) now call giveBackAfterStart(ctx, rt, w, lease), which gives a legacy lease back exactly as before and an HA one only over an empty host slice. New sites: registry:Replication x5 (the class compare, the log line, the assignment and the HA sync-interval check) and whole:Route x6 (rt handed to restoredReplication, openEntryFiles, the cleanup calls and giveBackAfterStart); no file read in this body; only adds a condition before an HA release, no check removed;rev3=census-ruling-rootfs-apps-3;basis=rootfs Plan 3 Tasks 7 and 8: the rootfs admission runs before the claim path and before Acquire on the refreshed row (rootfsWakeRefusal), again in full if a re-read under the lock changed any gate field, and a resident wake re-checks residentRunnable; for a rootfs row a held lease or refused config is an ownership refusal; a rootfs first boot (no good version, fresh) places the empty database under the lease (placeRootfsDB) and uploads it once (syncRootfsPlaceholder), while fresh with a good version is refused as a lost database; declared processes are logged after the wake (rootfsProcessesHook); binary rows unchanged; fix wave 1 and 2 (6189a9db, then the r2 ruling "refuse interrupted init"): a fresh rootfs first boot goes through rootfsFirstBoot (rootfsmarker.go) instead of placeRootfsDB alone: under the lease it reads the lifetime's first-boot marker from the hibernate bucket (present or unreadable refuses, present as errRootfsReplicaMissing), writes it create-only, reads it back (only a read back that finds it confirms it; a write conflict proves nothing), and only then places the database; a warm wake does nothing with the marker (fix wave 1's settleRootfsFirstBoot call and its whole:Route site are gone, no local pending record); adds refusals only, binary rows unchanged;rev3=census-ruling-rootfs-apps-3-release;basis=rootfs Plan 3 Group R, R3: (1) refuses (errWakeUnproven) while another entry's release record of the host is open; (2) a rootfs row with a plan or a pin reads its declared processes before the lease (declaredProcesses(rt, g): the existing staged-manifest read of ExecBackend.Processes, the manifest root's staging wrote, checked against the identity's path and digest) and refuses before Acquire on an error; (3) the staged-identity start runs releaseInWake(ctx, e, rt, id, lease) before startGenExe, under this wake's lease, and a release that did not pass fails the wake; (4) a rootfs row with no plan, no pin and no staged identity is refused, the lease given back, nothing started; (5) a start error whose release is not proven stopped hands the lease to the release record (oweWakeLeaseToRelease) instead of giving it back. New sites +whole:Route x2 (rt to declaredProcesses and releaseInWake); no new file read beyond the existing staged-manifest read; binary rows unchanged;rev3=census-ruling-rootfs-apps-3-workers;basis=rootfs Plan 3 Group W, W1: step 7 no longer calls rootfsProcessesHook (log only); it calls declareRootfsWorkers(e, rt, w), which registers the workers the wake's generation declares as pending and starts nothing (the resident tick starts them once the entry is awake under its lease watch); a worker is never a failure of the wake; the read of the declaration is the existing staged-manifest read (see registerRootfsWorkers); the same read sites in this body, no new read |
| +- `internal/activator/activator.go` `type Service`: authority, task B,C,D,F,J4. Basis: rev3=PROPOSED-seed; existing activator lifecycle and due-wake state plus owned seed exclusion and incarnation-keyed diagnostics; normal refusal and preparation ordering remain authoritative; PROPOSED-plans-2-box-limits adds the idleFor hook field, which only narrows idle windows;rev3=census-ruling-plans-4c-box-throttle;basis=gains the maxRunFor hook field beside idleFor (plans 4c). No read added.;rev3=census-ruling-plans-4d-lapse;basis=gains the disabledFor hook field beside maxRunFor (plans 4d). No read added.;rev3=census-ruling-remote-instance-metrics;basis=gains tenancySeq, hostTenants and hostMixed, in-memory fields for Tenancies; no read added;rev3=census-ruling-region-ha-p1a;basis=the agent as carlos: one more field, markers (markerRetry: an atomic running flag and the last log time) for retryOwedMarkers; no read added; merge of origin/main d7ae1d76: main's fields are kept as main has them (census-ruling-remote-instance-metrics: tenancySeq, hostTenants, hostMixed); this branch's change is the same as above;rev3=census-ruling-rootfs-apps-3;basis=rootfs Plan 3 Tasks 7 and 8: new fields for rootfs admission (rootfsArmed, rootfsSwept), the per-host gate ask and refusal memo, and residency state (lister, backoff, start ceiling, cursor, test seam); no read;rev3=census-ruling-rootfs-apps-3-release;basis=rootfs Plan 3 Group R: one new field, releaseOps (host to the in-memory release record, under a.mu); no read;rev3=census-ruling-rootfs-apps-3-workers;basis=rootfs Plan 3 Group W: one new field, leaseNow (a clock seam for a worker start's headroom against the lease deadline, nil is the real clock); no read |
| +- `internal/edge/cookiescope.go` `Edge.responseModifier`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=J1;basis=root-route;rev3=census-ruling-edge-asset-cache-3;basis=the ModifyResponse hook now also strips any asset cache header or trailer the app set (stripAssetResponseHeaders, stripAssetTrailers: X-Carlos-Asset-Fill, X-Carlos-Asset-Fill-Ack, X-Carlos-Asset-Expires, Carlos-Cache) between the purge channel and the cookie scoping; it deletes response headers only; read sites unchanged (2); no read added |
| +- `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 |
| +- `internal/activator/activator.go` `Service.serve`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-hotfix281;basis=Startup repeats the existing Kind and Hibernate checks; error logging moved to serveWakeError. A request held through startup re-reads its own route's Socket and Addr and can only refuse (wake-timeout 503) when recovery moved them; agent-side, deny-only, no root decision.;rev3=census-ruling-edge-request-records;basis=passes the member request r to begin's new req parameter; no read added;rev3=census-ruling-rootfs-apps-3;basis=rootfs Plan 3 Task 5: the activator-managed test is Route.ActivatorOwned instead of Kind and Hibernate inline, so a resident rootfs instance is the activator's; same deploy-safety for binary rows |
| + |
| +New dispositions, which census-propose wrote and the reviewer checks against the unit's reads and the diff: |
| + |
| +- new `internal/activator/haforward.go:ExecBackend.readHolderView`: reads +registry:Host; written legacy, accepted-legacy, frozen |
| +- new `internal/activator/haforward.go:Service.ForwardTarget`: reads +registry:HA, +registry:Host ×4, +whole:Route ×2; written legacy, accepted-legacy, frozen |
| +- new `internal/activator/haforward.go:Service.answerForwarded`: reads +whole:Route; written legacy, accepted-legacy, frozen |
| +- new `internal/activator/haforward.go:boxSelfRef`: reads +file:Exec; written legacy, accepted-legacy, frozen |
| +- new `internal/activator/haforward.go:forwardedHA`: reads +registry:HA; written legacy, accepted-legacy, frozen |
| +- new `internal/activator/haforward.go:holderReaderFor`: reads +whole:Route ×2; written legacy, accepted-legacy, frozen |
| +- new `internal/activator/haforward.go:noteNoHolder`: reads +whole:Route; written legacy, accepted-legacy, frozen |
| +- new `internal/edge/forwardha.go:Edge.frontForwardHA`: reads +registry:HA, +registry:Host, +whole:Route ×3; written legacy, accepted-legacy, frozen |
| +- reads `internal/activator/activator.go:Service.serveWakeError`: +whole:Route; keeps diagnostic, task C,J4 |
| + |
| +Seal: `7ebc3871ee3c93ff168bfa62d23d6be5a970786c67a9b8aa813e8cc4e39b3d74` → `5b559ba7a42084908cb0fec08083bb2b9b3c9d960036fd10418f81e56304bb64`. |
| + |
| +Overlay: `internal/provision/testdata/plan14-root-reads-region-ha-p1b2.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`. |
diff --git a/docs/superpowers/plans/2026-10-29-region-ha-p1b2-forwarding.md b/docs/superpowers/plans/2026-10-29-region-ha-p1b2-forwarding.md| new file mode 100644 |
| index 000000000..ad4839893 |
| --- /dev/null |
| +++ b/docs/superpowers/plans/2026-10-29-region-ha-p1b2-forwarding.md |
| @@ -0,0 +1,192 @@ |
| +# Region HA P1b-2: forwarding between boxes Implementation Plan |
| + |
| +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. |
| + |
| +**Goal:** A visitor request for a born-HA host that reaches a box which does not hold the host's lease is forwarded to the box that does, over the existing signed backhaul hop, instead of answering 503 "instance is waking elsewhere". |
| + |
| +**Architecture:** |
| +- **Forward at the front (Paul, 2026-10-30, after Astra round 2; stopping rule 2).** The forwarding box decides right after route lookup, before it runs any per-request step (gate, door scope, import and plan gates, guards, request records, rate limits, assets, compression, cache, usage, analytics). A forwarded request therefore has exactly one box doing every per-request step: the holder, as with cross-region backhaul today. |
| +- **The activator** answers one question for the edge: "should this request go to another box, and which?", from a bounded in-memory holder cache, or on a miss from one read of `lock.json`. It also answers forwarded requests it cannot serve with a holder diagnostic. |
| +- **The edge** checks the named box is in its view and forwards over the backhaul hop with its own failure answers. |
| + |
| +**Tech Stack:** Go 1.26, `internal/edge` (backhaul hop, `homeMap`), `internal/activator`, `internal/lease` (`ReadLock`), `internal/hafresh` (owner parsing). |
| + |
| +**Spec:** `docs/superpowers/specs/2026-10-26-region-ha-without-claims-design.md` §6.2, §6.4, §6.6, §4.3 (views), on main. |
| + |
| +**Status: rev 4, final. Astra round 3 NOT READY (2 P1, 2 P2), each P1 closed by a refusal up front; Paul (2026-10-30): apply as rev 4 with no fourth round, then build subagent-driven. Review closed.** |
| + |
| +## Rulings |
| + |
| +- **N-HA8 slicing (2026-10-29):** P1b-2 is forwarding only; see Scope. |
| +- **N-HA10 (Paul, 2026-10-30): forward at the front.** Rounds 1 and 2 both found a per-request step that ran on both boxes (the gate cookie, usage, analytics, asset fills, request records, rate-limit counters). Instead of patching each step, the forward happens before all of them. Cost accepted: on a cache miss, a cold wake on the forwarding box reads `lock.json` twice (one extra GET). |
| + |
| +## Round history |
| + |
| +| Round | File | Verdict | |
| +|---|---|---| |
| +| 1 | `CODEX-PLAN-REGION-HA-P1B2-R1.md` | NOT READY: 4 P1, 3 P2 | |
| +| 2 | `CODEX-PLAN-REGION-HA-P1B2-R2.md` | NOT READY: 1 P1, 3 P2 | |
| +| 3 | `CODEX-PLAN-REGION-HA-P1B2-R3.md` | NOT READY: 2 P1, 2 P2; applied as rev 4 (Paul), no fourth round | |
| + |
| +| Round 3 finding | Disposition in rev 4 | |
| +|---|---| |
| +| r3.1 P1 a headerless 503 from the holder never invalidates the cache | Refusal up front: a forwarded response with status 503 and no `X-Carlos-Holder` drops the entry (`Holder` reported as ""); the next request reads the lock. Task 3 test `TestHolderCacheDroppedOnHeaderless503`; Task 2 test `TestForwardHAHolderLostHost`. | |
| +| r3.2 P1 the view admits a box with another data store | Refusal up front: a box is in view only when its published `data_bucket` is non-empty and equals this box's, and its `secrets_key_fp` equals this box's (both empty counts as equal: a deployment without a key; one empty and one set is a mismatch). Task 1. | |
| +| r3.3 P2 the diagnostic mapping misses the early fence refusal and changes legacy hops | The mapping applies only to HA routes, and to every refusal exit of an HA hop, `maintenanceResponse` included. Legacy hops keep today's answers. Task 3. | |
| +| r3.4 P2 the accounting test does not prove the fixes | Task 2's one-owner test uses an ungated asset route with catching on, and asserts requests and delivered bytes for HEAD, range, conditional and coalesced requests, watched and 404 request records, and observe-mode rate-limit counters. | |
| + |
| +| Finding | Disposition in rev 3 | |
| +|---|---| |
| +| r1.1 P1 gate cookie | Gone by construction: the forwarding box forwards before `gate.Admit`, so the cookie is never stripped there. The holder's gate checks it. | |
| +| r1.2, r2.1 P1, r2.2 P2 accounting (usage, analytics, asset fills, records, rate-limit counters) | Gone by construction (N-HA10): none of those steps runs on the forwarding box for a forwarded request. Task 2's tests assert one owner for each. | |
| +| r1.3 P1 scheduled ticks | Gone by construction: ticks enter the activator through `ServeScheduled`, never through the edge's `ServeHTTP`, so they never meet the front-door decision. Task 3 keeps the witness. | |
| +| r1.4 P1 regional names | Kept: a route reached through a regional name never forwards (`up.regional != regionalNone`); it keeps today's answer. | |
| +| r1.5 P2 transport timeout | Kept: the forward has its own transport cache with a 2 s dial timeout. | |
| +| r1.6 P2, r2.3 P2 refusals of a forwarded request | One mapping (Global Constraints, "Answers"): a held lease of any owner answers `Retry-After: 1` and the holder's reference; every other refusal keeps today's answer and adds `X-Carlos-Holder: none`. | |
| +| r1.7 P2 nil activator | Gone: the edge discovers the interface on the activator it already has; a box with no activator has nothing to discover. | |
| +| r2.4 P2 test commands | Fixed: every named test is in its task's `-run` expression. | |
| + |
| +## Scope |
| + |
| +| Spec | In P1b-2 | Later | |
| +|---|---|---| |
| +| §6.2 decision | Steps 1, 2 and the held-by-owner-in-view outcome of step 4 | §6.3's placement outcome; the terminated outcome needs nothing new (P1b-1's acquire takes over on the holder's next request) | |
| +| §6.3 cold-wake placement | Cold wakes happen where the request lands, as today | Proven reuse and `ChooseRoomiest`: P1b-3 | |
| +| §6.4 forwarded requests | All of it | | |
| +| §6.5 one retry by the first box | | A later slice | |
| +| §6.6 holder cache | All of it, plus a 10 s negative entry | | |
| +| §4.3 views | The view test | Roles, `booting`: P3 | |
| +| §7 duties, §10 latch, §12.4 hairpin | | P1b-3; P3 | |
| + |
| +Visible result on dev: with `hapair-a1` awake on leo, a request through sophie's address is answered by leo's instance (200). |
| + |
| +## Global Constraints |
| + |
| +- **Which requests forward:** a request that reaches the front-door decision with a local route (`ok`), not a verified hop, not a door call, not from a tunnel, whose route is HA (`up.route.HA`), activator-managed (`up.hibernating`), and not reached through a regional name. Nothing else changes. |
| +- **Where:** in `Edge.ServeHTTP`, immediately after the `!ok` block (`internal/edge/edge.go` ~1731-1773) and before the login POST handling (~1774). Nothing between route lookup and that point may move. |
| +- **One hop, ever (§6.4).** The edge's structural rule stays. The front-door decision refuses verified hops before it asks the activator. |
| +- **View (§4.3):** box `ref` is in view only when its edges file is in the current fold, `ref` is not this box, the file's `generation` is no older than `boxchoice.MaxEdgesAge` (15 min) and no more than 1 min in the future, and its `region` and `placement` equal this box's own file's, and its `data_bucket` is non-empty and equals this box's, and its `secrets_key_fp` equals this box's (both empty is equal; one empty is a mismatch). If this box's own file is not in the fold, nothing is in view. |
| +- **Holder cache (§6.6):** host to box reference; at most 50,000 entries; an entry lives at most 1 hour; a negative entry ("not held elsewhere") lives 10 s. No S3 request on a hit. |
| + - Set from a lock read naming an unexpired HA box-format owner (`hafresh.ParseOwner`, `HA` true) whose `Ref` is not this box's, and from a forward's `X-Carlos-Holder: <ref>`. |
| + - Dropped when this box takes the lease, when the named box is not in view, when a forward fails to connect, on `X-Carlos-Holder: none`, and on a forwarded 503 that carries no `X-Carlos-Holder` (the holder's existing no-route refusal). |
| + - One lock read in flight per host (concurrent misses wait for it). |
| +- **Answers.** |
| + - A forward that cannot connect within 2 s: the forwarding box answers 503, `Retry-After: 10`, "instance is waking elsewhere; retry shortly". |
| + - A forwarded request for an HA route that the receiving box cannot serve (legacy routes keep today's answers): if the acquire answers held (any owner, this box's own previous process included): 503, `Retry-After: 1`, `X-Carlos-Holder: <owner's ref>`, "instance is waking elsewhere; retry shortly". Any other refusal, from every refusal exit (`serveWakeError` and the early `maintenanceResponse` fence refusal alike): today's status, `Retry-After` and body, plus `X-Carlos-Holder: none`. |
| + - Everything else is today's answer. |
| +- **S3 budget:** a request for a host held elsewhere costs 0 S3 requests on a hit and one `lock.json` GET on a miss. A cold wake on the forwarding box after a miss costs one GET more than today. The negative entry caps repeated misses at one GET per host per 10 s per box. |
| +- **Copy:** none new. Headers are diagnostics. |
| +- **Cross-compile** darwin and windows; linux/arm64 under 64,000,000 bytes. **Tests:** touched packages only, `-run`, `nice -n 19`. `GOCACHE` default. |
| +- **Census:** agent-run packages. Expected classes: `body` and `sites`. |
| + |
| +## Review Focus |
| + |
| +1. **The holder dies.** The cached holder's dial fails: 503 `Retry-After: 10`, entry dropped, and the next request reads the lock again. Task 2: `TestForwardHADialFailureIs503RetryTen`; Task 3: `TestHolderCacheDroppedOnUnreachable`. |
| +2. **The holder moved.** `X-Carlos-Holder: C` or `none` from B updates A. Task 3: `TestHolderCacheFollowsHolderHeader`. |
| +3. **A forwarded request at a box that is not the holder.** Never forwarded on; answered with the holder. Task 3: `TestHoppedHeldAnswersWithTheHolder`. |
| +4. **A password-gated host and an asset request held elsewhere.** One gate check and one billable request, both on the holder. Task 2: `TestFrontForwardRunsNoLocalStep`. |
| +5. **A burst of requests for a cold host.** One lock read, not one per request. Task 3: `TestForwardTargetSingleFlight`. |
| + |
| +--- |
| + |
| +Tasks 2 and 3 are **[own review]** (stopping rule 3). Task 5 is the dev drill and needs Paul's go. |
| + |
| +### Task 1: The edge's view of a box |
| + |
| +**Files:** Modify `internal/edge/homemap.go`; create `internal/edge/holderview.go`; test `internal/edge/holderview_test.go`. |
| + |
| +**Interfaces:** |
| +- Produces: |
| + - `edgesFileView` gains `Generation string \`json:"generation"\``, `DataBucket string \`json:"data_bucket"\`` and `SecretsKeyFP string \`json:"secrets_key_fp"\`` (the writer's names, `internal/host/edgesfile.go:284, 336`; `internal/edgesfile/snapshot.go:48, 66, 86`). |
| + - `func (m *homeMap) boxInView(ref string, now time.Time) (dial string, ok bool)`: the View rule. `dial` is `edgesfile.Reader.Dial` for that file with this box's own file as `Self` and this edge's `privateDial`, as `foldHomes` builds its reader (`homemap.go:796`). |
| + - `func HopVerified(r *http.Request) bool`: exported `hopVerified(r.Context())`. |
| + |
| +- [ ] **Step 1: Write the failing tests:** `TestHolderViewRules` (own file `{Box:"a", Region:"ie", Placement:"p", Generation:now}`; peer `b` same region/placement at now-1m in view with its EIP; now-16m out; now+2m out; region "uk" out; placement "q" out; self out; unknown out; own file absent: all out; peer `data_bucket` empty out; peer bucket differs out; `secrets_key_fp` differs out; peer empty and own set out; both empty in), `TestHolderViewDialsPrivateWithRegionHA`, `TestHopVerifiedExported`. |
| +- [ ] **Step 2: Run** `nice -n 19 go test ./internal/edge -run 'TestHolderView|TestHopVerifiedExported' -count=1`. Expected: FAIL. |
| +- [ ] **Step 3: Implement.** |
| +- [ ] **Step 4: Run** the Step 2 command. Expected: PASS. |
| +- [ ] **Step 5: Commit** `region-ha p1b-2: the edge's view of a box`. |
| + |
| +### Task 2: The front-door forward in the edge [own review] |
| + |
| +**Files:** Create `internal/edge/forwardha.go`; modify `internal/edge/edge.go` (one call at the insertion point); test `internal/edge/forwardha_test.go` (two-edge scene from `backhaul_e2e_test.go`). |
| + |
| +**Interfaces:** |
| +- Consumes: `boxInView` (Task 1); the hop signing and admission `backhaulTo` uses (`edge.go:3398-3445`, `backhaulProxy` `:3589`). |
| +- Produces: |
| + - `type HAForwarder interface { ForwardTarget(ctx context.Context, rt registry.Route) string; NoteForward(host string, res ForwardResult) }`. The edge finds it with a type assertion on its `Activator`; absent, nothing forwards. |
| + - `type ForwardOutcome int` (`ForwardNotInView`, `ForwardUnreachable`, `ForwardDone`); `type ForwardResult struct { Outcome ForwardOutcome; Status int; Holder string }` (`Status` is the upstream's status; `Holder` is its `X-Carlos-Holder`, "" when absent). |
| + - `func (e *Edge) frontForwardHA(w http.ResponseWriter, r *http.Request, host string, up upstream, hopped, isDoor bool) bool`: at the insertion point. False (serve here) unless every Global Constraints condition holds and `ForwardTarget` names a box. Then `forwardHA`, `NoteForward`, and true unless the outcome is `ForwardNotInView` (then false: serve here). |
| + - `func (e *Edge) forwardHA(w http.ResponseWriter, r *http.Request, host, ref string) ForwardResult`: `boxInView` false or no mesh key: writes nothing, `ForwardNotInView`. Otherwise signs the hop for `host` and proxies through `backhaulAdmit` over its own transport cache (`forwardDialTimeout = 2 * time.Second`, a `forwardDial` seam for tests); `backhaulTo`'s 5 s transports are untouched. Connect failure: the 503 above, `MarkAnswered`, `ForwardUnreachable`. Otherwise the response is relayed as is: `ForwardDone` with `Holder` from `ModifyResponse`. |
| + |
| +- [ ] **Step 1: Write the failing tests** (annie forwards to betty, both "ie", same placement; a fake `HAForwarder` on annie naming "betty"): |
| + - `TestFrontForwardReachesTheHolder`: 200 with betty's body; betty saw a verified hop. |
| + - `TestFrontForwardRunsNoLocalStep`: (a) a gated HA route on both edges: a visitor with a valid gate cookie at annie gets betty's 200; without one, betty's login page. (b) An ungated HA route with asset catching on: a GET, a HEAD, a range request, a conditional request (304) and two coalesced concurrent GETs for one asset path. For each, annie runs no asset fill and records nothing (usage requests and bytes, analytics, request records); betty records exactly one request each with the bytes the client received. (c) A watched guard match and a 404: one Match record and one not-found record, both on betty. (d) Observe-mode rate limiting: betty's counter moves by one per request, annie's not at all. |
| + - `TestForwardHAHolderLostHost`: betty stays in view but no longer serves the host; annie forwards, betty answers its existing no-route 503 (`Retry-After: 2`, no `X-Carlos-Holder`); `NoteForward` gets `{ForwardDone, ""}` with status 503. |
| + - `TestFrontForwardSkips`: no forward (the fake is not asked) for a verified hop, a door call, a regional-name route, a non-HA route, a non-activator route, and an activator without the interface. |
| + - `TestForwardHANotInView`: ref "carol" with no file → `ForwardNotInView`; annie serves locally. |
| + - `TestForwardHADialFailureIs503RetryTen`: a stalling `forwardDial` → 503, `Retry-After: 10`, the body, `ForwardUnreachable` after 2 s; a later `backhaulTo` to the same address still uses its 5 s transport (both call orders). |
| + - `TestForwardHAReadsHolderHeader`: betty's 503 with `X-Carlos-Holder: carol` reaches the client; `NoteForward` gets `{ForwardDone, "carol"}`; with `none`, `"none"`. |
| + - `TestForwardHAUpgradeSwitchesProtocols`: a WebSocket upgrade gets 101 and echoes one message. |
| +- [ ] **Step 2: Run** `nice -n 19 go test ./internal/edge -run 'TestFrontForward|TestForwardHA' -count=1`. Expected: FAIL. |
| +- [ ] **Step 3: Implement.** Share the sign-admit-proxy code with `backhaulTo` through one unexported helper taking the transport, error answer and response hook as parameters. |
| +- [ ] **Step 4: Run** the Step 2 command and `nice -n 19 go test ./internal/edge -run 'Backhaul|Hop|Home|Regional|Gate' -count=1`. Expected: PASS. |
| +- [ ] **Step 5: Commit** `region-ha p1b-2: the edge forwards an HA host's request at the front door`. |
| + |
| +### Task 3: The activator's answer and its holder cache [own review] |
| + |
| +**Files:** Create `internal/activator/hacache.go`, `internal/activator/haforward.go`; modify `internal/activator/activator.go` (`serveWakeError`, ~6026-6070); test `internal/activator/haforward_test.go`. |
| + |
| +**Interfaces:** |
| +- Consumes: `edge.HAForwarder`, `edge.ForwardResult`, `edge.HopVerified`; `lease.ReadLock` (`internal/lease/ha.go:169`); `hafresh.ParseOwner`; `lease.CurrentSelf().Ref`. |
| +- Produces: |
| + - `func (a *Service) ForwardTarget(ctx context.Context, rt registry.Route) string`: "" when `!rt.HA`, or the host is awake or waking here (the live-entry check `begin` makes first). A positive cache hit: its ref. A negative hit: "". A miss: one `ReadLock` (single-flight per host); an unexpired HA owner with another `Ref` sets the entry and returns it; anything else sets the 10 s negative entry and returns "". A read error returns "" and caches nothing. |
| + - `func (a *Service) NoteForward(host string, res edge.ForwardResult)`: `ForwardUnreachable`, `ForwardNotInView`, `Holder "none"`, and `Status` 503 with `Holder` "" drop the entry; a `Holder` ref sets it. |
| + - `var _ edge.HAForwarder = (*Service)(nil)`. |
| + - `holderCache` with `get(host) (ref string, positive, found bool)`, `set`, `setNegative`, `drop`; 50,000 entries (oldest evicted), 1 h and 10 s lifetimes, `now` seam. |
| + - A successful acquire drops the host's entry. |
| + - For an HA route (`rt.HA`) and a request with `edge.HopVerified(r)`, at every refusal exit (`serveWakeError` and the early fence refusal at `activator.go:~5966`): `errLeaseHeld` → 503, `Retry-After: 1`, `X-Carlos-Holder: <ref of errLeaseHeld.holder>`, the existing body; every other refusal → today's answer plus `X-Carlos-Holder: none`. Cancellation keeps today's behaviour. Legacy routes are unchanged. |
| + |
| +- [ ] **Step 1: Write the failing tests** (HA lease fakes as in `hatakeover_test.go`, a fake store counting GETs): |
| + - `TestForwardTargetNamesTheHolder`: lock held by `box/v1;ref=b;iid=i-b;pid=7;ha=1`, unexpired → "b", one GET; again → "b", no GET. |
| + - `TestForwardTargetServesHere`: awake here → ""; a release marker → "" and a negative entry (a second call within 10 s makes no GET; at 11 s one GET); a legacy route → "" with no GET. |
| + - `TestForwardTargetSingleFlight`: 20 concurrent misses → one GET. |
| + - `TestHolderCacheDroppedOnUnreachable`, `TestHolderCacheFollowsHolderHeader` ("c" sets, "none" drops), `TestHolderCacheBounds` (50,001 sets keep 50,000; 61 min reads absent), `TestTakingTheLeaseDropsTheEntry`. |
| + - `TestHoppedHeldAnswersWithTheHolder`: a verified hop, held by "b" → 503, `Retry-After: 1`, `X-Carlos-Holder: b`; held by this box's own ref (previous process) → the same with its own ref. |
| + - `TestHoppedOtherRefusalsSayNone`: an HA verified hop with a config refusal, a lease refusal, a wake timeout and the early fence refusal → today's status and `Retry-After`, plus `X-Carlos-Holder: none`. |
| + - `TestLegacyHopUnchanged`: a legacy verified hop held elsewhere → today's 503 and `Retry-After`, no `X-Carlos-Holder`. |
| + - `TestHolderCacheDroppedOnHeaderless503`: `NoteForward` with `{ForwardDone, 503, ""}` drops the entry; `{ForwardDone, 200, ""}` keeps it. |
| + - `TestScheduledTickNeverForwards`: `ServeScheduled` for a host held by "b" → today's answer; `ForwardTarget` not called. |
| +- [ ] **Step 2: Run** `nice -n 19 go test ./internal/activator -run 'TestForwardTarget|TestHolderCache|TestTakingTheLeaseDrops|TestHopped|TestScheduledTickNeverForwards|TestLegacyHopUnchanged' -count=1`. Expected: FAIL. |
| +- [ ] **Step 3: Implement.** Replace the "mesh seam" comment at `activator.go:~6013` with one line pointing at `haforward.go`. |
| +- [ ] **Step 4: Run** the Step 2 command and `nice -n 19 go test ./internal/activator -run 'HA|SameBox|Takeover|Lease' -count=1`. Expected: PASS. |
| +- [ ] **Step 5: Commit** `region-ha p1b-2: the activator names a holder to forward to`. |
| + |
| +### Task 4: Wiring and builds |
| + |
| +**Files:** test `internal/host/` (the nearest agent-wiring test). |
| + |
| +- [ ] **Step 1: Write the test** `TestAgentActivatorForwards`: the activator the agent hands the edge (`agent.go:724`, `act = svc`) satisfies `edge.HAForwarder`; with no activator configured, the edge gets none and forwards nothing. |
| +- [ ] **Step 2: Run** it, then the three builds and the linux/arm64 size. Expected: PASS, under 64,000,000 bytes. |
| +- [ ] **Step 3: Commit** `region-ha p1b-2: wiring check`. |
| + |
| +### Task 5: Dev drill. Needs Paul's go before anything touches dev. |
| + |
| +Release dev-only as the README and the roll-order rule say. Log UTC times. |
| + |
| +- [ ] **Step 0: Pre-check the view.** leo's and sophie's edges files carry the same non-empty `data_bucket` and the same `secrets_key_fp`. In mid-October leo had no `CARLOS_SECRETS_KEY` while sophie did; if they still differ, copying the dev secrets key to leo as dennis got it (2026-10-15, SSM path) needs Paul's go, and forwarding stays refused until then. |
| +- [ ] **Step 1: Forward.** `hapair-a1` awake on leo; 20 requests through sophie's address. Expected: 20 × 200 from leo's instance; sophie reads `lock.json` at most once. |
| +- [ ] **Step 2: One owner.** Leo's usage for the 20 requests counts 20; sophie's counts 0. |
| +- [ ] **Step 3: Holder dies.** `systemctl kill -s KILL carlos-edge` on leo, probes through sophie every 0.5 s. Record: the 503 `Retry-After: 10` window (the unit restarts in about 1 s), and when 200s resume after leo's same-box re-take (P1a waits for its lease to expire). |
| +- [ ] **Step 4: Report** on amadan #421. |
| + |
| +## Census |
| + |
| +Agent-run changes only: `make census-card`, CLAIMS, `make census-propose`, cross-model reviewer. If 9B8 reports a changed digest, add a re-pin layer as `fresh_box_446_census_test.go` did. |
| + |
| +## Spec gaps and follow-ups |
| + |
| +- §6.3 placement and the over-capacity alert: P1b-3. §6.5's retry: later. |
| +- **Regional names** keep today's answer on a box that is not the holder; same-region forwarding for them is a later slice. |
| +- **Cross-region requests** for an HA host backhaul to the box the fold elects as home. If it is not the holder, the hop is answered 503 `Retry-After: 1` with `X-Carlos-Holder` and not forwarded on: no worse than today. A far edge using the holder is the §6.5 slice. |
| +- **Roles, `booting`, the serving latch, the lifecycle hook, hairpin:** P3. |
diff --git a/docs/superpowers/plans/CODEX-PLAN-REGION-HA-P1B2-BRIEF-1.md b/docs/superpowers/plans/CODEX-PLAN-REGION-HA-P1B2-BRIEF-1.md| new file mode 100644 |
| index 000000000..5c06ef225 |
| --- /dev/null |
| +++ b/docs/superpowers/plans/CODEX-PLAN-REGION-HA-P1B2-BRIEF-1.md |
| @@ -0,0 +1,41 @@ |
| +# Review brief: Region HA P1b-2 plan (forwarding between boxes), round 1 of 3 |
| + |
| +Repo carlos/platform, branch `region-ha-p1b2-forwarding`, the commit that adds this brief. |
| +Under review: `docs/superpowers/plans/2026-10-29-region-ha-p1b2-forwarding.md`. |
| +Authorities: `docs/superpowers/specs/2026-10-26-region-ha-without-claims-design.md` (§6, §4.3; rulings N-HA8, N-HA9), P1a and P1b-1 |
| +as merged on main, and the code on this branch. Do not review against unmerged branches. |
| + |
| +You are an independent reviewer. Read the plan, then the code it names, and check every claim against that code. |
| + |
| +## Fixed: do not re-argue |
| + |
| +- The slicing in the plan's "Scope" table (Paul, 2026-10-29: pick up region HA, small slices). Report only mechanisms in this slice that |
| + fail, not the absence of deferred pieces, unless a deferred piece makes this slice unsafe. |
| +- N-HA9 and the lease rules from P1a/P1b-1 are unchanged by this slice. |
| + |
| +## What to check |
| + |
| +1. **Single writer and loops.** Can forwarding ever cause a second wake, a wake on a box that should not wake, or a forwarding loop? |
| + Check the activator's decision order against `Service.serve`/`begin` (`internal/activator/activator.go` ~5943-6070), the edge's one-hop |
| + rule (`internal/edge/homemap.go:58-63`, `edge.go:3375-3402`) and how a verified hop reaches the activator. |
| +2. **The view test.** Is `boxInView` sound given how `homeMap` folds files (`homemap.go:440-530`, `:783-800`) and the writer's |
| + `generation` (`internal/edgesfile/snapshot.go:86`)? Can a box out of region, stale, or self be chosen? |
| +3. **The forward.** Does sharing `backhaulTo`'s sign/admit/proxy path (`edge.go:3398-3445`, `:3589-3636`) with a 2 s connect timeout, |
| + a 503 `Retry-After: 10` on connect failure, and a `ModifyResponse` reading `X-Carlos-Holder` work without changing `backhaulTo`'s own |
| + behaviour? WebSocket upgrades through it? |
| +4. **The holder cache.** Are its set/drop rules enough to stop a stale entry from black-holing a host? Is its bound and TTL right? |
| +5. **S3 budget.** Does a cache hit really skip the lock GET, and a miss cost at most today's one GET? |
| +6. **Tests and the drill.** Do the named tests prove the claims? Is Task 5 runnable on dev (pool `hapair` on leo and sophie)? |
| + |
| +## Severity |
| + |
| +- **P1**: unsafe, would not compile, a test fails, or it would not work. Blocks merge. |
| +- **P2**: wrong or missing. Fixed without reopening this review. |
| +- **P3**: clarity or polish. Follow-up list. |
| + |
| +A P1 states its failure scenario and the evidence (file:line). Do not raise a P2 to P1 to keep the review open. |
| + |
| +## Output |
| + |
| +Findings ranked P1, P2, P3, each with the task, problem, evidence (file:line), failure scenario, fix and fault family. End with exactly one |
| +verdict: READY, READY AFTER FIXES, or NOT READY. Do not edit files, spawn subagents of your own, or run full suites. |
diff --git a/docs/superpowers/plans/CODEX-PLAN-REGION-HA-P1B2-BRIEF-2.md b/docs/superpowers/plans/CODEX-PLAN-REGION-HA-P1B2-BRIEF-2.md| new file mode 100644 |
| index 000000000..eacdcfe5c |
| --- /dev/null |
| +++ b/docs/superpowers/plans/CODEX-PLAN-REGION-HA-P1B2-BRIEF-2.md |
| @@ -0,0 +1,50 @@ |
| +# Review brief: Region HA P1b-2 plan (forwarding between boxes), round 2 of 3 |
| + |
| +Repo carlos/platform, branch `region-ha-p1b2-forwarding`, the commit that adds this brief (rev 2). |
| +Under review: `docs/superpowers/plans/2026-10-29-region-ha-p1b2-forwarding.md`. |
| +Authorities: `docs/superpowers/specs/2026-10-26-region-ha-without-claims-design.md` (§6, §4.3; rulings N-HA8, N-HA9), P1a and P1b-1 |
| +as merged on main, and the code on this branch. Do not review against unmerged branches. |
| + |
| +You are an independent reviewer. Read the plan, then the code it names, and check every claim against that code. |
| + |
| +## Fixed: do not re-argue |
| + |
| +- The slicing in the plan's "Scope" table (Paul, 2026-10-29: pick up region HA, small slices). Report only mechanisms in this slice that |
| + fail, not the absence of deferred pieces, unless a deferred piece makes this slice unsafe. |
| +- N-HA9 and the lease rules from P1a/P1b-1 are unchanged by this slice. |
| + |
| +## What to check |
| + |
| +1. **Single writer and loops.** Can forwarding ever cause a second wake, a wake on a box that should not wake, or a forwarding loop? |
| + Check the activator's decision order against `Service.serve`/`begin` (`internal/activator/activator.go` ~5943-6070), the edge's one-hop |
| + rule (`internal/edge/homemap.go:58-63`, `edge.go:3375-3402`) and how a verified hop reaches the activator. |
| +2. **The view test.** Is `boxInView` sound given how `homeMap` folds files (`homemap.go:440-530`, `:783-800`) and the writer's |
| + `generation` (`internal/edgesfile/snapshot.go:86`)? Can a box out of region, stale, or self be chosen? |
| +3. **The forward.** Does sharing `backhaulTo`'s sign/admit/proxy path (`edge.go:3398-3445`, `:3589-3636`) with a 2 s connect timeout, |
| + a 503 `Retry-After: 10` on connect failure, and a `ModifyResponse` reading `X-Carlos-Holder` work without changing `backhaulTo`'s own |
| + behaviour? WebSocket upgrades through it? |
| +4. **The holder cache.** Are its set/drop rules enough to stop a stale entry from black-holing a host? Is its bound and TTL right? |
| +5. **S3 budget.** Does a cache hit really skip the lock GET, and a miss cost at most today's one GET? |
| +6. **Tests and the drill.** Do the named tests prove the claims? Is Task 5 runnable on dev (pool `hapair` on leo and sophie)? |
| + |
| +## Round 2 |
| + |
| +Earlier round: `docs/superpowers/plans/CODEX-PLAN-REGION-HA-P1B2-R1.md` (NOT READY: 4 P1, 3 P2). The plan's "Round 1 dispositions" |
| +table says how each was handled; r1.4 is answered by refusing regional names up front (no production region is HA). First give one line |
| +per P1 and P2 from round 1: resolved, partly, or not. Carry every unresolved finding forward at its severity, then add new findings, in |
| +particular any other edge path that runs once per request on BOTH boxes now that both serve the route (the class r1.1-r1.4 came from): |
| +look for every observer, gate, guard, rate limit, cache, asset or analytics step between route lookup and the activator in |
| +`internal/edge/edge.go` ServeHTTP and say whether a forwarded request double-runs it harmfully. |
| + |
| +## Severity |
| + |
| +- **P1**: unsafe, would not compile, a test fails, or it would not work. Blocks merge. |
| +- **P2**: wrong or missing. Fixed without reopening this review. |
| +- **P3**: clarity or polish. Follow-up list. |
| + |
| +A P1 states its failure scenario and the evidence (file:line). Do not raise a P2 to P1 to keep the review open. |
| + |
| +## Output |
| + |
| +Findings ranked P1, P2, P3, each with the task, problem, evidence (file:line), failure scenario, fix and fault family. End with exactly one |
| +verdict: READY, READY AFTER FIXES, or NOT READY. Do not edit files, spawn subagents of your own, or run full suites. |
diff --git a/docs/superpowers/plans/CODEX-PLAN-REGION-HA-P1B2-BRIEF-3.md b/docs/superpowers/plans/CODEX-PLAN-REGION-HA-P1B2-BRIEF-3.md| new file mode 100644 |
| index 000000000..018a2559e |
| --- /dev/null |
| +++ b/docs/superpowers/plans/CODEX-PLAN-REGION-HA-P1B2-BRIEF-3.md |
| @@ -0,0 +1,53 @@ |
| +# Review brief: Region HA P1b-2 plan (forwarding between boxes), round 3 of 3 (final) |
| + |
| +Repo carlos/platform, branch `region-ha-p1b2-forwarding`, the commit that adds this brief (rev 3). |
| +Under review: `docs/superpowers/plans/2026-10-29-region-ha-p1b2-forwarding.md`. |
| +Authorities: `docs/superpowers/specs/2026-10-26-region-ha-without-claims-design.md` (§6, §4.3; rulings N-HA8, N-HA9), P1a and P1b-1 |
| +as merged on main, and the code on this branch. Do not review against unmerged branches. |
| + |
| +You are an independent reviewer. Read the plan, then the code it names, and check every claim against that code. |
| + |
| +## Fixed: do not re-argue |
| + |
| +- The slicing in the plan's "Scope" table (Paul, 2026-10-29: pick up region HA, small slices). Report only mechanisms in this slice that |
| + fail, not the absence of deferred pieces, unless a deferred piece makes this slice unsafe. |
| +- N-HA9 and the lease rules from P1a/P1b-1 are unchanged by this slice. |
| + |
| +## What to check |
| + |
| +1. **Single writer and loops.** Can forwarding ever cause a second wake, a wake on a box that should not wake, or a forwarding loop? |
| + Check the activator's decision order against `Service.serve`/`begin` (`internal/activator/activator.go` ~5943-6070), the edge's one-hop |
| + rule (`internal/edge/homemap.go:58-63`, `edge.go:3375-3402`) and how a verified hop reaches the activator. |
| +2. **The view test.** Is `boxInView` sound given how `homeMap` folds files (`homemap.go:440-530`, `:783-800`) and the writer's |
| + `generation` (`internal/edgesfile/snapshot.go:86`)? Can a box out of region, stale, or self be chosen? |
| +3. **The forward.** Does sharing `backhaulTo`'s sign/admit/proxy path (`edge.go:3398-3445`, `:3589-3636`) with a 2 s connect timeout, |
| + a 503 `Retry-After: 10` on connect failure, and a `ModifyResponse` reading `X-Carlos-Holder` work without changing `backhaulTo`'s own |
| + behaviour? WebSocket upgrades through it? |
| +4. **The holder cache.** Are its set/drop rules enough to stop a stale entry from black-holing a host? Is its bound and TTL right? |
| +5. **S3 budget.** Does a cache hit really skip the lock GET, and a miss cost at most today's one GET? |
| +6. **Tests and the drill.** Do the named tests prove the claims? Is Task 5 runnable on dev (pool `hapair` on leo and sophie)? |
| + |
| +## Round 3 (final) |
| + |
| +Earlier rounds: `CODEX-PLAN-REGION-HA-P1B2-R1.md` (NOT READY: 4 P1, 3 P2) and `CODEX-PLAN-REGION-HA-P1B2-R2.md` (NOT READY: 1 P1, 3 P2). |
| +After round 2, stopping rule 2 applied to the accounting fault family and Paul ruled N-HA10 (in the plan): forward at the front, right |
| +after route lookup and before every per-request step. N-HA10 is fixed: do not argue for the rev 2 design. Check that the front-door |
| +placement really runs no per-request step on the forwarding box (walk `Edge.ServeHTTP` from the top to the insertion point and list |
| +everything that has already run), and that nothing the holder needs is lost by forwarding that early. |
| + |
| +First give one line per P1 and P2 from round 2: resolved, partly, or not. Carry every unresolved finding forward at its severity, then add |
| +new findings. This is round 3: a NOT READY also says whether the P1s share one cause, and whether refusing the case up front or cutting |
| +the feature would remove them. |
| + |
| +## Severity |
| + |
| +- **P1**: unsafe, would not compile, a test fails, or it would not work. Blocks merge. |
| +- **P2**: wrong or missing. Fixed without reopening this review. |
| +- **P3**: clarity or polish. Follow-up list. |
| + |
| +A P1 states its failure scenario and the evidence (file:line). Do not raise a P2 to P1 to keep the review open. |
| + |
| +## Output |
| + |
| +Findings ranked P1, P2, P3, each with the task, problem, evidence (file:line), failure scenario, fix and fault family. End with exactly one |
| +verdict: READY, READY AFTER FIXES, or NOT READY. Do not edit files, spawn subagents of your own, or run full suites. |
diff --git a/docs/superpowers/plans/CODEX-PLAN-REGION-HA-P1B2-R1.md b/docs/superpowers/plans/CODEX-PLAN-REGION-HA-P1B2-R1.md| new file mode 100644 |
| index 000000000..0e2545194 |
| --- /dev/null |
| +++ b/docs/superpowers/plans/CODEX-PLAN-REGION-HA-P1B2-R1.md |
| @@ -0,0 +1,47 @@ |
| +Reviewed round 1 at `2a6a483508a3e5bb0c0edbf5fc4d8e1865614d04`. No files changed, subagents spawned, or tests run. |
| + |
| +1. **P1 — Tasks 2–3: Forwarding breaks password-protected hosts.** |
| + **Evidence:** The proposed insertion is after password admission ([plan:118](docs/superpowers/plans/2026-10-29-region-ha-p1b2-forwarding.md:118)). Admission runs at [edge.go:1970](internal/edge/edge.go:1970) and removes the gate cookie at [gate.go:121](internal/gate/gate.go:121). |
| + **Failure scenario:** A visitor presents a valid cookie to A. A strips it, then forwards to holder B. B runs its gate without the cookie and returns 401. Logging in again repeats this indefinitely. WebSocket handshakes fail too. |
| + **Fix:** Preserve the cookie privately for the outbound mesh request so B can validate it, while still stripping it before the app. Add a two-edge test through both actual gate paths. |
| + **Fault family:** Authentication evidence survives forwarding. |
| + |
| +2. **P1 — Tasks 2–3: Every forwarded request is billed twice.** |
| + **Evidence:** The activator runs underneath the usage observer. Both A and B execute [edge.go:1902](internal/edge/edge.go:1902); `UsageMeter.Record` adds requests and bytes unconditionally ([usagemeter.go:37](internal/edge/usagemeter.go:37)). Its hop counters are subsets, not deductions. |
| + **Failure scenario:** A forwards one response from B. Both boxes record one billable request and its response bytes. HTML responses also reach both analytics observers. Existing backhaul avoids this because its sending edge has no local route; this slice gives both edges one. |
| + **Fix:** Define which edge owns accounting and suppress the duplicate usage and analytics observation. Cover successful forwarding, forwarding failures, and locally served cache hits with aggregate-counter assertions. |
| + **Fault family:** One request has one accounting owner. |
| + |
| +3. **P1 — Task 3: The forwarding decision also forwards scheduled ticks.** |
| + **Evidence:** `ServeScheduled` calls the same `serve` function with `stamp=false` ([activator.go:5940](internal/activator/activator.go:5940)). The planned decision checks HA and the forwarder, with no scheduled-delivery exclusion ([plan:127](docs/superpowers/plans/2026-10-29-region-ha-p1b2-forwarding.md:127)). Scheduled-token replacement happens inside the local proxy wrapper ([activator.go:5930](internal/activator/activator.go:5930)), which forwarding bypasses. |
| + **Failure scenario:** A scheduled tick on A encounters cached holder B. It leaves through B’s public edge with A’s potentially missing or stale token. With a valid token, B treats it as visitor activity and resets the idle clock. A recurring schedule present on both boxes can now deliver through both runners. |
| + **Fix:** Restrict this slice’s forwarding to visitor requests; preserve `ServeScheduled`’s existing local behavior until duties are implemented. Test that scheduled delivery never calls the forwarder. |
| + **Fault family:** Scheduled delivery stays local and activity-invisible. |
| + |
| +4. **P1 — Tasks 2–3: Regional custom domains reject the new forward.** |
| + **Evidence:** Regional aliases retain the target route, including HA ([regional.go:140](internal/edge/regional.go:140)), but `regionalGate` rejects every verified hop ([regional.go:76](internal/edge/regional.go:76)), before the activator. HA instances remain eligible regional targets ([regionaltarget.go:17](internal/release/regionaltarget.go:17)). |
| + **Failure scenario:** A and B serve an HA instance behind a regional domain; B holds its lease. A forwards the domain’s request as required. B rejects it with 503 despite being the holder in the correct region. The response has no holder update, so A retains B and repeats the failure. |
| + **Fix:** Specify how same-region HA forwarding passes this boundary while preserving cross-region refusal. Add regional apex and wildcard tests through two edges, including a cross-region negative case. |
| + **Fault family:** Regional isolation permits legitimate same-region forwarding. |
| + |
| +5. **P2 — Task 2: The transport-sharing instructions omit timeout isolation.** |
| + **Evidence:** The plan requires the same transport with a two-second connect timeout ([plan:99](docs/superpowers/plans/2026-10-29-region-ha-p1b2-forwarding.md:99)). Existing transports use five seconds and are cached solely by address ([edge.go:3510](internal/edge/edge.go:3510)). The prescribed extraction names only error and response hooks. |
| + **Failure scenario:** Reusing an existing transport retains five seconds; changing the shared transport changes ordinary backhaul behavior. A closed-port test fails immediately and proves neither timeout. |
| + **Fix:** Specify separate transport profiles or caches. Test both call orders with a controlled stalled dial, preserving ordinary backhaul’s timeout. |
| + **Fault family:** Transport configuration cannot depend on cache population order. |
| + |
| +6. **P2 — Task 3: Same-box held leases miss the forwarded retry contract.** |
| + **Evidence:** The special forwarded answer applies only when the owner reference differs from this box ([plan:130](docs/superpowers/plans/2026-10-29-region-ha-p1b2-forwarding.md:130)). Otherwise today’s held response uses the remaining lease lifetime ([activator.go:6064](internal/activator/activator.go:6064)). |
| + **Failure scenario:** B restarts with its previous process’s unexpired lease. A forwards to B, which cannot acquire yet. B returns a potentially fifteen-minute retry instead of the required `Retry-After: 1`. |
| + **Fix:** Apply the one-second retry to every forwarded held-lease refusal, including same-box ownership, with the appropriate holder diagnostic. Add that restart case. |
| + **Fault family:** Forwarded refusal semantics are consistent. |
| + |
| +7. **P2 — Task 4: Wiring must handle an absent activator.** |
| + **Evidence:** Task 4 requires `svc.SetForwarder(e)` on every box ([plan:162](docs/superpowers/plans/2026-10-29-region-ha-p1b2-forwarding.md:162)), but `svc` exists only when `cfg != nil` ([agent.go:415](internal/host/agent.go:415)); the ready callback runs outside that condition. |
| + **Failure scenario:** A box without hibernation calls the setter on a nil service and panics unless the new setter explicitly supports nil receivers. |
| + **Fix:** Require `if svc != nil` around the wiring and test both armed and unarmed cases. |
| + **Fault family:** Optional activator wiring preserves startup. |
| + |
| +No P3 findings. |
| + |
| +NOT READY |
| \ No newline at end of file |
diff --git a/docs/superpowers/plans/CODEX-PLAN-REGION-HA-P1B2-R2.md b/docs/superpowers/plans/CODEX-PLAN-REGION-HA-P1B2-R2.md| new file mode 100644 |
| index 000000000..370db4c48 |
| --- /dev/null |
| +++ b/docs/superpowers/plans/CODEX-PLAN-REGION-HA-P1B2-R2.md |
| @@ -0,0 +1,70 @@ |
| +- **r1.1 P1 — Resolved:** capture before gate admission and restore on the outbound hop preserves the visitor’s cookie. |
| +- **r1.2 P1 — Partly:** ordinary forwarding avoids duplicate usage and analytics, but asset fills still produce incorrect billing; request records also remain duplicated. |
| +- **r1.3 P1 — Resolved:** forwarding requires `stamp=true`. |
| +- **r1.4 P1 — Resolved:** regional requests explicitly retain today’s refusal. |
| +- **r1.5 P2 — Resolved:** separate transport caches preserve timeout isolation. |
| +- **r1.6 P2 — Resolved:** the instructions explicitly include same-box held leases. |
| +- **r1.7 P2 — Resolved:** wiring requires `svc != nil`. |
| + |
| +1. **P1 — Tasks 2–3: Holder-owned accounting bills internal asset fills as visitor deliveries.** |
| + |
| + **Evidence:** The plan unconditionally suppresses the forwarding edge’s accounting ([plan:115](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/region-ha-p1b2/docs/superpowers/plans/2026-10-29-region-ha-p1b2-forwarding.md:115)). However, `serveAssetLocal` reaches the activator through `fillFromApp` ([assetcatch.go:318](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/region-ha-p1b2/internal/edge/assetcatch.go:318), `:586`). The fill inherits the original outcome through its context (`:534`, `:627`), but constructs a new GET without the visitor’s Range or conditional headers (`:644`). A buffered visitor receives its eventual answer separately (`:553`). |
| + |
| + **Failure scenario:** A receives a cold-cache `HEAD` for an asset while B holds the lease. A constructs a GET and forwards it to B. B bills one GET and the full asset body. The forwarded marker suppresses A’s accounting, although A delivers no body to the visitor. A conditional request answered with 304 or a range request has the same problem. `TestForwardHABillsOnlyTheHolder` does not exercise this path. |
| + |
| + **Fix:** Distinguish an internal fill from a visitor delivery before assigning accounting ownership. Add two-edge tests asserting aggregate request counts and actual delivered bytes for HEAD, conditional and range requests, plus coalesced fills. |
| + |
| + **Fault family:** **One request has one accounting owner**, continuing r1.2. This family has findings in two consecutive rounds, so stopping rule 2 applies. The choices are an admission refusal for the unsupported case, cutting HA asset catching, or enforcing the delivery-accounting invariant in one place with guard tests. I recommend the invariant and tests; another isolated observer patch is insufficient. |
| + |
| +2. **P2 — Task 2: The forwarding marker leaves request records duplicated.** |
| + |
| + **Evidence:** The plan lists usage, analytics and edge-error emission as the observers to suppress. The same defer also calls `observeRecords` ([edge.go:1909](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/region-ha-p1b2/internal/edge/edge.go:1909)). That function excludes tunnel deliveries, but does not exclude forwarding ([reqrecords.go:57](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/region-ha-p1b2/internal/edge/reqrecords.go:57)). |
| + |
| + **Failure scenario:** One forwarded 404 produces two request counts and two not-found records. A watched guard match produces two Match records. A can also claim knowledge of a wake that happened elsewhere. |
| + |
| + **Fix:** Include request recording in the ownership decision. Assert one aggregate Response/Match for ordinary, watched and 404 forwarding, while retaining A’s record when A answers locally. Also cover observe-mode rate-limit counters: `noteRateLimited` updates usage immediately on both boxes ([ratelimit.go:145](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/region-ha-p1b2/internal/edge/ratelimit.go:145)). |
| + |
| + **Fault family:** One request has one accounting owner. |
| + |
| +3. **P2 — Task 3: Non-held refusals contradict the forwarded-response contract.** |
| + |
| + **Evidence:** Global Constraints require an unservable forwarded request to receive 503, `Retry-After: 1`, and a holder diagnostic ([plan:58](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/region-ha-p1b2/docs/superpowers/plans/2026-10-29-region-ha-p1b2-forwarding.md:58)). Decision step 4 instead preserves today’s answer and adds only `X-Carlos-Holder: none` (`:153`). Today’s config refusal returns 30 seconds; lease refusal returns 10 seconds ([activator.go:6046](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/region-ha-p1b2/internal/activator/activator.go:6046)). |
| + |
| + **Failure scenario:** A forwarded request reaches B, whose acquisition is refused. It receives `Holder: none` with the wrong retry interval and body. |
| + |
| + **Fix:** Specify one response mapping for unservable HA hops, preserving cancellation behavior. Test config refusal, lease refusal and wake timeout. |
| + |
| + **Fault family:** Forwarded refusal semantics are consistent. |
| + |
| +4. **P2 — Task 3: Both prescribed test commands omit two required regression tests.** |
| + |
| + **Evidence:** Neither expression at [plan:169](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/region-ha-p1b2/docs/superpowers/plans/2026-10-29-region-ha-p1b2-forwarding.md:169) or `:171` selects `TestScheduledTickNeverForwards` or `TestRegionalRequestNeverForwards`. |
| + |
| + **Failure scenario:** Both commands pass while the tests protecting r1.3 and r1.4 never run. |
| + |
| + **Fix:** Add both names to the targeted expression. |
| + |
| + **Fault family:** Required regression witnesses execute. |
| + |
| +The remaining request-path audit is: |
| + |
| +| Path between lookup and activator | Effect on forwarding | |
| +|---|---| |
| +| Regional gate; exact-home and lookup-miss branches | Existing hop refusals remain intact. The activator’s additional hop check prevents onward forwarding. | |
| +| Login POST parsing and password gate | Login answers return before forwarding. Admitted visitor requests retain their cookies under the revision. | |
| +| Door ownership and signed door exemption | Rechecking ownership is safe; the shared backhaul path preserves the receiving limiter’s door exemption. | |
| +| Import and plan-disabled gates | Recheck local policy without waking anything. Their refusals return before the activator. | |
| +| Guard checks and request recording | Blocking returns locally; watched matches reach both observers. Duplicate records are finding 2. | |
| +| Upgrade tracking and admission | Both edges can track their own connection leg. The existing HTTP/1.1 proxy and hijackable writer path support upgrades. | |
| +| Plan throttle and instance rate limit | Each edge consults its separate local limiter. Refusals stop forwarding; observe-mode counters need the ownership treatment in finding 2. | |
| +| Local assets and generated fills | Internal request conversion breaks delivery accounting: finding 1. Verified-hop context survives conversion, so it does not open a forwarding loop. | |
| +| Compression and shared response cache | Existing encoding prevents double compression. Local hits return before forwarding; generation-managed forwarded responses lack local generation provenance and are refused storage by `maybeStore`. | |
| +| Usage, analytics and edge errors | Ordinary relayed responses are covered by the proposed marker; locally answered failures remain observable. | |
| + |
| +The view rules use the retained files’ generation timestamps, so carrying a last-good file forward does not refresh its age. The specified region, placement, self-exclusion and reader-specific dial checks are consistent with the existing fold. Cache invalidation permits a later acquire after dial failure or `Holder: none`; an uncontended held-lock miss retains today’s one GET. |
| + |
| +Task 5 is mechanically a dev crash/restart drill. The unit restarts automatically after one second, so two-second probes may miss the dial-failure window. Recovery can still wait for the previous lease’s expiry. Record those times explicitly; no live dev state was checked. |
| + |
| +Reviewed commit `50a843dfa2a3a3ec1c4fedc32ea3ffbedf374bc4`. No files changed, subagents spawned, or Go suites run. No P3 findings. |
| + |
| +NOT READY |
| \ No newline at end of file |
diff --git a/docs/superpowers/plans/CODEX-PLAN-REGION-HA-P1B2-R3.md b/docs/superpowers/plans/CODEX-PLAN-REGION-HA-P1B2-R3.md| new file mode 100644 |
| index 000000000..838fefcde |
| --- /dev/null |
| +++ b/docs/superpowers/plans/CODEX-PLAN-REGION-HA-P1B2-R3.md |
| @@ -0,0 +1,64 @@ |
| +- **r2.1 P1 — Resolved:** forwarding before asset handling preserves the visitor request and puts delivery accounting on the holder. |
| +- **r2.2 P2 — Partly:** placement removes duplicate observers, but the prescribed tests omit watched/404 records and rate-limit counters. |
| +- **r2.3 P2 — Partly:** the response mapping is consistent now, but some activator refusals bypass its proposed implementation. |
| +- **r2.4 P2 — Resolved:** the commands select the named tests; regional exclusions are covered by `TestFrontForwardSkips`. |
| + |
| +1. **P1 — Tasks 2–3: A cached holder’s existing “not served here” answer never invalidates the cache.** |
| + |
| + **Evidence:** [The planned invalidation rules](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/region-ha-p1b2/docs/superpowers/plans/2026-10-29-region-ha-p1b2-forwarding.md:135) drop entries on connection failure, exclusion from view, or `Holder: none`. A verified hop whose route is absent exits through [the lookup-miss branch](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/region-ha-p1b2/internal/edge/edge.go:1731). Its [existing response](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/region-ha-p1b2/internal/edge/homemap.go:1351) is 503, `Retry-After: 2`, without `X-Carlos-Holder`. |
| + |
| + **Failure scenario:** A caches B. B stops serving H and releases its lease, while continuing to publish a fresh edges file for other hosts. A forwards to B, receives that headerless 503, and reports `{ForwardDone, ""}`. Nothing drops the entry. Requests through A continue failing for up to an hour instead of discovering the released lock and waking locally. Removing a route already retires its instance through [the existing activator path](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/region-ha-p1b2/internal/activator/activator.go:5646). |
| + |
| + **Fix:** Preserve the existing no-route response, but carry sufficient response information into the cache decision to invalidate this case. Conservatively dropping the holder on a headerless 503 would suffice. Add a two-edge test where B loses H but remains in view. |
| + |
| + **Fault family:** A stale holder must not prevent rediscovery. |
| + |
| +2. **P1 — Task 1: The view test permits forwarding across different data stores.** |
| + |
| + **Evidence:** [The plan’s view rule](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/region-ha-p1b2/docs/superpowers/plans/2026-10-29-region-ha-p1b2-forwarding.md:60) compares age, region and placement. [Spec §4.3](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/region-ha-p1b2/docs/superpowers/specs/2026-10-26-region-ha-without-claims-design.md:145) also requires the same data bucket and deployment secrets-key fingerprint. Both are [already published](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/region-ha-p1b2/internal/host/edgesfile.go:1030), but the proposed reader gains only `Generation`. |
| + |
| + **Failure scenario:** A retains B as holder while B restarts with a different hibernation bucket. B’s fresh file still matches region and placement, so A forwards. B acquires against [its own configured bucket](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/region-ha-p1b2/internal/activator/hawake.go:318), where H’s lock and data can be absent, and starts H from an empty store rather than A’s authoritative replica. |
| + |
| + **Fix:** Decode and validate the published bucket and fingerprint evidence before accepting a peer. Reject missing or mismatched evidence. Add mismatch tests to `TestHolderViewRules`. |
| + |
| + **Fault family:** Forwarding peers share the authoritative storage and configuration boundary. |
| + |
| +3. **P2 — Task 3: The diagnostic mapping misses early refusals and changes legacy hops.** |
| + |
| + **Evidence:** [Task 3](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/region-ha-p1b2/docs/superpowers/plans/2026-10-29-region-ha-p1b2-forwarding.md:139) changes `serveWakeError` whenever `HopVerified` is true. However, [the initial fence refusal](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/region-ha-p1b2/internal/activator/activator.go:5966) calls `maintenanceResponse` directly. That [response helper](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/region-ha-p1b2/internal/activator/maintenance.go:344) supplies no holder diagnostic. Conversely, the proposed condition lacks an HA check. |
| + |
| + **Failure scenario:** A forwarded HA request refused by the initial fence lacks the promised `Holder: none`, retaining its sender’s stale entry. A legacy held-lease hop receives the new one-second retry despite the HA-only scope. |
| + |
| + **Fix:** Scope the mapping to HA hops and enforce it consistently across activator refusal exits, preserving cancellation behavior. Add fenced-HA and legacy-hop regression cases. |
| + |
| + **Fault family:** Forwarded refusal semantics are consistent. |
| + |
| +4. **P2 — Task 2: The regression test specification does not prove the earlier accounting fixes.** |
| + |
| + **Evidence:** [The proposed test](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/region-ha-p1b2/docs/superpowers/plans/2026-10-29-region-ha-p1b2-forwarding.md:116) specifies a gated route, request counts, and HEAD/range asset requests. [Asset catching explicitly excludes gated routes](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/region-ha-p1b2/internal/edge/assetcatch.go:267). It also omits delivered-byte assertions, conditional responses, coalesced fills, watched/404 records and observe-mode rate-limit counters. |
| + |
| + **Failure scenario:** The test passes without exercising asset catching or detecting duplicate Match records and rate-limit counts. |
| + |
| + **Fix:** Use a separate ungated asset route with catching enabled. Assert aggregate requests and delivered bytes for HEAD, range, conditional and coalesced requests. Add watched/404 record and observe-mode limiter assertions. |
| + |
| + **Fault family:** One request has one accounting owner. |
| + |
| +The `ServeHTTP` audit confirms that, before the insertion point, the forwarding box has already: |
| + |
| +- Split the host and captured GeoIP headers. |
| +- Checked reserved door, steering, tunnel and store-door branches. |
| +- Accepted or rejected the hop and scrubbed internal asset headers. |
| +- Computed GeoIP metadata and attached the forwarding-proof key. |
| +- Resolved the route and evaluated regional, exact-home and lookup-miss branches. |
| + |
| +For a request reaching the new forward, login parsing, policy gates, observers, guards, assets, compression, caching and rate limits have not run. The shared backhaul path preserves Host, cookies and the unread body, carries the client address, and sends the GeoIP result for adoption by the holder. |
| + |
| +Separate transports can preserve the existing five-second backhaul behavior while providing the new two-second dial timeout. The existing HTTP/1.1 proxy path supports WebSocket upgrades. A positive cache hit avoids discovery GETs; a discovery miss costs one GET. The extra acquire GET for a local cold wake is explicitly accepted by N-HA10. |
| + |
| +Task 5 is mechanically runnable as a crash/restart drill: `carlos-edge.service` specifies `Restart=always` and `RestartSec=1`. Live dev configuration was not checked, and the short connection-failure window may escape sampling. |
| + |
| +No P3 findings. Reviewed the requested commit; no files changed, subagents spawned, or tests run. |
| + |
| +The two P1s have separate causes: incomplete peer qualification and incomplete cache invalidation. Rejecting mismatched peers up front removes the first storage hazard. Dropping cached targets on the existing no-route refusal removes the cache failure. Cutting inter-box forwarding removes both exposures. This is round 3 of 3; no fourth round is proposed. |
| + |
| +NOT READY |
| \ No newline at end of file |
diff --git a/docs/superpowers/plans/CODEX-REVIEW-BRIEF-REGION-HA-P1B2-BRANCH-1.md b/docs/superpowers/plans/CODEX-REVIEW-BRIEF-REGION-HA-P1B2-BRANCH-1.md| new file mode 100644 |
| index 000000000..f9684ed52 |
| --- /dev/null |
| +++ b/docs/superpowers/plans/CODEX-REVIEW-BRIEF-REGION-HA-P1B2-BRANCH-1.md |
| @@ -0,0 +1,30 @@ |
| +# Review brief: Region HA P1b-2 branch (forwarding between boxes), round 1 of 3 |
| + |
| +Repo carlos/platform, branch `region-ha-p1b2-forwarding`, commit 0e2cb7e5a7a172a7ebdce725aba2de479306aa48. Under review: the code diff |
| +c01c4d4e..0e2cb7e5 (c01c4d4e is plan rev 4 on main 1fa2a99b), packaged in `/home/paulca/amadan.net/carlos/platform/.claude/worktrees/region-ha-p1b2/.superpowers/sdd/2026-10-29-region-ha-p1b2-forwarding/review-c01c4d4e..0e2cb7e5.diff` (read it first). |
| +Authorities: `docs/superpowers/plans/2026-10-29-region-ha-p1b2-forwarding.md` (rev 4; its review closed at round 3 with Paul's rulings |
| +N-HA8 and N-HA10), the spec `docs/superpowers/specs/2026-10-26-region-ha-without-claims-design.md` (§6, §4.3), and P1a/P1b-1 on main. |
| +The SDD ledger with every task review and the deferred minors: `.superpowers/sdd/2026-10-29-region-ha-p1b2-forwarding/progress.md`. Tasks 2 and 3 had their own Astra reviews; Tasks 1 |
| +and 4 had none (AGENTS.md rule 3): review them in full. |
| + |
| +## Fixed: do not re-argue |
| + |
| +- N-HA10: forward at the front door, before every per-request step. The plan's Scope table (§6.3 placement, §6.5 retry, roles and the latch |
| + are later slices; regional names refused). The census is a later step. |
| + |
| +## What to check |
| + |
| +1. Single writer and loops across the whole branch: can any path wake a host on a box that should not, forward a hop, or loop? |
| +2. The front-door placement: nothing per-request runs on the forwarding box (gate, assets, guards, records, rate limits, usage, analytics). |
| +3. Production wiring end to end: agent -> edge type assertion -> Service.ForwardTarget through SplitBackend -> holder cache -> lease read; |
| + and the holder's answers. A review already caught one production-only gap (SplitBackend); look for any other. |
| +4. The holder cache: bounds, TTLs, single-flight, every set/drop rule; can a stale entry black-hole a host? |
| +5. The deferred minor in the ledger (a dead holder with an unexpired lease costs one GET plus a 2 s dial per request): must it be fixed |
| + before merge? |
| +6. Tests: do they prove the claims, and would they fail without the change? |
| + |
| +## Severity, output |
| + |
| +P1 (unsafe, does not work, a test fails), P2 (wrong or missing; fixed without another round), P3 (follow-up). Each with file:line, failure |
| +scenario, fix and fault family. End with exactly one verdict: READY, READY AFTER FIXES, or NOT READY. Do not edit files, spawn subagents of |
| +your own, or run full suites. |
diff --git a/docs/superpowers/plans/CODEX-REVIEW-REGION-HA-P1B2-BRANCH-1-RECHECK.md b/docs/superpowers/plans/CODEX-REVIEW-REGION-HA-P1B2-BRANCH-1-RECHECK.md| new file mode 100644 |
| index 000000000..069d00ffe |
| --- /dev/null |
| +++ b/docs/superpowers/plans/CODEX-REVIEW-REGION-HA-P1B2-BRANCH-1-RECHECK.md |
| @@ -0,0 +1,9 @@ |
| +**P2 — ADDRESSED.** The complete holder read now runs under a two-second timeout, with deferred cancellation: [haforward.go:130](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/region-ha-p1b2/internal/activator/haforward.go:130). |
| + |
| +Detaching from visitor cancellation introduces no background read goroutine. The bounded context reaches `GetObject` and remains active through body consumption and closure: [legacytake.go:113](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/region-ha-p1b2/internal/lease/legacytake.go:113). On timeout, the result is not cached. Deferred cleanup removes the flight and releases waiters; waiters also retain their own cancellation path: [hacache.go:150](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/region-ha-p1b2/internal/activator/hacache.go:150), [hacache.go:167](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/region-ha-p1b2/internal/activator/hacache.go:167). |
| + |
| +The new witness checks concurrent callers return, nothing is cached, the flight disappears, and a subsequent lookup succeeds: [haforward_test.go:478](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/region-ha-p1b2/internal/activator/haforward_test.go:478). It covers stalled headers; body-stall and cancellation behavior were checked by source inspection. |
| + |
| +No new Critical/Important breakage found in `cc508a8d..9ffce8d7`. `git diff --check` passed. The targeted test could not start because the read-only sandbox rejected Go’s work directory. No files were edited, subagents spawned, or full suites run. |
| + |
| +**All findings addressed: yes** |
| \ No newline at end of file |
diff --git a/docs/superpowers/plans/CODEX-REVIEW-REGION-HA-P1B2-BRANCH-1.md b/docs/superpowers/plans/CODEX-REVIEW-REGION-HA-P1B2-BRANCH-1.md| new file mode 100644 |
| index 000000000..6b2126855 |
| --- /dev/null |
| +++ b/docs/superpowers/plans/CODEX-REVIEW-REGION-HA-P1B2-BRANCH-1.md |
| @@ -0,0 +1,23 @@ |
| +No P1 found. Two findings: |
| + |
| +1. **P2 — Bound the holder lookup’s duration.** Task 3, [haforward.go:120](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/region-ha-p1b2/internal/activator/haforward.go:120). |
| + |
| + `ForwardTarget` passes the visitor’s context directly to `ReadLock`, before entering the activator’s bounded wake path. If the store accepts the connection but stalls its headers or body, the initiating request can wait indefinitely. Concurrent requests for that host join the same unfinished flight ([hacache.go:150](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/region-ha-p1b2/internal/activator/hacache.go:150)). The production HTTP server supplies no request deadline. |
| + |
| + **Fix:** give holder discovery an explicit timeout, covering the complete read. On timeout, cache nothing and release the flight. Add a stalled-read witness proving that the initiator and waiters return, and a subsequent lookup can proceed. |
| + |
| + **Fault family:** bounded request waiting during holder discovery. |
| + |
| +2. **P3 — Keep the dead-holder amplification as a follow-up.** Task 3, [haforward.go:155](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/region-ha-p1b2/internal/activator/haforward.go:155). |
| + |
| + After a failed dial, the entry is dropped. The next request reads the unchanged, unexpired lease and attempts the same dead holder again: one GET plus up to two seconds dialing per sequential request. |
| + |
| + **Disposition:** this need not block merge. It follows the agreed invalidation rules, preserves single-writer safety, and ends when the lease expires or the holder leaves view. A later bounded suspect/backoff state could reduce repeated work while preserving lease fencing. |
| + |
| + **Fault family:** request and storage amplification during holder failure. |
| + |
| +Source inspection found no additional production wiring gap, onward-forward path, or duplicate per-request processing on the forwarding box. The tests contain meaningful witnesses for those claims, including `SplitBackend` discovery. |
| + |
| +Targeted tests could not start: the read-only sandbox rejected creation of Go’s work directory. `git diff --check` passed. No files were edited; no subagents or full suites were run. Census remains the separately scheduled step. |
| + |
| +READY AFTER FIXES |
| \ No newline at end of file |
diff --git a/internal/activator/activator.go b/internal/activator/activator.go| index bfedb62c8..994d6a85d 100644 |
| --- a/internal/activator/activator.go |
| +++ b/internal/activator/activator.go |
| @@ -1268,6 +1268,10 @@ type Service struct { |
| // codepath was touched at all. Single-box v1 drops the field; it re-enters |
| // with the mesh port. |
| + // holders is the region HA holder cache (hacache.go): for a born-HA |
| + // host held by another box, which one, so the edge forwards there. |
| + holders holderCache |
| + |
| // lifeCtx is cancelled by Shutdown: the seam that lets an in-flight worker |
| // spawn be TORN DOWN rather than waited out. See Shutdown for why waiting |
| // is the wrong trade there. |
| @@ -2542,6 +2546,10 @@ func (a *Service) doWake(ctx context.Context, e *actEntry) (*wokenInstance, erro |
| w.steps.mark(a.now(), "checks") |
| *w.stopOutcome = stopObservation{} |
| lease, err := a.backend.Acquire(ctx, rt) |
| + if err == nil { |
| + // This box holds the host now: no holder elsewhere to forward to. |
| + a.holders.drop(host) |
| + } |
| // A row with a runtime that meets a held lease or refused config is |
| // refused, never failed (markOwnershipRefusal); a binary row's answer |
| // is main's. |
| @@ -5967,6 +5975,7 @@ func (a *Service) serve(w http.ResponseWriter, r *http.Request, rt registry.Rout |
| fenced := a.fences[rt.Host] != 0 |
| a.mu.Unlock() |
| if fenced { |
| + a.answerForwarded(w, r, rt, ErrFenced) |
| maintenanceResponse(w, r) |
| return true |
| } |
| @@ -5996,6 +6005,8 @@ func (a *Service) serve(w http.ResponseWriter, r *http.Request, rt registry.Rout |
| // could spoof. |
| r.Header.Del(SidecarHeader) |
| if err := a.BeginSidecarRequest(r.Context(), rt); err != nil { |
| + // A forwarded request's answer says none (haforward.go). |
| + noteNoHolder(w, r, rt, err) |
| if errors.Is(err, ErrFenced) { |
| maintenanceResponse(w, r) |
| return true |
| @@ -6014,11 +6025,8 @@ func (a *Service) serve(w http.ResponseWriter, r *http.Request, rt registry.Rout |
| return true |
| } |
| - // mesh seam: Eleven proxied a member request for a host with no live |
| - // local entry and an HRW owner on another live box to that peer here (one |
| - // hop max, guarded by a forwarded marker); a host with ANY live local |
| - // entry stayed local — placement converges at the next sleep boundary, |
| - // since its state is already in S3. Single-box v1 always wakes locally. |
| + // A born-HA host held by another box was forwarded there by the edge |
| + // before this, on the activator's word (haforward.go). |
| release, err := a.begin(r.Context(), rt, stamp, r) |
| if err != nil { |
| @@ -6030,6 +6038,10 @@ func (a *Service) serve(w http.ResponseWriter, r *http.Request, rt registry.Rout |
| } |
| func (a *Service) serveWakeError(w http.ResponseWriter, r *http.Request, rt registry.Route, err error) bool { |
| + // A forwarded request's answer names the holder (haforward.go). |
| + if a.answerForwarded(w, r, rt, err) { |
| + return true |
| + } |
| var held *errLeaseHeld |
| var refused *errConfigRefused |
| var backoff *errResidentBackoff |
diff --git a/internal/activator/hacache.go b/internal/activator/hacache.go| new file mode 100644 |
| index 000000000..c1b73ded7 |
| --- /dev/null |
| +++ b/internal/activator/hacache.go |
| @@ -0,0 +1,183 @@ |
| +package activator |
| + |
| +import ( |
| + "container/list" |
| + "context" |
| + "sync" |
| + "time" |
| +) |
| + |
| +// The holder cache (region HA P1b-2; spec 2026-10-26 §6.6): for a born-HA |
| +// host this box does not hold, which box does, so the edge can forward a |
| +// visitor's request there without an S3 request on every one. A positive |
| +// entry names the holder; a negative one says "not held elsewhere, serve |
| +// here" and exists only to cap the lock reads of a host that keeps |
| +// missing. The cache is advice, never a lease: every way it can be wrong |
| +// ends in a drop (haforward.go's NoteForward, the acquire in doWake) or, |
| +// at the latest, its lifetime. |
| +const ( |
| + // holderCacheMax bounds the cache; the oldest entry set goes first. |
| + holderCacheMax = 50_000 |
| + // holderPositiveTTL is the longest a named holder is believed without |
| + // a forward's answer confirming it. |
| + holderPositiveTTL = time.Hour |
| + // holderNegativeTTL is how long a miss that found no other holder is |
| + // remembered: one lock read per host per 10 s per box at most. |
| + holderNegativeTTL = 10 * time.Second |
| +) |
| + |
| +// holderCache is host to holder box reference. The zero value is ready; |
| +// now is the clock seam (nil is the real clock). |
| +type holderCache struct { |
| + mu sync.Mutex |
| + now func() time.Time |
| + holders map[string]*list.Element // host -> *holderEntry in order |
| + order list.List // oldest set at the front |
| + flights map[string]*holderFlight // host -> the lock read in flight |
| +} |
| + |
| +type holderEntry struct { |
| + host string |
| + ref string // "" for a negative entry |
| + expires time.Time |
| +} |
| + |
| +// holderFlight is one lock read in flight for a host. stale is set when |
| +// the host's entry is set or dropped while the read runs: the read began |
| +// before that news, so its answer goes to its waiters but is not cached. |
| +type holderFlight struct { |
| + done chan struct{} |
| + ref string |
| + stale bool |
| +} |
| + |
| +func (c *holderCache) clock() time.Time { |
| + if c.now != nil { |
| + return c.now() |
| + } |
| + return time.Now() |
| +} |
| + |
| +// get is host's live entry: its ref and positive true for a holder, |
| +// positive false for a negative entry, found false for none (an expired |
| +// entry is removed). |
| +func (c *holderCache) get(host string) (ref string, positive, found bool) { |
| + c.mu.Lock() |
| + defer c.mu.Unlock() |
| + return c.getLocked(host) |
| +} |
| + |
| +func (c *holderCache) getLocked(host string) (string, bool, bool) { |
| + el := c.holders[host] |
| + if el == nil { |
| + return "", false, false |
| + } |
| + e := el.Value.(*holderEntry) |
| + if !c.clock().Before(e.expires) { |
| + c.removeLocked(el) |
| + return "", false, false |
| + } |
| + return e.ref, e.ref != "", true |
| +} |
| + |
| +// set names ref as host's holder for holderPositiveTTL. An empty ref sets |
| +// nothing. |
| +func (c *holderCache) set(host, ref string) { |
| + if ref == "" { |
| + return |
| + } |
| + c.mu.Lock() |
| + defer c.mu.Unlock() |
| + c.putLocked(host, ref, holderPositiveTTL) |
| +} |
| + |
| +// setNegative remembers for holderNegativeTTL that host is not held |
| +// elsewhere. |
| +func (c *holderCache) setNegative(host string) { |
| + c.mu.Lock() |
| + defer c.mu.Unlock() |
| + c.putLocked(host, "", holderNegativeTTL) |
| +} |
| + |
| +// drop forgets host's entry, and any read in flight for it. |
| +func (c *holderCache) drop(host string) { |
| + c.mu.Lock() |
| + defer c.mu.Unlock() |
| + if el := c.holders[host]; el != nil { |
| + c.removeLocked(el) |
| + } |
| + if f := c.flights[host]; f != nil { |
| + f.stale = true |
| + } |
| +} |
| + |
| +func (c *holderCache) putLocked(host, ref string, ttl time.Duration) { |
| + if f := c.flights[host]; f != nil { |
| + f.stale = true |
| + } |
| + if c.holders == nil { |
| + c.holders = map[string]*list.Element{} |
| + } |
| + expires := c.clock().Add(ttl) |
| + if el := c.holders[host]; el != nil { |
| + e := el.Value.(*holderEntry) |
| + e.ref, e.expires = ref, expires |
| + c.order.MoveToBack(el) |
| + return |
| + } |
| + for len(c.holders) >= holderCacheMax { |
| + c.removeLocked(c.order.Front()) |
| + } |
| + c.holders[host] = c.order.PushBack(&holderEntry{host: host, ref: ref, expires: expires}) |
| +} |
| + |
| +func (c *holderCache) removeLocked(el *list.Element) { |
| + delete(c.holders, el.Value.(*holderEntry).host) |
| + c.order.Remove(el) |
| +} |
| + |
| +// resolve answers a miss for host with one read at a time: the first |
| +// caller runs read and every caller meanwhile waits for its answer (or |
| +// its own ctx, answering ""). read names the holder ("" for none) and ok |
| +// false when it could not tell, which caches nothing. An entry set while |
| +// a caller queued is answered without a read. |
| +func (c *holderCache) resolve(ctx context.Context, host string, read func() (ref string, ok bool)) string { |
| + c.mu.Lock() |
| + if ref, _, found := c.getLocked(host); found { |
| + c.mu.Unlock() |
| + return ref |
| + } |
| + if f := c.flights[host]; f != nil { |
| + c.mu.Unlock() |
| + select { |
| + case <-f.done: |
| + return f.ref |
| + case <-ctx.Done(): |
| + return "" |
| + } |
| + } |
| + f := &holderFlight{done: make(chan struct{})} |
| + if c.flights == nil { |
| + c.flights = map[string]*holderFlight{} |
| + } |
| + c.flights[host] = f |
| + c.mu.Unlock() |
| + |
| + ref, ok := "", false |
| + defer func() { |
| + c.mu.Lock() |
| + delete(c.flights, host) |
| + if ok && !f.stale { |
| + if ref != "" { |
| + c.putLocked(host, ref, holderPositiveTTL) |
| + } else { |
| + c.putLocked(host, "", holderNegativeTTL) |
| + } |
| + } |
| + f.ref = ref |
| + c.mu.Unlock() |
| + close(f.done) |
| + }() |
| + ref, ok = read() |
| + return ref |
| +} |
diff --git a/internal/activator/haforward.go b/internal/activator/haforward.go| new file mode 100644 |
| index 000000000..4daed63d1 |
| --- /dev/null |
| +++ b/internal/activator/haforward.go |
| @@ -0,0 +1,220 @@ |
| +package activator |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "log" |
| + "net/http" |
| + "sync/atomic" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/edge" |
| + "github.com/carlosframework/platform/internal/hafresh" |
| + "github.com/carlosframework/platform/internal/lease" |
| + "github.com/carlosframework/platform/internal/registry" |
| +) |
| + |
| +// Region HA forwarding, the activator's half (region HA P1b-2; spec |
| +// 2026-10-26 §6.2, §6.6). The edge asks ForwardTarget, for a visitor's |
| +// request for a born-HA host, which box to send it to, and tells |
| +// NoteForward how the forward went. The answer comes from the holder cache |
| +// (hacache.go), or on a miss from one read of the host's lock.json. A |
| +// forwarded request this box cannot serve is answered with |
| +// X-Carlos-Holder, so the forwarding box can follow the lease |
| +// (answerForwarded). |
| +// |
| +// Nothing here can keep a host from being served for long. A named box |
| +// that is out of view, unreachable, answers "none", or answers 503 without |
| +// naming anyone is dropped at once, and the request is served here or |
| +// retried against a fresh read; a box that stops holding the host without |
| +// any of those answers it itself, as a verified hop it can wake for. The |
| +// hour's lifetime bounds the rest. |
| + |
| +var _ edge.HAForwarder = (*Service)(nil) |
| + |
| +// holderHeader is edge's: the holder's diagnostic on an answer to a |
| +// forwarded request, the box that holds the lease or "none". |
| +const holderHeader = "X-Carlos-Holder" |
| + |
| +// holderNone is the header's value for a refusal that names no holder. |
| +const holderNone = "none" |
| + |
| +// forwardedHop is edge.HopVerified: whether r arrived as a proven hop from |
| +// another box. A var only so a test can make a request one. |
| +var forwardedHop = edge.HopVerified |
| + |
| +// readHolderLock is lease.ReadLock, the miss's one lock read. A var only so |
| +// a test can hold the read open. |
| +var readHolderLock = lease.ReadLock |
| + |
| +// holderLockReader is the backend's half of a miss: where rt's lock is, |
| +// and who this box is. The exec backend has it; a backend without it |
| +// forwards nothing. |
| +type holderLockReader interface { |
| + readHolderView(ctx context.Context, rt registry.Route) (hafresh.View, error) |
| + self() hafresh.Self |
| +} |
| + |
| +func (b *ExecBackend) readHolderView(ctx context.Context, rt registry.Route) (hafresh.View, error) { |
| + return readHolderLock(ctx, b.Cfg.Bucket, b.Cfg.hibernatePrefix(rt.Host), b.Cfg.Region) |
| +} |
| + |
| +// holderReaderFor is the backend that reads rt's holder, nil for none. The |
| +// agent's backend is a SplitBackend (host/agent.go): rt goes to the half |
| +// that serves it, as every other call does, and the unit half (which never |
| +// wakes a born-HA host) reads nothing. |
| +func holderReaderFor(b Backend, rt registry.Route) holderLockReader { |
| + switch b := b.(type) { |
| + case *SplitBackend: |
| + return holderReaderFor(b.pick(rt), rt) |
| + case holderLockReader: |
| + return b |
| + } |
| + return nil |
| +} |
| + |
| +// boxSelfRef is this box's reference as its HA leases name it: the exec |
| +// backend's identity, through a SplitBackend too. ok is false for a |
| +// backend that takes no HA lease. |
| +func boxSelfRef(b Backend) (string, bool) { |
| + switch b := b.(type) { |
| + case *SplitBackend: |
| + return boxSelfRef(b.Exec) |
| + case holderLockReader: |
| + return b.self().Ref, true |
| + } |
| + return "", false |
| +} |
| + |
| +// holderReadTimeout bounds holder discovery's one lock read, headers and |
| +// body: a store that takes the connection and stalls holds no request, nor |
| +// any request queued on the read, past it. The read then answers "serve |
| +// here" and caches nothing. |
| +const holderReadTimeout = 2 * time.Second |
| + |
| +// holderReadErrLogged is when a failed lock read was last logged (unix |
| +// nanos): at most one line a minute for the box, since every request of |
| +// a host whose read fails reads again. |
| +var holderReadErrLogged atomic.Int64 |
| + |
| +// ForwardTarget names the box rt's request should be forwarded to, or "" |
| +// to serve it here: always "" for a host that is not born HA, or that is |
| +// awake or waking here (begin's own first look, a live entry). Otherwise |
| +// the cache answers; a miss reads the lock once, however many requests |
| +// miss together, and an unexpired HA lease of another box sets the entry, |
| +// anything else the negative one. A read that fails caches nothing. |
| +func (a *Service) ForwardTarget(ctx context.Context, rt registry.Route) string { |
| + if !rt.HA { |
| + return "" |
| + } |
| + r := holderReaderFor(a.backend, rt) |
| + if r == nil { |
| + return "" |
| + } |
| + a.mu.Lock() |
| + here := a.entries[rt.Host] != nil |
| + a.mu.Unlock() |
| + if here { |
| + return "" |
| + } |
| + if ref, positive, found := a.holders.get(rt.Host); found { |
| + if positive { |
| + return ref |
| + } |
| + return "" |
| + } |
| + return a.holders.resolve(ctx, rt.Host, func() (string, bool) { |
| + // The read is every queued caller's, not only this one's: detached |
| + // from this request's cancellation, so one visitor hanging up does |
| + // not fail the rest, and bounded on its own. |
| + rctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), holderReadTimeout) |
| + defer cancel() |
| + v, err := r.readHolderView(rctx, rt) |
| + if err != nil { |
| + now := time.Now() |
| + if last := holderReadErrLogged.Load(); now.UnixNano()-last >= int64(time.Minute) && holderReadErrLogged.CompareAndSwap(last, now.UnixNano()) { |
| + log.Printf("activator: %s: reading the holder: %v; serving here", rt.Host, err) |
| + } |
| + return "", false |
| + } |
| + self, _ := boxSelfRef(a.backend) |
| + return otherHolder(v, self, a.holders.clock()), true |
| + }) |
| +} |
| + |
| +// otherHolder is the box v names as holding the host, when that is an |
| +// unexpired HA lease of a box other than self: "" for an absent lock, a |
| +// release marker, an expired lease, a lock that is not in the HA box |
| +// format, or this box's own. |
| +func otherHolder(v hafresh.View, self string, now time.Time) string { |
| + if v.Absent || v.Lock.Release != nil || !now.Before(v.Lock.ExpiresAt) { |
| + return "" |
| + } |
| + o, ok := hafresh.ParseOwner(v.Lock.Owner) |
| + if !ok || !o.HA || o.Ref == "" || o.Ref == self { |
| + return "" |
| + } |
| + return o.Ref |
| +} |
| + |
| +// NoteForward follows a forward's outcome for host: a named box out of |
| +// view or unreachable, an answer of "none", and a 503 that names nobody |
| +// drop the entry; an answer naming a box sets it, unless the box is this |
| +// one, which drops it (this box is never forwarded to). |
| +func (a *Service) NoteForward(host string, res edge.ForwardResult) { |
| + switch { |
| + case res.Outcome == edge.ForwardNotInView, res.Outcome == edge.ForwardUnreachable: |
| + a.holders.drop(host) |
| + case res.Holder == holderNone: |
| + a.holders.drop(host) |
| + case res.Holder != "": |
| + if self, ok := boxSelfRef(a.backend); ok && res.Holder == self { |
| + a.holders.drop(host) |
| + return |
| + } |
| + a.holders.set(host, res.Holder) |
| + case res.Status == http.StatusServiceUnavailable: |
| + a.holders.drop(host) |
| + } |
| +} |
| + |
| +// answerForwarded is the holder diagnostic on the refusal err of a |
| +// forwarded request (a verified hop) on an HA route; it reports whether it |
| +// wrote the whole answer. A held lease is 503, Retry-After: 1 and the |
| +// holder's ref, whoever holds it (this box's own previous process |
| +// included), so the forwarding box follows the lease. Any other refusal |
| +// gets X-Carlos-Holder: none, so the forwarding box stops forwarding, and |
| +// the caller writes today's answer under it. A cancelled request, a legacy |
| +// route and a request that was not forwarded are left as they are. |
| +func (a *Service) answerForwarded(w http.ResponseWriter, r *http.Request, rt registry.Route, err error) bool { |
| + if !forwardedHA(r, rt, err) { |
| + return false |
| + } |
| + var held *errLeaseHeld |
| + if errors.As(err, &held) { |
| + if o, ok := hafresh.ParseOwner(held.holder); ok && o.Ref != "" { |
| + w.Header().Set("Retry-After", "1") |
| + w.Header().Set(holderHeader, o.Ref) |
| + edge.MarkAnswered(r) |
| + http.Error(w, "instance is waking elsewhere; retry shortly", http.StatusServiceUnavailable) |
| + return true |
| + } |
| + } |
| + w.Header().Set(holderHeader, holderNone) |
| + return false |
| +} |
| + |
| +// noteNoHolder is answerForwarded for a refusal that never names a holder |
| +// (a sidecar request's: asleep, or fenced): X-Carlos-Holder: none on a |
| +// forwarded HA request, and the caller's answer as today. |
| +func noteNoHolder(w http.ResponseWriter, r *http.Request, rt registry.Route, err error) { |
| + if forwardedHA(r, rt, err) { |
| + w.Header().Set(holderHeader, holderNone) |
| + } |
| +} |
| + |
| +// forwardedHA is whether the refusal err of r is owed the holder |
| +// diagnostic: r is a verified hop for an HA route, and was not cancelled. |
| +func forwardedHA(r *http.Request, rt registry.Route, err error) bool { |
| + return rt.HA && forwardedHop(r) && !errors.Is(err, context.Canceled) |
| +} |
diff --git a/internal/activator/haforward_test.go b/internal/activator/haforward_test.go| new file mode 100644 |
| index 000000000..226c5d6d9 |
| --- /dev/null |
| +++ b/internal/activator/haforward_test.go |
| @@ -0,0 +1,519 @@ |
| +package activator |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "fmt" |
| + "net/http" |
| + "net/http/httptest" |
| + "sync" |
| + "sync/atomic" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/edge" |
| + "github.com/carlosframework/platform/internal/hafresh" |
| + "github.com/carlosframework/platform/internal/registry" |
| +) |
| + |
| +// Region HA P1b-2: the activator names the box the edge forwards a born-HA |
| +// host's request to, follows each forward's outcome, and answers a |
| +// forwarded request it cannot serve with the holder's diagnostic. |
| + |
| +// asForwarded makes every request in the test a verified hop. |
| +func asForwarded(t *testing.T) { |
| + t.Helper() |
| + old := forwardedHop |
| + forwardedHop = func(*http.Request) bool { return true } |
| + t.Cleanup(func() { forwardedHop = old }) |
| +} |
| + |
| +// lockGets counts the GETs of rt's lock.json. |
| +func lockGets(b *ExecBackend, rt registry.Route) int { |
| + n := 0 |
| + for _, r := range haFixOf(b).fx.Requests() { |
| + if r == "GET "+lockKeyOf(b, rt) { |
| + n++ |
| + } |
| + } |
| + return n |
| +} |
| + |
| +// haHeldByB is an HA service whose host's lock is b's unexpired HA lease, |
| +// with its route marked born HA. |
| +func haHeldByB(t *testing.T) *haSvc { |
| + t.Helper() |
| + s := haService(t, "shop.example.com") |
| + s.rt.HA = true |
| + putLockFor(t, s.b, s.rt, leaseBody(t, heldByB, time.Now().Add(10*time.Minute))) |
| + return s |
| +} |
| + |
| +func TestForwardTargetNamesTheHolder(t *testing.T) { |
| + s := haHeldByB(t) |
| + if got := s.a.ForwardTarget(context.Background(), s.rt); got != "b" { |
| + t.Fatalf("ForwardTarget = %q, want b", got) |
| + } |
| + if n := lockGets(s.b, s.rt); n != 1 { |
| + t.Fatalf("%d lock reads on a miss, want 1", n) |
| + } |
| + if got := s.a.ForwardTarget(context.Background(), s.rt); got != "b" { |
| + t.Fatalf("ForwardTarget on a hit = %q, want b", got) |
| + } |
| + if n := lockGets(s.b, s.rt); n != 1 { |
| + t.Fatalf("a hit read the lock: %d reads", n) |
| + } |
| +} |
| + |
| +func TestForwardTargetServesHere(t *testing.T) { |
| + t.Run("awake here", func(t *testing.T) { |
| + s, _ := haServiceEntry(t, "shop.example.com") |
| + s.rt.HA = true |
| + before := lockGets(s.b, s.rt) |
| + if got := s.a.ForwardTarget(context.Background(), s.rt); got != "" { |
| + t.Fatalf("ForwardTarget for a host awake here = %q", got) |
| + } |
| + if n := lockGets(s.b, s.rt) - before; n != 0 { |
| + t.Fatalf("a host awake here read the lock %d times", n) |
| + } |
| + }) |
| + t.Run("release marker", func(t *testing.T) { |
| + s := haService(t, "shop.example.com") |
| + s.rt.HA = true |
| + clk := &fakeClock{t: time.Now()} |
| + s.a.holders.now = clk.now |
| + putLockFor(t, s.b, s.rt, markerBody(t, "b", "i-b", haFixOf(s.b).lifetime, 5, true)) |
| + if got := s.a.ForwardTarget(context.Background(), s.rt); got != "" { |
| + t.Fatalf("ForwardTarget over a release marker = %q", got) |
| + } |
| + if _, positive, found := s.a.holders.get(s.rt.Host); !found || positive { |
| + t.Fatalf("no negative entry: found %v, positive %v", found, positive) |
| + } |
| + clk.advance(9 * time.Second) |
| + if got := s.a.ForwardTarget(context.Background(), s.rt); got != "" || lockGets(s.b, s.rt) != 1 { |
| + t.Fatalf("within 10 s: %q, %d reads, want \"\" and 1", got, lockGets(s.b, s.rt)) |
| + } |
| + clk.advance(2 * time.Second) |
| + if got := s.a.ForwardTarget(context.Background(), s.rt); got != "" || lockGets(s.b, s.rt) != 2 { |
| + t.Fatalf("at 11 s: %q, %d reads, want \"\" and 2", got, lockGets(s.b, s.rt)) |
| + } |
| + }) |
| + t.Run("own lease", func(t *testing.T) { |
| + s := haService(t, "shop.example.com") |
| + s.rt.HA = true |
| + putLockFor(t, s.b, s.rt, leaseBody(t, "box/v1;ref=a;iid=i-a;pid=99;ha=1", time.Now().Add(10*time.Minute))) |
| + if got := s.a.ForwardTarget(context.Background(), s.rt); got != "" { |
| + t.Fatalf("ForwardTarget over this box's own lease = %q", got) |
| + } |
| + }) |
| + t.Run("expired lease", func(t *testing.T) { |
| + s := haService(t, "shop.example.com") |
| + s.rt.HA = true |
| + putLockFor(t, s.b, s.rt, leaseBody(t, heldByB, time.Now().Add(-time.Minute))) |
| + if got := s.a.ForwardTarget(context.Background(), s.rt); got != "" { |
| + t.Fatalf("ForwardTarget over an expired lease = %q", got) |
| + } |
| + }) |
| + t.Run("legacy route", func(t *testing.T) { |
| + s := haHeldByB(t) |
| + s.rt.HA = false |
| + if got := s.a.ForwardTarget(context.Background(), s.rt); got != "" || lockGets(s.b, s.rt) != 0 { |
| + t.Fatalf("legacy route: %q, %d reads", got, lockGets(s.b, s.rt)) |
| + } |
| + }) |
| + t.Run("read error", func(t *testing.T) { |
| + s := haHeldByB(t) |
| + s.fx.FailNext("GET", http.StatusForbidden) |
| + if got := s.a.ForwardTarget(context.Background(), s.rt); got != "" { |
| + t.Fatalf("a failed read = %q", got) |
| + } |
| + if _, _, found := s.a.holders.get(s.rt.Host); found { |
| + t.Fatal("a failed read cached an entry") |
| + } |
| + }) |
| +} |
| + |
| +func TestForwardTargetSingleFlight(t *testing.T) { |
| + s := haHeldByB(t) |
| + gate := make(chan struct{}) |
| + var reads atomic.Int32 |
| + old := readHolderLock |
| + readHolderLock = func(ctx context.Context, bucket, prefix, region string) (hafresh.View, error) { |
| + reads.Add(1) |
| + <-gate |
| + return old(ctx, bucket, prefix, region) |
| + } |
| + t.Cleanup(func() { readHolderLock = old }) |
| + var wg sync.WaitGroup |
| + got := make([]string, 20) |
| + for i := range got { |
| + wg.Add(1) |
| + go func() { |
| + defer wg.Done() |
| + got[i] = s.a.ForwardTarget(context.Background(), s.rt) |
| + }() |
| + } |
| + waitFor(t, "the first read", func() bool { return reads.Load() == 1 }) |
| + time.Sleep(50 * time.Millisecond) // the other 19 queue on it |
| + close(gate) |
| + wg.Wait() |
| + for i, ref := range got { |
| + if ref != "b" { |
| + t.Fatalf("caller %d got %q, want b", i, ref) |
| + } |
| + } |
| + if n := reads.Load(); n != 1 { |
| + t.Fatalf("%d lock reads for 20 concurrent misses, want 1", n) |
| + } |
| + if n := lockGets(s.b, s.rt); n != 1 { |
| + t.Fatalf("%d lock GETs, want 1", n) |
| + } |
| +} |
| + |
| +func TestHolderCacheDroppedOnUnreachable(t *testing.T) { |
| + for _, outcome := range []edge.ForwardOutcome{edge.ForwardUnreachable, edge.ForwardNotInView} { |
| + s := haHeldByB(t) |
| + if got := s.a.ForwardTarget(context.Background(), s.rt); got != "b" { |
| + t.Fatalf("ForwardTarget = %q, want b", got) |
| + } |
| + s.a.NoteForward(s.rt.Host, edge.ForwardResult{Outcome: outcome}) |
| + if _, _, found := s.a.holders.get(s.rt.Host); found { |
| + t.Fatalf("outcome %d kept the entry", outcome) |
| + } |
| + } |
| +} |
| + |
| +func TestHolderCacheFollowsHolderHeader(t *testing.T) { |
| + s := haHeldByB(t) |
| + host := s.rt.Host |
| + s.a.holders.set(host, "b") |
| + s.a.NoteForward(host, edge.ForwardResult{Outcome: edge.ForwardDone, Status: 503, Holder: "c"}) |
| + if ref, positive, _ := s.a.holders.get(host); ref != "c" || !positive { |
| + t.Fatalf("after X-Carlos-Holder: c the entry is %q", ref) |
| + } |
| + if got := s.a.ForwardTarget(context.Background(), s.rt); got != "c" || lockGets(s.b, s.rt) != 0 { |
| + t.Fatalf("ForwardTarget = %q with %d reads, want c and none", got, lockGets(s.b, s.rt)) |
| + } |
| + s.a.NoteForward(host, edge.ForwardResult{Outcome: edge.ForwardDone, Status: 503, Holder: "none"}) |
| + if _, _, found := s.a.holders.get(host); found { |
| + t.Fatal("X-Carlos-Holder: none kept the entry") |
| + } |
| + // A holder naming this box itself is never forwarded to. |
| + s.a.holders.set(host, "b") |
| + s.a.NoteForward(host, edge.ForwardResult{Outcome: edge.ForwardDone, Status: 503, Holder: "a"}) |
| + if _, _, found := s.a.holders.get(host); found { |
| + t.Fatal("X-Carlos-Holder naming this box set an entry") |
| + } |
| +} |
| + |
| +func TestHolderCacheBounds(t *testing.T) { |
| + clk := &fakeClock{t: time.Now()} |
| + c := &holderCache{now: clk.now} |
| + for i := range holderCacheMax + 1 { |
| + c.set(fmt.Sprintf("h%d.example.com", i), "b") |
| + } |
| + if n := len(c.holders); n != holderCacheMax { |
| + t.Fatalf("%d entries, want %d", n, holderCacheMax) |
| + } |
| + if _, _, found := c.get("h0.example.com"); found { |
| + t.Fatal("the oldest entry was not evicted") |
| + } |
| + if ref, _, found := c.get(fmt.Sprintf("h%d.example.com", holderCacheMax)); !found || ref != "b" { |
| + t.Fatal("the newest entry is missing") |
| + } |
| + clk.advance(59 * time.Minute) |
| + if _, _, found := c.get("h1.example.com"); !found { |
| + t.Fatal("an entry is gone before its hour") |
| + } |
| + clk.advance(2 * time.Minute) |
| + if _, _, found := c.get("h1.example.com"); found { |
| + t.Fatal("an entry outlived its hour") |
| + } |
| + c.setNegative("n.example.com") |
| + clk.advance(10 * time.Second) |
| + if _, _, found := c.get("n.example.com"); found { |
| + t.Fatal("a negative entry outlived 10 s") |
| + } |
| +} |
| + |
| +func TestTakingTheLeaseDropsTheEntry(t *testing.T) { |
| + s := haService(t, "shop.example.com") |
| + s.a.holders.set(s.rt.Host, "b") |
| + if _, err := s.wakeForTest(context.Background()); err != nil { |
| + t.Fatalf("wake: %v", err) |
| + } |
| + if _, _, found := s.a.holders.get(s.rt.Host); found { |
| + t.Fatal("the entry survived this box taking the lease") |
| + } |
| +} |
| + |
| +// mustNotProxy is the proxy of a request that must be refused. |
| +func mustNotProxy(t *testing.T) http.Handler { |
| + return http.HandlerFunc(func(http.ResponseWriter, *http.Request) { |
| + t.Error("the refused request was proxied") |
| + }) |
| +} |
| + |
| +func TestHoppedHeldAnswersWithTheHolder(t *testing.T) { |
| + asForwarded(t) |
| + t.Run("another box", func(t *testing.T) { |
| + s := haHeldByB(t) |
| + rec := httptest.NewRecorder() |
| + s.a.ServeHTTP(rec, httptest.NewRequest("GET", "http://shop.example.com/", nil), s.rt, mustNotProxy(t)) |
| + if rec.Code != 503 || rec.Header().Get("Retry-After") != "1" || rec.Header().Get(holderHeader) != "b" || |
| + rec.Body.String() != "instance is waking elsewhere; retry shortly\n" { |
| + t.Fatalf("answer %d, Retry-After %q, holder %q, body %q", rec.Code, rec.Header().Get("Retry-After"), rec.Header().Get(holderHeader), rec.Body) |
| + } |
| + }) |
| + t.Run("this box's previous process", func(t *testing.T) { |
| + a, b, _, _ := testActivator(t, time.Minute) |
| + b.acquireErr = &errLeaseHeld{holder: "box/v1;ref=a;iid=i-a;pid=99;ha=1", retryAfter: 7 * time.Minute} |
| + rt := testRoute("shop.example.com") |
| + rt.HA = true |
| + rec := httptest.NewRecorder() |
| + a.ServeHTTP(rec, httptest.NewRequest("GET", "http://shop.example.com/", nil), rt, mustNotProxy(t)) |
| + if rec.Code != 503 || rec.Header().Get("Retry-After") != "1" || rec.Header().Get(holderHeader) != "a" { |
| + t.Fatalf("answer %d, Retry-After %q, holder %q", rec.Code, rec.Header().Get("Retry-After"), rec.Header().Get(holderHeader)) |
| + } |
| + }) |
| +} |
| + |
| +// refusal is the answer to one request for shop.example.com, born HA or |
| +// not, on a fresh activator that setup arranges to refuse it. |
| +func refusal(t *testing.T, ha bool, setup func(*Service, *fakeBackend)) *httptest.ResponseRecorder { |
| + t.Helper() |
| + a, b, _, _ := testActivator(t, time.Minute) |
| + setup(a, b) |
| + rt := testRoute("shop.example.com") |
| + rt.HA = ha |
| + rec := httptest.NewRecorder() |
| + a.ServeHTTP(rec, httptest.NewRequest("GET", "http://shop.example.com/", nil), rt, mustNotProxy(t)) |
| + return rec |
| +} |
| + |
| +func TestHoppedOtherRefusalsSayNone(t *testing.T) { |
| + asForwarded(t) |
| + old := wakeWaitBound |
| + wakeWaitBound = 100 * time.Millisecond |
| + t.Cleanup(func() { wakeWaitBound = old }) |
| + cases := []struct { |
| + name string |
| + retry string |
| + setup func(*Service, *fakeBackend) |
| + }{ |
| + {"config refusal", "30", func(_ *Service, b *fakeBackend) { b.acquireErr = &errConfigRefused{err: errors.New("no key")} }}, |
| + {"lease refusal", "10", func(_ *Service, b *fakeBackend) { b.acquireErr = &errLeaseRefused{reason: "outside the nested layout"} }}, |
| + {"wake timeout", "5", func(_ *Service, b *fakeBackend) { |
| + gate := make(chan struct{}) |
| + b.startGate = gate |
| + t.Cleanup(func() { close(gate) }) |
| + }}, |
| + {"fence", "5", func(a *Service, _ *fakeBackend) { |
| + a.mu.Lock() |
| + a.fences = map[string]uint64{"shop.example.com": 1} |
| + a.mu.Unlock() |
| + }}, |
| + } |
| + for _, c := range cases { |
| + t.Run(c.name, func(t *testing.T) { |
| + today := refusal(t, false, c.setup) |
| + got := refusal(t, true, c.setup) |
| + if got.Code != 503 || got.Code != today.Code || got.Header().Get("Retry-After") != c.retry || |
| + today.Header().Get("Retry-After") != c.retry || got.Body.String() != today.Body.String() { |
| + t.Fatalf("HA %d %q %q, today %d %q %q", got.Code, got.Header().Get("Retry-After"), got.Body, |
| + today.Code, today.Header().Get("Retry-After"), today.Body) |
| + } |
| + if h := got.Header().Get(holderHeader); h != "none" { |
| + t.Fatalf("X-Carlos-Holder %q, want none", h) |
| + } |
| + if h := today.Header().Get(holderHeader); h != "" { |
| + t.Fatalf("a legacy route's refusal names a holder: %q", h) |
| + } |
| + }) |
| + } |
| + t.Run("cancelled", func(t *testing.T) { |
| + a, b, _, _ := testActivator(t, time.Minute) |
| + b.acquireErr = context.Canceled |
| + rt := testRoute("shop.example.com") |
| + rt.HA = true |
| + rec := httptest.NewRecorder() |
| + a.serveWakeError(rec, httptest.NewRequest("GET", "http://shop.example.com/", nil), rt, context.Canceled) |
| + if len(rec.Header()) != 0 || rec.Body.Len() != 0 { |
| + t.Fatalf("a cancelled request was answered: %v %q", rec.Header(), rec.Body) |
| + } |
| + }) |
| +} |
| + |
| +func TestLegacyHopUnchanged(t *testing.T) { |
| + asForwarded(t) |
| + rec := refusal(t, false, func(_ *Service, b *fakeBackend) { |
| + b.acquireErr = &errLeaseHeld{holder: heldByB, retryAfter: 7 * time.Second} |
| + }) |
| + if rec.Code != 503 || rec.Header().Get("Retry-After") != "8" { |
| + t.Fatalf("answer %d, Retry-After %q, want 503 and 8", rec.Code, rec.Header().Get("Retry-After")) |
| + } |
| + if _, ok := rec.Header()[holderHeader]; ok { |
| + t.Fatalf("a legacy hop's answer names a holder: %q", rec.Header().Get(holderHeader)) |
| + } |
| +} |
| + |
| +func TestHolderCacheDroppedOnHeaderless503(t *testing.T) { |
| + s := haHeldByB(t) |
| + host := s.rt.Host |
| + s.a.holders.set(host, "b") |
| + s.a.NoteForward(host, edge.ForwardResult{Outcome: edge.ForwardDone, Status: 200}) |
| + if ref, _, _ := s.a.holders.get(host); ref != "b" { |
| + t.Fatalf("a 200 changed the entry to %q", ref) |
| + } |
| + s.a.NoteForward(host, edge.ForwardResult{Outcome: edge.ForwardDone, Status: 503}) |
| + if _, _, found := s.a.holders.get(host); found { |
| + t.Fatal("a 503 naming nobody kept the entry") |
| + } |
| +} |
| + |
| +func TestScheduledTickNeverForwards(t *testing.T) { |
| + s := haHeldByB(t) |
| + var reads atomic.Int32 |
| + old := readHolderLock |
| + readHolderLock = func(ctx context.Context, bucket, prefix, region string) (hafresh.View, error) { |
| + reads.Add(1) |
| + return old(ctx, bucket, prefix, region) |
| + } |
| + t.Cleanup(func() { readHolderLock = old }) |
| + rec := httptest.NewRecorder() |
| + s.a.ServeScheduled(rec, httptest.NewRequest("POST", "http://shop.example.com/", nil), s.rt, mustNotProxy(t)) |
| + if rec.Code != 503 || rec.Header().Get("Retry-After") == "" || rec.Header().Get("Retry-After") == "1" || |
| + rec.Body.String() != "instance is waking elsewhere; retry shortly\n" { |
| + t.Fatalf("answer %d, Retry-After %q, body %q", rec.Code, rec.Header().Get("Retry-After"), rec.Body) |
| + } |
| + if _, ok := rec.Header()[holderHeader]; ok { |
| + t.Fatal("a scheduled tick's answer names a holder") |
| + } |
| + if reads.Load() != 0 { |
| + t.Fatal("the tick asked for a forward target") |
| + } |
| + if _, _, found := s.a.holders.get(s.rt.Host); found { |
| + t.Fatal("the tick set a holder entry") |
| + } |
| +} |
| + |
| +// The production backend is a SplitBackend over the exec backend |
| +// (host/agent.go): holder discovery goes through it to the exec half, and a |
| +// unit-backed row, which cannot be born HA here, reads nothing. |
| +func TestForwardTargetThroughSplitBackend(t *testing.T) { |
| + s := haHeldByB(t) |
| + a := New(Config{Bucket: s.b.Cfg.Bucket, Idle: time.Hour}, &SplitBackend{Exec: s.b, Unit: &UnitBackend{}}, s.b.Registry) |
| + if got := a.ForwardTarget(context.Background(), s.rt); got != "b" { |
| + t.Fatalf("ForwardTarget through the split backend = %q, want b", got) |
| + } |
| + if n := lockGets(s.b, s.rt); n != 1 { |
| + t.Fatalf("%d lock reads on a miss, want 1", n) |
| + } |
| + if got := a.ForwardTarget(context.Background(), s.rt); got != "b" || lockGets(s.b, s.rt) != 1 { |
| + t.Fatalf("a hit: %q with %d reads, want b and 1", got, lockGets(s.b, s.rt)) |
| + } |
| + // This box's identity is the exec half's: an answer naming it drops. |
| + a.NoteForward(s.rt.Host, edge.ForwardResult{Outcome: edge.ForwardDone, Status: 503, Holder: "a"}) |
| + if _, _, found := a.holders.get(s.rt.Host); found { |
| + t.Fatal("X-Carlos-Holder naming this box set an entry through the split backend") |
| + } |
| + unit := s.rt |
| + unit.Host, unit.Backing = "unit.example.com", registry.BackingUnit |
| + if got := a.ForwardTarget(context.Background(), unit); got != "" { |
| + t.Fatalf("a unit-backed row = %q", got) |
| + } |
| +} |
| + |
| +// A forwarded sidecar request on an HA route is refused as today, asleep or |
| +// fenced, and says none; a legacy route's says nothing. |
| +func TestHoppedSidecarRefusalsSayNone(t *testing.T) { |
| + asForwarded(t) |
| + cases := []struct { |
| + name string |
| + setup func(*Service, *fakeBackend) |
| + }{ |
| + {"asleep", func(*Service, *fakeBackend) {}}, |
| + // BeginSidecarRequest's own fence, past serve's: a held recovery |
| + // probe's entry. |
| + {"fenced", func(a *Service, _ *fakeBackend) { |
| + a.mu.Lock() |
| + a.entries["shop.example.com"] = &actEntry{host: "shop.example.com", state: actWaking, ready: make(chan struct{}), probeHeld: true} |
| + a.mu.Unlock() |
| + }}, |
| + } |
| + sidecar := func(t *testing.T, ha bool, setup func(*Service, *fakeBackend)) *httptest.ResponseRecorder { |
| + a, b, _, _ := testActivator(t, time.Minute) |
| + setup(a, b) |
| + rt := testRoute("shop.example.com") |
| + rt.HA = ha |
| + req := httptest.NewRequest("GET", "http://shop.example.com/", nil) |
| + req.Header.Set(SidecarHeader, "1") |
| + rec := httptest.NewRecorder() |
| + a.ServeHTTP(rec, req, rt, mustNotProxy(t)) |
| + return rec |
| + } |
| + for _, c := range cases { |
| + t.Run(c.name, func(t *testing.T) { |
| + today := sidecar(t, false, c.setup) |
| + got := sidecar(t, true, c.setup) |
| + if got.Code != 503 || got.Code != today.Code || got.Header().Get("Retry-After") != "5" || |
| + today.Header().Get("Retry-After") != "5" || got.Body.String() != today.Body.String() { |
| + t.Fatalf("HA %d %q %q, today %d %q %q", got.Code, got.Header().Get("Retry-After"), got.Body, |
| + today.Code, today.Header().Get("Retry-After"), today.Body) |
| + } |
| + if h := got.Header().Get(holderHeader); h != "none" { |
| + t.Fatalf("X-Carlos-Holder %q, want none", h) |
| + } |
| + if _, ok := today.Header()[holderHeader]; ok { |
| + t.Fatal("a legacy route's sidecar refusal names a holder") |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// A store that takes the connection and never answers holds no request past |
| +// holderReadTimeout: the read's initiator and every caller queued on it |
| +// return "", nothing is cached, the flight is gone, and the next lookup |
| +// reads afresh. |
| +func TestForwardTargetStalledReadIsBounded(t *testing.T) { |
| + s := haHeldByB(t) |
| + release := make(chan struct{}) |
| + stall := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + select { |
| + case <-release: |
| + case <-r.Context().Done(): |
| + } |
| + })) |
| + t.Cleanup(stall.Close) |
| + t.Cleanup(func() { close(release) }) // before stall.Close, which waits on the handlers |
| + t.Setenv("CARLOS_S3_ENDPOINT", stall.URL) |
| + start := time.Now() |
| + got := make(chan string, 10) |
| + for range cap(got) { |
| + go func() { got <- s.a.ForwardTarget(context.Background(), s.rt) }() |
| + } |
| + bound := time.After(holderReadTimeout + 2*time.Second) |
| + for range cap(got) { |
| + select { |
| + case ref := <-got: |
| + if ref != "" { |
| + t.Fatalf("a stalled read answered %q", ref) |
| + } |
| + case <-bound: |
| + t.Fatalf("lookups still waiting %s after a stalled read began", time.Since(start)) |
| + } |
| + } |
| + if _, _, found := s.a.holders.get(s.rt.Host); found { |
| + t.Fatal("a stalled read cached an entry") |
| + } |
| + s.a.holders.mu.Lock() |
| + flights := len(s.a.holders.flights) |
| + s.a.holders.mu.Unlock() |
| + if flights != 0 { |
| + t.Fatalf("%d flights left after the stalled read", flights) |
| + } |
| + t.Setenv("CARLOS_S3_ENDPOINT", s.fx.URL) |
| + if ref := s.a.ForwardTarget(context.Background(), s.rt); ref != "b" || lockGets(s.b, s.rt) != 1 { |
| + t.Fatalf("the lookup after the stall: %q with %d reads, want b and 1", ref, lockGets(s.b, s.rt)) |
| + } |
| +} |
diff --git a/internal/edge/assetcatch.go b/internal/edge/assetcatch.go| index d082efa33..9add65556 100644 |
| --- a/internal/edge/assetcatch.go |
| +++ b/internal/edge/assetcatch.go |
| @@ -1275,6 +1275,9 @@ type assetInformationalScrub struct{ http.ResponseWriter } |
| func (s assetInformationalScrub) WriteHeader(code int) { |
| if code < 200 { |
| stripAssetResponseHeaders(s.Header()) |
| + // Nor an app's holder diagnostic (responseModifier's rule): the |
| + // platform never sends one on a 1xx. |
| + s.Header().Del(holderHeader) |
| } |
| s.ResponseWriter.WriteHeader(code) |
| } |
diff --git a/internal/edge/backhaul_e2e_test.go b/internal/edge/backhaul_e2e_test.go| index 1ed30579c..909491b1e 100644 |
| --- a/internal/edge/backhaul_e2e_test.go |
| +++ b/internal/edge/backhaul_e2e_test.go |
| @@ -510,13 +510,13 @@ type backhaulScene struct { |
| } |
| // backhaulSceneExtra is what a scene adds to the standard two edges: more |
| -// route rows on either edge, the home edge's activator, more certificates in |
| +// route rows on either edge, either edge's activator, more certificates in |
| // the bucket, and more entries in the home edge's and the sending edge's |
| // edges files (host → the JSON of its entry, edgesHostView's shape). The zero |
| // value is the standard scene. |
| type backhaulSceneExtra struct { |
| homeRoutes, farRoutes []registry.Route |
| - homeAct Activator |
| + homeAct, farAct Activator |
| certs []string |
| homeEntries, farEntries map[string]string |
| } |
| @@ -554,7 +554,7 @@ func newBackhaulSceneWith(t *testing.T, x backhaulSceneExtra) *backhaulScene { |
| s.a = newBackhaulEdgeWith(t, bucket, "annie", s.ca, from, x.homeAct, append([]registry.Route{{ |
| Host: e2eHomedHost, Kind: "service", Addr: e2eApp(t, e2eHomeMarker).Listener.Addr().String(), Status: "ready", |
| }}, x.homeRoutes...)) |
| - s.b = newBackhaulEdgeWith(t, bucket, "betty", s.ca, from, nil, append([]registry.Route{{ |
| + s.b = newBackhaulEdgeWith(t, bucket, "betty", s.ca, from, x.farAct, append([]registry.Route{{ |
| Host: e2eSenderHost, Kind: "service", Addr: e2eApp(t, e2eSenderMarker).Listener.Addr().String(), Status: "ready", |
| }}, x.farRoutes...)) |
diff --git a/internal/edge/cookiescope.go b/internal/edge/cookiescope.go| index e8f073124..7223ec745 100644 |
| --- a/internal/edge/cookiescope.go |
| +++ b/internal/edge/cookiescope.go |
| @@ -74,8 +74,14 @@ func appsDomainFromEnv() string { |
| // proxy: the Carlos-Purge channel (purgeModifier), the removal of any asset |
| // cache header or trailer the app set (stripAssetResponseHeaders, |
| // stripAssetTrailers: the edge's own are set after this, never inherited |
| -// from the app) and the cookie scoping above, in that order. None depends on |
| -// another. |
| +// from the app), the removal of any X-Carlos-Holder the app set, as a |
| +// header or a trailer (stripAppHolder), and the |
| +// cookie scoping above, in that order. None depends on another. |
| +// |
| +// X-Carlos-Holder names the box holding an HA host's lease (forwardha.go), |
| +// and a forwarding box's holder cache follows it, so only the platform may |
| +// say it: the activator's and the edge's own refusals, which are written to |
| +// the client directly and never pass through this hook. |
| func (e *Edge) responseModifier(rt registry.Route) func(*http.Response) error { |
| purge := e.purgeModifier(rt) |
| return func(resp *http.Response) error { |
| @@ -84,6 +90,7 @@ func (e *Edge) responseModifier(rt registry.Route) func(*http.Response) error { |
| } |
| stripAssetResponseHeaders(resp.Header) |
| stripAssetTrailers(resp) |
| + stripAppHolder(resp) |
| e.scopeCookies(rt, resp) |
| return nil |
| } |
diff --git a/internal/edge/edge.go b/internal/edge/edge.go| index 0a8cb6e54..7098c8997 100644 |
| --- a/internal/edge/edge.go |
| +++ b/internal/edge/edge.go |
| @@ -307,6 +307,10 @@ type Edge struct { |
| // backhaul target, and keying per host would let a stranger's stream of |
| // invented hostnames grow this map without limit. |
| backhaulTransports sync.Map |
| + // forwardTransports is the same for region HA forwards (forwardha.go), |
| + // keyed by the holder's dial address: their own cache, with their own |
| + // 2 s connect bound, so backhaulTo's transports never change. |
| + forwardTransports sync.Map |
| // backhaulInflight counts the hops currently in flight toward each home |
| // box — the containment half of the egress ruling (backhaulAcquire). |
| // Keyed by BOX for the same reason backhaulTransports is keyed by EIP: a |
| @@ -1771,6 +1775,17 @@ func (e *Edge) ServeHTTP(w http.ResponseWriter, r *http.Request) { |
| return |
| } |
| + // Region HA forwarding (forwardha.go): a visitor's request for a born-HA |
| + // host whose lease another box in this region holds goes to that box |
| + // HERE, before any per-request step below runs on this box, so the |
| + // holder runs each of them once. After the lookup and its !ok branch, |
| + // which a forward never needs, and before the login POST reads the body |
| + // (the hop proxies it). A verified hop, a door call and a tunnel |
| + // delivery are never forwarded; nor is a regional name. |
| + if e.frontForwardHA(w, r, host, up, hopped, isDoor) { |
| + return |
| + } |
| + |
| // A login POST re-resolves its upstream by the path in `next`, not by |
| // its own (spec §4.2). On a hostname that routes by path prefix, |
| // lookupUpstreamPath keys on the first segment; "/.carlos/gate" has no |
| @@ -3413,11 +3428,26 @@ func (e *Edge) backhaulTo(w http.ResponseWriter, r *http.Request, host, eip, box |
| e.logThrottled("backhaul-no-mesh-key", fmt.Sprintf("%s is homed on %s but no mesh key is mirrored — not dialling (the request gets the unknown-host answer until the key lands)", host, box)) |
| return false |
| } |
| + e.hopTo(w, r, host, eip, box, key, "backhaul", e.backhaulTransport(eip), nil, nil) |
| + return true |
| +} |
| + |
| +// hopTo is the sign-admit-proxy core backhaulTo and a region HA forward |
| +// (forwardHA) share: admit the hop toward box, sign it for host with key, and |
| +// proxy r to eip over tr. It reports whether the hop was admitted; a refusal |
| +// has been answered on w. |
| +// |
| +// onError, when non-nil, replaces backhaulProxy's error answer (the 502), |
| +// and onResponse, when non-nil, sees each upstream response before |
| +// backhaulProxy's own scrub. event is the regionalObserve test hook's name |
| +// for the dial. |
| +func (e *Edge) hopTo(w http.ResponseWriter, r *http.Request, host, eip, box string, key []byte, event string, tr http.RoundTripper, |
| + onError func(http.ResponseWriter, *http.Request, error), onResponse func(*http.Response)) bool { |
| // Containment (the egress ruling, 2026-08-24), between the last guard and |
| // the dial: backhaulAdmit answers a refused hop itself. |
| releaseSlot, ok := e.backhaulAdmit(w, r, eip, box) |
| if !ok { |
| - return true |
| + return false |
| } |
| // Held until the hop's ServeHTTP returns, which for a stream or an |
| // upgraded connection is the life of the stream (backhaulAcquire). |
| @@ -3433,11 +3463,22 @@ func (e *Edge) backhaulTo(w http.ResponseWriter, r *http.Request, host, eip, box |
| if _, ok := doorCallerFrom(r.Context()); ok { |
| doorAuth = signHopDoor(key, host, now) |
| } |
| + p := backhaulProxy(host, eip, box, auth, doorAuth, false, tr, e.logThrottled) |
| + if onError != nil { |
| + p.ErrorHandler = onError |
| + } |
| + if onResponse != nil { |
| + scrub := p.ModifyResponse |
| + p.ModifyResponse = func(resp *http.Response) error { |
| + onResponse(resp) |
| + return scrub(resp) |
| + } |
| + } |
| // The client boundary for informational responses: a 1xx from the home |
| // reaches w through the proxy's trace hook, past ModifyResponse, so the |
| // asset vocabulary comes off it here (assetInformationalScrub). |
| - observeRegional("backhaul", host) |
| - backhaulProxy(host, eip, box, auth, doorAuth, false, e.backhaulTransport(eip), e.logThrottled).ServeHTTP(assetInformationalScrub{w}, r) |
| + observeRegional(event, host) |
| + p.ServeHTTP(assetInformationalScrub{w}, r) |
| return true |
| } |
diff --git a/internal/edge/forwardha.go b/internal/edge/forwardha.go| new file mode 100644 |
| index 000000000..fc8407ec3 |
| --- /dev/null |
| +++ b/internal/edge/forwardha.go |
| @@ -0,0 +1,230 @@ |
| +package edge |
| + |
| +// Region HA forwarding at the front door (region HA P1b-2; spec 2026-10-26 |
| +// §6.2, §6.4). A visitor's request for a born-HA host that reaches a box |
| +// which does not hold the host's lease goes to the box that does, over the |
| +// signed backhaul hop, before this box runs any per-request step: the gate, |
| +// the door scope, the import and plan gates, the guards, request records, |
| +// rate limits, assets, compression, the cache, usage and analytics. A |
| +// forwarded request therefore has one box doing every one of them, the |
| +// holder, exactly as a cross-region backhaul does today. |
| +// |
| +// The activator says WHETHER and to WHICH box (HAForwarder, found on the |
| +// edge's own Activator); the edge says whether that box is in its view |
| +// (boxInView) and owns the hop and its failure answers. One hop, ever: a |
| +// verified hop is never forwarded (frontForwardHA's first test, and |
| +// forwardHA's own), and the holder answers what it cannot serve itself. |
| + |
| +import ( |
| + "context" |
| + "crypto/tls" |
| + "errors" |
| + "fmt" |
| + "net" |
| + "net/http" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/registry" |
| +) |
| + |
| +// HAForwarder is the activator's half of region HA forwarding. The edge finds |
| +// it with a type assertion on its Activator; an activator without it, or no |
| +// activator, forwards nothing. |
| +// |
| +// ForwardTarget names the box a request for rt should go to, or "" to serve |
| +// it here. NoteForward reports how the forward went, so the activator's |
| +// holder cache can follow it. host is rt.Host, the route's own host, never an |
| +// alias the request named. |
| +type HAForwarder interface { |
| + ForwardTarget(ctx context.Context, rt registry.Route) string |
| + NoteForward(host string, res ForwardResult) |
| +} |
| + |
| +// ForwardOutcome is how one forward ended. |
| +type ForwardOutcome int |
| + |
| +const ( |
| + // ForwardNotInView: the named box is not in this box's view, or no mesh |
| + // key is mirrored. Nothing was written; the request is served here. |
| + ForwardNotInView ForwardOutcome = iota |
| + // ForwardUnreachable: the named box could not be connected to within |
| + // forwardDialTimeout. This box answered 503, Retry-After: 10. |
| + ForwardUnreachable |
| + // ForwardDone: the request went to the named box and its answer, whatever |
| + // it was, was relayed, or this box refused the hop itself (Status 0). |
| + ForwardDone |
| +) |
| + |
| +// ForwardResult is what NoteForward is told. Status is the upstream's status, |
| +// 0 when no answer came back from it (a hop this box refused, or a failure |
| +// after connecting). Holder is the upstream's X-Carlos-Holder, "" when absent. |
| +type ForwardResult struct { |
| + Outcome ForwardOutcome |
| + Status int |
| + Holder string |
| +} |
| + |
| +// holderHeader is the holder's diagnostic on an answer to a forwarded |
| +// request: the box that holds the lease, or "none". Only the platform sets |
| +// it; an app's is removed at the tenant response boundary (responseModifier). |
| +const holderHeader = "X-Carlos-Holder" |
| + |
| +// stripAppHolder removes an app's X-Carlos-Holder from resp at the tenant |
| +// response boundary (responseModifier): the header, the announced trailer |
| +// name now, and the trailer value, announced or not, when the body closes, |
| +// which is when httputil.ReverseProxy has filled resp.Trailer and before it |
| +// copies it out (stripAssetTrailers' arrangement). A 101 keeps its body: it |
| +// is the raw connection, and carries no trailers. |
| +func stripAppHolder(resp *http.Response) { |
| + resp.Header.Del(holderHeader) |
| + resp.Trailer.Del(holderHeader) |
| + if resp.StatusCode == http.StatusSwitchingProtocols || resp.Body == nil { |
| + return |
| + } |
| + resp.Body = &trailerCookieBody{ReadCloser: resp.Body, close: func() { |
| + resp.Trailer.Del(holderHeader) |
| + }} |
| +} |
| + |
| +// forwardDialTimeout bounds connecting to the holder, TCP and TLS together. |
| +// Shorter than backhaulDialTimeout: the holder is in this box's own region, |
| +// and a holder that does not answer in 2 s is treated as gone (the 503 tells |
| +// the visitor to come back once the activator has looked again). |
| +const forwardDialTimeout = 2 * time.Second |
| + |
| +// forwardDial makes the TCP connection to a holder at addr. A var only so a |
| +// test can point it at another listener or make it stall; the deadline is on |
| +// ctx. |
| +var forwardDial = func(ctx context.Context, network, addr string) (net.Conn, error) { |
| + var d net.Dialer |
| + return d.DialContext(ctx, network, addr) |
| +} |
| + |
| +// forwardConnectError marks a failure to connect to the holder, as against a |
| +// failure after connecting, so the error answer can tell them apart. |
| +type forwardConnectError struct{ err error } |
| + |
| +func (e *forwardConnectError) Error() string { return "connect: " + e.err.Error() } |
| +func (e *forwardConnectError) Unwrap() error { return e.err } |
| + |
| +// frontForwardHA is the front-door decision, called in ServeHTTP right after |
| +// route lookup. It reports whether it answered. False, serve here, unless the |
| +// request has a local route (the caller's ok), is not a verified hop, a door |
| +// call or a tunnel delivery, its route is born HA, activator-managed and not |
| +// reached through a regional name, and the activator names a box. Then the |
| +// request is forwarded, the activator is told how it went, and it is answered |
| +// unless the box was not in view. |
| +func (e *Edge) frontForwardHA(w http.ResponseWriter, r *http.Request, host string, up upstream, hopped, isDoor bool) bool { |
| + if hopped || isDoor || hopVerified(r.Context()) || fromTunnel(r.Context()) { |
| + return false |
| + } |
| + if !up.route.HA || !up.hibernating || up.regional != regionalNone { |
| + return false |
| + } |
| + fw, ok := e.act.(HAForwarder) |
| + if !ok { |
| + return false |
| + } |
| + ref := fw.ForwardTarget(r.Context(), up.route) |
| + if ref == "" { |
| + return false |
| + } |
| + res := e.forwardHA(w, r, host, ref) |
| + fw.NoteForward(up.route.Host, res) |
| + return res.Outcome != ForwardNotInView |
| +} |
| + |
| +// forwardHA sends r to the box labelled ref over a signed hop for host. A box |
| +// out of view, or no mesh key, writes nothing and answers ForwardNotInView. |
| +// Otherwise the hop is admitted and signed as backhaulTo's is, over this |
| +// edge's forward transport to ref. A failure to connect is answered 503, |
| +// Retry-After: 10; every other answer is the holder's, relayed as is. |
| +// |
| +// It repeats the arrived-hop guard: a verified hop is never forwarded, so a |
| +// forwarding loop needs this line and frontForwardHA's to be wrong at once. |
| +func (e *Edge) forwardHA(w http.ResponseWriter, r *http.Request, host, ref string) ForwardResult { |
| + m := e.homes.Load() |
| + if m == nil || hopVerified(r.Context()) { |
| + return ForwardResult{Outcome: ForwardNotInView} |
| + } |
| + dial, ok := m.boxInView(ref, time.Now()) |
| + if !ok { |
| + return ForwardResult{Outcome: ForwardNotInView} |
| + } |
| + key := signingKey(m.meshKeys()) |
| + if len(key) == 0 { |
| + e.logThrottled("forward-no-mesh-key", fmt.Sprintf("%s is held on %s but no mesh key is mirrored; serving here", host, ref)) |
| + return ForwardResult{Outcome: ForwardNotInView} |
| + } |
| + res := ForwardResult{Outcome: ForwardDone} |
| + onError := func(w http.ResponseWriter, r *http.Request, err error) { |
| + var connect *forwardConnectError |
| + if errors.As(err, &connect) && r.Context().Err() == nil { |
| + e.logThrottled("forward-unreachable "+ref, fmt.Sprintf("forward %s → %s (%s): %v; answering 503 + Retry-After: 10", host, ref, dial, err)) |
| + res.Outcome = ForwardUnreachable |
| + w.Header().Set("Retry-After", "10") |
| + MarkAnswered(r) |
| + http.Error(w, "instance is waking elsewhere; retry shortly", http.StatusServiceUnavailable) |
| + return |
| + } |
| + // After connecting, or the client left: backhaul's bad gateway. |
| + e.logThrottled("forward-error "+ref, fmt.Sprintf("forward %s → %s (%s): %v", host, ref, dial, err)) |
| + w.WriteHeader(http.StatusBadGateway) |
| + } |
| + onResponse := func(resp *http.Response) { |
| + res.Status = resp.StatusCode |
| + res.Holder = resp.Header.Get(holderHeader) |
| + } |
| + e.hopTo(w, r, host, dial, ref, key, "forward", e.forwardTransport(dial), onError, onResponse) |
| + return res |
| +} |
| + |
| +// forwardTransport is the cached transport to the holder at dial, as |
| +// backhaulTransport is per EIP and for the same reasons, with one difference: |
| +// connecting (TCP and TLS) has forwardDialTimeout in all, and a failure there |
| +// is a forwardConnectError. A separate cache, so backhaulTo's 5 s transports |
| +// to the same address are never this one. |
| +// |
| +// It does the TLS itself (DialTLSContext) so that the deadline and the error |
| +// mark cover the handshake too. Verification is backhaulTransport's: the |
| +// system roots (backhaulRootCAs) and the host from the outbound URL's |
| +// authority. No ALPN is offered, so the hop speaks HTTP/1.1 and an upgrade |
| +// passes through. |
| +func (e *Edge) forwardTransport(dial string) *http.Transport { |
| + if tr, ok := e.forwardTransports.Load(dial); ok { |
| + return tr.(*http.Transport) |
| + } |
| + tr := &http.Transport{ |
| + DialTLSContext: func(ctx context.Context, network, addr string) (net.Conn, error) { |
| + name, _, err := net.SplitHostPort(addr) |
| + if err != nil { |
| + return nil, &forwardConnectError{err} |
| + } |
| + ctx, cancel := context.WithTimeout(ctx, forwardDialTimeout) |
| + defer cancel() |
| + raw, err := forwardDial(ctx, network, net.JoinHostPort(dial, backhaulPort)) |
| + if err != nil { |
| + return nil, &forwardConnectError{err} |
| + } |
| + conn := tls.Client(raw, &tls.Config{ServerName: name, RootCAs: backhaulRootCAs, MinVersion: tls.VersionTLS12}) |
| + if err := conn.HandshakeContext(ctx); err != nil { |
| + raw.Close() |
| + return nil, &forwardConnectError{err} |
| + } |
| + return conn, nil |
| + }, |
| + ResponseHeaderTimeout: backhaulHeaderTimeout, |
| + // The client's Accept-Encoding goes to the holder as sent. Without |
| + // this the transport would ask for gzip on the client's behalf and |
| + // undo it here, and the holder would meter the compressed bytes |
| + // while this box delivered more. |
| + DisableCompression: true, |
| + MaxIdleConns: 32, |
| + MaxIdleConnsPerHost: 32, |
| + IdleConnTimeout: 90 * time.Second, |
| + } |
| + if existing, loaded := e.forwardTransports.LoadOrStore(dial, tr); loaded { |
| + return existing.(*http.Transport) |
| + } |
| + return tr |
| +} |
diff --git a/internal/edge/forwardha_test.go b/internal/edge/forwardha_test.go| new file mode 100644 |
| index 000000000..36526b817 |
| --- /dev/null |
| +++ b/internal/edge/forwardha_test.go |
| @@ -0,0 +1,962 @@ |
| +package edge |
| + |
| +// Region HA P1b-2 Task 2: the front-door forward. The scene is the |
| +// multi-region backhaul's (newBackhaulSceneWith): two real Edges over one |
| +// DirStore, real TLS on both doors, the mesh key minted into the bucket and |
| +// real hop auth. Here both boxes serve the same born-HA hosts, both are in |
| +// region "ie" and placement "p" with the same data bucket and secrets key, |
| +// and annie's activator is a fake HAForwarder naming betty as the holder. |
| +// Every request below is a real client's, handshaken with annie by name. |
| +// |
| +// One seam stands in for the network: every box in a scene is dialled on |
| +// one port (backhaulPort), so forwardDial sends annie's forwards to betty's |
| +// door, where the dial address would be betty's EIP in production. |
| + |
| +import ( |
| + "bufio" |
| + "context" |
| + "crypto/tls" |
| + "fmt" |
| + "io" |
| + "net" |
| + "net/http" |
| + "net/http/httptest" |
| + "path/filepath" |
| + "strings" |
| + "sync" |
| + "sync/atomic" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/analytics" |
| + "github.com/carlosframework/platform/internal/assetcache" |
| + "github.com/carlosframework/platform/internal/gate" |
| + "github.com/carlosframework/platform/internal/registry" |
| + "github.com/carlosframework/platform/internal/reqrec" |
| + "github.com/carlosframework/platform/internal/usage" |
| +) |
| + |
| +const ( |
| + // fwHost is the plain born-HA instance both boxes serve. |
| + fwHost = "ha.forward.test" |
| + // fwGatedHost is the same behind the password gate. |
| + fwGatedHost = "gated.forward.test" |
| + // fwAssetHost is an ungated HA instance whose /assets/ the asset cache |
| + // catches on both boxes. |
| + fwAssetHost = "assets.forward.test" |
| + // fwRateHost is an HA instance with a one-request backstop. |
| + fwRateHost = "rate.forward.test" |
| + // fwLegacyHost is an activator-managed instance that is not HA. |
| + fwLegacyHost = "legacy.forward.test" |
| + |
| + fwAssetBody = "console.log('forwarded');\n" |
| + fwPassword = "correct horse" |
| +) |
| + |
| +// fwBigBody is a page large and repetitive enough for the edge to gzip. |
| +var fwBigBody = strings.Repeat("<p>forwarded and compressible</p>\n", 2048) |
| + |
| +var fwHosts = []string{fwHost, fwGatedHost, fwAssetHost, fwRateHost, fwLegacyHost} |
| + |
| +// fwAct is a box's activator: it wakes nothing (the route's TCP upstream |
| +// answers) and, as an HAForwarder, names target and keeps every note. |
| +type fwAct struct { |
| + target string |
| + asked atomic.Int64 |
| + mu sync.Mutex |
| + notes []fwNote |
| +} |
| + |
| +type fwNote struct { |
| + host string |
| + res ForwardResult |
| +} |
| + |
| +var _ HAForwarder = (*fwAct)(nil) |
| + |
| +func (a *fwAct) ServeHTTP(w http.ResponseWriter, r *http.Request, _ registry.Route, _ http.Handler) bool { |
| + // The platform's own refusal of a forwarded request (Task 3's answer): |
| + // written by the activator, never by the app. |
| + if r.URL.Path == "/platform-held" { |
| + w.Header().Set(holderHeader, r.URL.Query().Get("ref")) |
| + w.Header().Set("Retry-After", "1") |
| + MarkAnswered(r) |
| + http.Error(w, "instance is waking elsewhere; retry shortly", http.StatusServiceUnavailable) |
| + return true |
| + } |
| + return false |
| +} |
| +func (a *fwAct) RetireExcept(map[string]bool) {} |
| +func (a *fwAct) ForwardTarget(_ context.Context, _ registry.Route) string { |
| + a.asked.Add(1) |
| + return a.target |
| +} |
| +func (a *fwAct) NoteForward(host string, res ForwardResult) { |
| + a.mu.Lock() |
| + defer a.mu.Unlock() |
| + a.notes = append(a.notes, fwNote{host, res}) |
| +} |
| + |
| +func (a *fwAct) noted() []fwNote { |
| + a.mu.Lock() |
| + defer a.mu.Unlock() |
| + return append([]fwNote(nil), a.notes...) |
| +} |
| + |
| +// fwPlainAct is an activator without the forwarding interface. |
| +type fwPlainAct struct{} |
| + |
| +func (fwPlainAct) ServeHTTP(http.ResponseWriter, *http.Request, registry.Route, http.Handler) bool { |
| + return false |
| +} |
| +func (fwPlainAct) RetireExcept(map[string]bool) {} |
| + |
| +// fwApp is one box's app behind every forward host. Its ordinary body names |
| +// the box, the host and the path; /missing is a 404; /holder answers 503 with |
| +// X-Carlos-Holder set to its ref query (none when the query is empty), or |
| +// the status query's status; /big is a large compressible page; |
| +// /assets/ is a cacheable script, and /assets/held.js waits on the first |
| +// request until the test releases it; an upgrade echoes with the box's name. |
| +type fwAppServer struct { |
| + srv *httptest.Server |
| + n atomic.Int64 |
| + first func() bool |
| + started chan struct{} |
| + wait, release func() |
| + heldRequests, assetRequests atomic.Int64 |
| +} |
| + |
| +func fwApp(t *testing.T, box string) *fwAppServer { |
| + t.Helper() |
| + a := &fwAppServer{} |
| + a.first, a.started, a.wait, a.release = fillGate() |
| + t.Cleanup(a.release) |
| + echo := upgradeEchoHandler(box) |
| + a.srv = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + a.n.Add(1) |
| + switch { |
| + case isUpgradeRequest(r): |
| + echo.ServeHTTP(w, r) |
| + case r.URL.Path == "/missing": |
| + http.NotFound(w, r) |
| + case r.URL.Path == "/holder": |
| + if ref := r.URL.Query().Get("ref"); ref != "" { |
| + w.Header().Set(holderHeader, ref) |
| + } |
| + status := http.StatusServiceUnavailable |
| + if r.URL.Query().Get("status") == "200" { |
| + status = http.StatusOK |
| + } |
| + w.Header().Set("Retry-After", "1") |
| + http.Error(w, "held", status) |
| + case r.URL.Path == "/trailer-holder": |
| + // X-Carlos-Holder after the body, beside an ordinary trailer: |
| + // announced in a Trailer header, or not (TrailerPrefix). |
| + announced := r.URL.Query().Get("announced") == "1" |
| + if announced { |
| + w.Header().Set("Trailer", "X-Kept, "+holderHeader) |
| + } |
| + io.WriteString(w, "trailed") |
| + w.(http.Flusher).Flush() |
| + prefix := "" |
| + if !announced { |
| + prefix = http.TrailerPrefix |
| + } |
| + w.Header().Set(prefix+"X-Kept", "1") |
| + w.Header().Set(prefix+holderHeader, "carol") |
| + case r.URL.Path == "/big": |
| + w.Header().Set("Content-Type", "text/html; charset=utf-8") |
| + io.WriteString(w, fwBigBody) |
| + case r.URL.Path == "/assets/held.js": |
| + a.heldRequests.Add(1) |
| + if a.first() { |
| + close(a.started) |
| + a.wait() |
| + } |
| + assetOK(fwAssetBody, "ETag", `"f1"`)(w, r) |
| + case strings.HasPrefix(r.URL.Path, "/assets/"): |
| + a.assetRequests.Add(1) |
| + assetOK(fwAssetBody, "ETag", `"f1"`)(w, r) |
| + default: |
| + fmt.Fprintf(w, "%s|%s|%s", box, r.Host, r.URL.Path) |
| + } |
| + })) |
| + t.Cleanup(a.srv.Close) |
| + return a |
| +} |
| + |
| +// fwScene is the armed two-edge scene: annie forwards, betty holds. |
| +type fwScene struct { |
| + *backhaulScene |
| + aAct, bAct *fwAct |
| + aApp, bApp *fwAppServer |
| + aMeter, bMeter *UsageMeter |
| + aObs, bObs *memAnalytics |
| + aRec, bRec *lockedRecorder |
| + aStore, bStore *assetcache.Store |
| + hash string |
| + // seen are the record and observation counts the last take returned up to. |
| + seen map[*lockedRecorder][2]int |
| + obs map[*memAnalytics]int |
| +} |
| + |
| +type fwOpts struct { |
| + // aAct replaces annie's forwarding fake (nil keeps it). |
| + aAct Activator |
| + // aTarget is the box annie's fake names ("" is betty). |
| + aTarget string |
| + // bettyLacks leaves betty without the HA hosts: in view, not serving. |
| + bettyLacks bool |
| +} |
| + |
| +func newFwScene(t *testing.T, o fwOpts) *fwScene { |
| + t.Helper() |
| + t.Setenv("CARLOS_RATE_LIMIT", "observe") |
| + t.Setenv("CARLOS_REGION_HA", "") |
| + hash, err := gate.Hash(fwPassword) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + x := &fwScene{ |
| + aAct: &fwAct{target: "betty"}, bAct: &fwAct{target: "annie"}, |
| + aApp: fwApp(t, "annie"), bApp: fwApp(t, "betty"), |
| + aMeter: NewUsageMeter(), bMeter: NewUsageMeter(), |
| + aObs: &memAnalytics{}, bObs: &memAnalytics{}, |
| + aRec: &lockedRecorder{}, bRec: &lockedRecorder{}, |
| + hash: hash, seen: map[*lockedRecorder][2]int{}, obs: map[*memAnalytics]int{}, |
| + } |
| + routes := func(addr string) []registry.Route { |
| + base := registry.Route{Kind: "instance", Hibernate: true, Addr: addr, Status: "ready", Account: "abc", App: "shop"} |
| + rs := make([]registry.Route, 0, len(fwHosts)) |
| + for _, h := range fwHosts { |
| + rt := base |
| + rt.Host = h |
| + switch h { |
| + case fwGatedHost: |
| + rt.Gate = hash |
| + case fwAssetHost: |
| + rt.AssetGen, rt.Version = laGen, laBuild |
| + case fwRateHost: |
| + rt.RateLimit = `{"rate":1,"burst":1}` |
| + } |
| + rs = append(rs, rt) |
| + } |
| + return rs |
| + } |
| + if o.aTarget != "" { |
| + x.aAct.target = o.aTarget |
| + } |
| + var aAct Activator = x.aAct |
| + if o.aAct != nil { |
| + aAct = o.aAct |
| + } |
| + extra := backhaulSceneExtra{ |
| + homeRoutes: routes(x.aApp.srv.Listener.Addr().String()), |
| + homeAct: aAct, |
| + farAct: x.bAct, |
| + certs: fwHosts, |
| + } |
| + if !o.bettyLacks { |
| + extra.farRoutes = routes(x.bApp.srv.Listener.Addr().String()) |
| + } |
| + x.backhaulScene = newBackhaulSceneWith(t, extra) |
| + for _, be := range []*backhaulEdge{x.a, x.b} { |
| + for _, h := range fwHosts { |
| + if h == fwLegacyHost { |
| + continue |
| + } |
| + if _, ok := be.edge.lookupUpstream(h); !ok { |
| + continue |
| + } |
| + if err := be.reg.SetHA(h); err != nil { |
| + t.Fatalf("SetHA %s: %v", h, err) |
| + } |
| + } |
| + if err := be.edge.Reload(); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + x.publishViewFiles(t, time.Now()) |
| + x.converge(t) |
| + fwDialTo(t, x.b.tlsAddr) |
| + |
| + x.aStore = openStoreAt(t, filepath.Join(t.TempDir(), "asset-cache")) |
| + x.bStore = openStoreAt(t, filepath.Join(t.TempDir(), "asset-cache")) |
| + for _, w := range []struct { |
| + be *backhaulEdge |
| + meter *UsageMeter |
| + obs *memAnalytics |
| + rec *lockedRecorder |
| + store *assetcache.Store |
| + }{{x.a, x.aMeter, x.aObs, x.aRec, x.aStore}, {x.b, x.bMeter, x.bObs, x.bRec, x.bStore}} { |
| + e := w.be.edge |
| + e.EnableCache(NewCache(DefaultCacheMaxEntries, DefaultCacheMaxBodyBytes)) |
| + e.EnableUsage(w.meter) |
| + e.EnableAnalytics(w.obs) |
| + e.SetAnalyticsOn(map[string]bool{"abc/shop": true}) |
| + e.EnableRequestRecords(w.rec) |
| + e.guard = guardWatch |
| + armForTest(t, e, w.store, &fakeLocalAssets{ |
| + hosts: map[string]HostAssets{fwAssetHost: {Account: "abc", App: "shop", Paths: []string{"/assets/"}, |
| + Gen: laGen, At: time.Now(), Primary: fwAssetHost}}, |
| + builds: map[string]bool{laBuild: true}, |
| + }) |
| + } |
| + return x |
| +} |
| + |
| +// publishViewFiles rewrites both boxes' edges files with the holder view's |
| +// fields: one region and placement, one data bucket and secrets key, written |
| +// at gen. |
| +func (x *fwScene) publishViewFiles(t *testing.T, gen time.Time) { |
| + t.Helper() |
| + for _, f := range []struct { |
| + box, eip string |
| + hosts []string |
| + }{{"annie", x.aEIP, []string{e2eHomedHost, e2eMovedHost}}, {"betty", x.bEIP, []string{e2eSenderHost}}} { |
| + parts := make([]string, 0, len(f.hosts)) |
| + for _, h := range f.hosts { |
| + parts = append(parts, fmt.Sprintf(`%q:{"role":"home"}`, h)) |
| + } |
| + putJSON(t, x.seed, "control/edges/"+f.box+".json", fmt.Sprintf( |
| + `{"v":1,"box":%q,"eip":%q,"region":"ie","placement":"p","generation":%q,"data_bucket":"bkt","secrets_key_fp":"fp","hosts":{%s}}`, |
| + f.box, f.eip, gen.UTC().Format(time.RFC3339), strings.Join(parts, ","))) |
| + } |
| +} |
| + |
| +// fwDialTo points every forward dial at addr for the test's lifetime. |
| +func fwDialTo(t *testing.T, addr string) { |
| + t.Helper() |
| + old := forwardDial |
| + forwardDial = func(ctx context.Context, network, _ string) (net.Conn, error) { |
| + var d net.Dialer |
| + return d.DialContext(ctx, network, addr) |
| + } |
| + t.Cleanup(func() { forwardDial = old }) |
| +} |
| + |
| +func (x *fwScene) fetch(t *testing.T, host, path string, hdr ...string) (*http.Response, string) { |
| + t.Helper() |
| + return x.do(t, http.MethodGet, host, path, hdr...) |
| +} |
| + |
| +// do is fetch with the method given, through annie's client. |
| +func (x *fwScene) do(t *testing.T, method, host, path string, hdr ...string) (*http.Response, string) { |
| + t.Helper() |
| + req, err := http.NewRequest(method, "https://"+host+path, nil) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + for k, v := range e2eHeaders(hdr) { |
| + req.Header.Set(k, v) |
| + } |
| + resp, err := x.a.client.Do(req) |
| + if err != nil { |
| + t.Fatalf("%s %s%s: %v", method, host, path, err) |
| + } |
| + b, err := io.ReadAll(resp.Body) |
| + resp.Body.Close() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return resp, string(b) |
| +} |
| + |
| +func (x *fwScene) fetchAsync(host, path string) <-chan e2eResult { |
| + ch := make(chan e2eResult, 1) |
| + go func() { |
| + resp, err := x.try(x.a, "https://"+host+path, e2eHeaders(nil), true) |
| + if err != nil { |
| + ch <- e2eResult{err: err} |
| + return |
| + } |
| + b, err := io.ReadAll(resp.Body) |
| + resp.Body.Close() |
| + ch <- e2eResult{resp: resp, body: string(b), err: err} |
| + }() |
| + return ch |
| +} |
| + |
| +// fwBox is what one box recorded for a host since the last take. |
| +type fwBox struct { |
| + use usage.EdgeRow |
| + obs []analytics.Obs |
| + resp []reqrec.Response |
| + match []reqrec.Match |
| +} |
| + |
| +// take waits for every handler on both boxes to return, then drains both |
| +// meters for host and returns each box's new observations and records. |
| +func (x *fwScene) take(t *testing.T, host string) (annie, betty fwBox) { |
| + t.Helper() |
| + laWaitFor(t, "both edges' handlers to return", func() bool { |
| + return x.a.served.Load() == x.a.calls.Load() && x.b.served.Load() == x.b.calls.Load() |
| + }) |
| + box := func(m *UsageMeter, obs *memAnalytics, rec *lockedRecorder) fwBox { |
| + var b fwBox |
| + b.use = m.Drain()[host] |
| + all := obs.snap() |
| + b.obs = all[x.obs[obs]:] |
| + x.obs[obs] = len(all) |
| + rec.mu.Lock() |
| + seen := x.seen[rec] |
| + b.resp = append([]reqrec.Response(nil), rec.resp[seen[0]:]...) |
| + b.match = append([]reqrec.Match(nil), rec.match[seen[1]:]...) |
| + x.seen[rec] = [2]int{len(rec.resp), len(rec.match)} |
| + rec.mu.Unlock() |
| + return b |
| + } |
| + return box(x.aMeter, x.aObs, x.aRec), box(x.bMeter, x.bObs, x.bRec) |
| +} |
| + |
| +// wantNothing: the box recorded nothing at all. |
| +func wantNothing(t *testing.T, step string, b fwBox) { |
| + t.Helper() |
| + if b.use.Requests != 0 || b.use.BytesOut != 0 || b.use.RateCeiling != 0 || b.use.RateShed != 0 || |
| + len(b.obs) != 0 || len(b.resp) != 0 || len(b.match) != 0 { |
| + t.Fatalf("%s: the forwarding box recorded usage %+v, %d observations, %d responses, %d matches; want nothing", |
| + step, b.use, len(b.obs), len(b.resp), len(b.match)) |
| + } |
| +} |
| + |
| +// wantOneDelivery: the box recorded one request of n bytes, as a hop, in |
| +// usage, analytics and one response record of status. |
| +func wantOneDelivery(t *testing.T, step string, b fwBox, n int, status int) { |
| + t.Helper() |
| + if b.use.Requests != 1 || b.use.BytesOut != int64(n) || b.use.HopRequests != 1 { |
| + t.Fatalf("%s: the holder metered %+v, want one hop request of %d bytes", step, b.use, n) |
| + } |
| + if len(b.obs) != 1 || b.obs[0].Bytes != int64(n) || b.obs[0].Status != status { |
| + t.Fatalf("%s: the holder observed %+v, want one observation of %d bytes, status %d", step, b.obs, n, status) |
| + } |
| + if len(b.resp) != 1 || b.resp[0].Status != status || len(b.match) != 0 { |
| + t.Fatalf("%s: the holder recorded responses %+v matches %+v, want one response %d", step, b.resp, b.match, status) |
| + } |
| +} |
| + |
| +func (x *fwScene) wantNote(t *testing.T, want ...fwNote) { |
| + t.Helper() |
| + got := x.aAct.noted() |
| + if len(got) != len(want) { |
| + t.Fatalf("notes = %+v, want %+v", got, want) |
| + } |
| + for i := range want { |
| + if got[i] != want[i] { |
| + t.Fatalf("note %d = %+v, want %+v", i, got[i], want[i]) |
| + } |
| + } |
| +} |
| + |
| +// ---- the forward ------------------------------------------------------------- |
| + |
| +func TestFrontForwardReachesTheHolder(t *testing.T) { |
| + x := newFwScene(t, fwOpts{}) |
| + resp, body := x.fetch(t, fwHost, "/deep?q=1") |
| + if resp.StatusCode != http.StatusOK || body != "betty|"+fwHost+"|/deep" { |
| + t.Fatalf("GET = %d %q, want betty's 200", resp.StatusCode, body) |
| + } |
| + annie, betty := x.take(t, fwHost) |
| + wantNothing(t, "a forward", annie) |
| + // Metered as a hop: betty saw a verified one. |
| + wantOneDelivery(t, "a forward", betty, len(body), http.StatusOK) |
| + if n := x.aApp.n.Load(); n != 0 { |
| + t.Fatalf("annie's app saw %d requests", n) |
| + } |
| + if got := x.aAct.asked.Load(); got != 1 { |
| + t.Fatalf("annie asked its activator %d times, want 1", got) |
| + } |
| + // One hop: betty never asks where to send a hop. |
| + if got := x.bAct.asked.Load(); got != 0 { |
| + t.Fatalf("betty asked its activator %d times for a hop, want 0", got) |
| + } |
| + x.wantNote(t, fwNote{fwHost, ForwardResult{Outcome: ForwardDone, Status: http.StatusOK}}) |
| +} |
| + |
| +func TestFrontForwardRunsNoLocalStep(t *testing.T) { |
| + x := newFwScene(t, fwOpts{}) |
| + |
| + t.Run("a gate", func(t *testing.T) { |
| + cookie := gate.CookieName + "=" + gate.Mint(fwGatedHost, x.hash, time.Now().Add(time.Hour)) |
| + resp, body := x.fetch(t, fwGatedHost, "/in", "Cookie", cookie) |
| + if resp.StatusCode != http.StatusOK || body != "betty|"+fwGatedHost+"|/in" { |
| + t.Fatalf("with the cookie = %d %q, want betty's 200", resp.StatusCode, body) |
| + } |
| + annie, betty := x.take(t, fwGatedHost) |
| + wantNothing(t, "a gated pass", annie) |
| + wantOneDelivery(t, "a gated pass", betty, len(body), http.StatusOK) |
| + |
| + calls := x.b.calls.Load() |
| + resp, body = x.fetch(t, fwGatedHost, "/in") |
| + if resp.StatusCode != http.StatusUnauthorized || !strings.Contains(body, gate.LoginPath) { |
| + t.Fatalf("without the cookie = %d %q, want the login page", resp.StatusCode, body) |
| + } |
| + if got := x.b.calls.Load() - calls; got != 1 { |
| + t.Fatalf("betty saw %d requests for the refusal, want 1: annie's gate answered", got) |
| + } |
| + annie, betty = x.take(t, fwGatedHost) |
| + wantNothing(t, "a gated refusal", annie) |
| + wantOneDelivery(t, "a gated refusal", betty, len(body), http.StatusUnauthorized) |
| + }) |
| + |
| + t.Run("b assets", func(t *testing.T) { |
| + step := func(name, method, path string, wantStatus int, hdr ...string) *http.Response { |
| + t.Helper() |
| + resp, body := x.do(t, method, fwAssetHost, path, hdr...) |
| + if resp.StatusCode != wantStatus { |
| + t.Fatalf("%s = %d %q, want %d", name, resp.StatusCode, body, wantStatus) |
| + } |
| + if method == http.MethodHead && body != "" { |
| + t.Fatalf("HEAD body = %q, want none", body) |
| + } |
| + annie, betty := x.take(t, fwAssetHost) |
| + wantNothing(t, name, annie) |
| + wantOneDelivery(t, name, betty, len(body), wantStatus) |
| + if got := betty.obs[0].Method; got != method { |
| + t.Fatalf("%s: the holder observed a %s", name, got) |
| + } |
| + return resp |
| + } |
| + // Carlos-Cache does not cross a hop (scrubBackhaulResponse), so the |
| + // catch is read off betty's store and app. |
| + get := step("GET", http.MethodGet, "/assets/app.js", http.StatusOK) |
| + appKey := assetcache.Key{Account: "abc", App: "shop", Gen: laGen, Host: fwAssetHost, Path: "/assets/app.js"} |
| + if _, ok := x.bStore.Get(appKey); !ok { |
| + t.Fatal("betty's asset cache did not catch the GET") |
| + } |
| + step("HEAD", http.MethodHead, "/assets/app.js", http.StatusOK) |
| + step("range", http.MethodGet, "/assets/app.js", http.StatusPartialContent, "Range", "bytes=0-4") |
| + step("conditional", http.MethodGet, "/assets/app.js", http.StatusNotModified, "If-None-Match", get.Header.Get("ETag")) |
| + if n := x.bApp.assetRequests.Load(); n != 1 { |
| + t.Fatalf("betty's app saw %d asset requests, want the one fill", n) |
| + } |
| + |
| + // Two coalesced GETs: the second waits on betty's fill. |
| + lead := x.fetchAsync(fwAssetHost, "/assets/held.js") |
| + e2eStarted(t, x.bApp.started, lead) |
| + rest := x.fetchAsync(fwAssetHost, "/assets/held.js") |
| + key := assetcache.Key{Account: "abc", App: "shop", Gen: laGen, Host: fwAssetHost, Path: "/assets/held.js"} |
| + laWaitFor(t, "the second GET to join betty's fill", func() bool { return flightWaitersOf(x.b.edge, key.ID()) == 1 }) |
| + x.bApp.release() |
| + for _, ch := range []<-chan e2eResult{lead, rest} { |
| + if r := e2eAwait(t, ch); r.resp.StatusCode != http.StatusOK || r.body != fwAssetBody { |
| + t.Fatalf("coalesced GET = %d %q", r.resp.StatusCode, r.body) |
| + } |
| + } |
| + annie, betty := x.take(t, fwAssetHost) |
| + wantNothing(t, "coalesced", annie) |
| + if betty.use.Requests != 2 || betty.use.BytesOut != int64(2*len(fwAssetBody)) || len(betty.obs) != 2 || len(betty.resp) != 2 { |
| + t.Fatalf("coalesced: the holder metered %+v, %d observations, %d records; want two of %d bytes each", |
| + betty.use, len(betty.obs), len(betty.resp), len(fwAssetBody)) |
| + } |
| + if n := x.bApp.heldRequests.Load(); n != 1 { |
| + t.Fatalf("betty's app saw %d requests for the coalesced path, want one fill", n) |
| + } |
| + |
| + // Annie filled nothing and asked its app nothing. |
| + if s := x.aStore.Stats(); s.Entries != 0 || s.Reserved != 0 { |
| + t.Fatalf("annie's asset store holds %+v", s) |
| + } |
| + if n := x.aApp.n.Load(); n != 0 { |
| + t.Fatalf("annie's app saw %d requests", n) |
| + } |
| + if s := x.bStore.Stats(); s.Entries != 2 { |
| + t.Fatalf("betty's asset store holds %+v, want the two paths", s) |
| + } |
| + }) |
| + |
| + t.Run("c guard and not found", func(t *testing.T) { |
| + resp, body := x.fetch(t, fwHost, "/.env") |
| + if resp.StatusCode != http.StatusOK || !strings.HasPrefix(body, "betty|") { |
| + t.Fatalf("watched = %d %q, want betty's 200", resp.StatusCode, body) |
| + } |
| + annie, betty := x.take(t, fwHost) |
| + wantNothing(t, "watched", annie) |
| + if len(betty.match) != 1 || betty.match[0].Kind != reqrec.KindWatch || len(betty.resp) != 0 { |
| + t.Fatalf("watched: the holder recorded matches %+v responses %+v, want one watch match", betty.match, betty.resp) |
| + } |
| + |
| + resp, body = x.fetch(t, fwHost, "/missing") |
| + if resp.StatusCode != http.StatusNotFound { |
| + t.Fatalf("missing = %d %q, want 404", resp.StatusCode, body) |
| + } |
| + annie, betty = x.take(t, fwHost) |
| + wantNothing(t, "not found", annie) |
| + wantOneDelivery(t, "not found", betty, len(body), http.StatusNotFound) |
| + }) |
| + |
| + t.Run("d rate limit observed", func(t *testing.T) { |
| + x.fetch(t, fwRateHost, "/") // spends the backstop's one token, at betty |
| + x.take(t, fwRateHost) |
| + for i := range 3 { |
| + if resp, _ := x.fetch(t, fwRateHost, "/"); resp.StatusCode != http.StatusOK { |
| + t.Fatalf("request %d = %d, want observe mode to serve", i, resp.StatusCode) |
| + } |
| + annie, betty := x.take(t, fwRateHost) |
| + wantNothing(t, fmt.Sprintf("rate %d", i), annie) |
| + if betty.use.RateCeiling != 1 || betty.use.Requests != 1 { |
| + t.Fatalf("rate %d: the holder counted %+v, want one request over the backstop", i, betty.use) |
| + } |
| + } |
| + if n := x.aApp.n.Load(); n != 0 { |
| + t.Fatalf("annie's app saw %d requests", n) |
| + } |
| + }) |
| +} |
| + |
| +func TestForwardHAHolderLostHost(t *testing.T) { |
| + x := newFwScene(t, fwOpts{bettyLacks: true}) |
| + resp, body := x.fetch(t, fwHost, "/") |
| + if resp.StatusCode != http.StatusServiceUnavailable || resp.Header.Get("Retry-After") != "2" { |
| + t.Fatalf("GET = %d Retry-After %q %q, want betty's no-route 503", resp.StatusCode, resp.Header.Get("Retry-After"), body) |
| + } |
| + if v := resp.Header.Values(holderHeader); len(v) != 0 { |
| + t.Fatalf("%s = %q, want none", holderHeader, v) |
| + } |
| + x.wantNote(t, fwNote{fwHost, ForwardResult{Outcome: ForwardDone, Status: http.StatusServiceUnavailable}}) |
| + if n := x.aApp.n.Load(); n != 0 { |
| + t.Fatalf("annie's app saw %d requests", n) |
| + } |
| +} |
| + |
| +func TestFrontForwardSkips(t *testing.T) { |
| + x := newFwScene(t, fwOpts{}) |
| + local := func(t *testing.T, host, body string) { |
| + t.Helper() |
| + if !strings.HasPrefix(body, "annie|"+host+"|") { |
| + t.Fatalf("%s: body %q, want annie's own app", host, body) |
| + } |
| + } |
| + wantNotAsked := func(t *testing.T) { |
| + t.Helper() |
| + if n := x.aAct.asked.Load(); n != 0 { |
| + t.Fatalf("the activator was asked %d times", n) |
| + } |
| + if notes := x.aAct.noted(); len(notes) != 0 { |
| + t.Fatalf("notes = %+v", notes) |
| + } |
| + } |
| + direct := func(t *testing.T, r *http.Request, up upstream, hopped, isDoor bool) { |
| + t.Helper() |
| + rec := httptest.NewRecorder() |
| + if x.a.edge.frontForwardHA(rec, r, fwHost, up, hopped, isDoor) { |
| + t.Fatal("frontForwardHA answered") |
| + } |
| + if rec.Code != http.StatusOK || rec.Body.Len() != 0 || len(rec.Header()) != 0 { |
| + t.Fatalf("frontForwardHA wrote %d %q %v", rec.Code, rec.Body.String(), rec.Header()) |
| + } |
| + } |
| + haUp, ok := x.a.edge.lookupUpstream(fwHost) |
| + if !ok || !haUp.route.HA || !haUp.hibernating || haUp.regional != regionalNone { |
| + t.Fatalf("test bug: %s is not a local HA activator route: %+v", fwHost, haUp) |
| + } |
| + newReq := func() *http.Request { |
| + r := httptest.NewRequest(http.MethodGet, "https://"+fwHost+"/", nil) |
| + r.RemoteAddr = "203.0.113.9:4000" |
| + return r |
| + } |
| + |
| + t.Run("verified hop", func(t *testing.T) { |
| + resp, body := x.fetch(t, fwHost, "/hop", hopHeader, "1", hopAuthHeader, signHop(x.key, fwHost, time.Now())) |
| + if resp.StatusCode != http.StatusOK { |
| + t.Fatalf("hop = %d %q", resp.StatusCode, body) |
| + } |
| + local(t, fwHost, body) |
| + r := newReq() |
| + direct(t, r.WithContext(withHopVerified(r.Context())), haUp, false, false) |
| + direct(t, newReq(), haUp, true, false) |
| + wantNotAsked(t) |
| + }) |
| + t.Run("door call", func(t *testing.T) { |
| + r := newReq() |
| + r = r.WithContext(context.WithValue(r.Context(), doorCallerKey{}, doorCaller{Account: "abc", App: "shop"})) |
| + rec := httptest.NewRecorder() |
| + x.a.edge.ServeHTTP(rec, r) |
| + if rec.Code != http.StatusOK { |
| + t.Fatalf("door call = %d %q", rec.Code, rec.Body.String()) |
| + } |
| + local(t, fwHost, rec.Body.String()) |
| + direct(t, newReq(), haUp, false, true) |
| + wantNotAsked(t) |
| + }) |
| + t.Run("from a tunnel", func(t *testing.T) { |
| + old := fromTunnel |
| + fromTunnel = func(context.Context) bool { return true } |
| + defer func() { fromTunnel = old }() |
| + direct(t, newReq(), haUp, false, false) |
| + wantNotAsked(t) |
| + }) |
| + t.Run("regional name", func(t *testing.T) { |
| + for _, mode := range []regionalMode{regionalServe, regionalDeny} { |
| + up := haUp |
| + up.regional = mode |
| + direct(t, newReq(), up, false, false) |
| + } |
| + wantNotAsked(t) |
| + }) |
| + t.Run("not HA", func(t *testing.T) { |
| + _, body := x.fetch(t, fwLegacyHost, "/") |
| + local(t, fwLegacyHost, body) |
| + up := haUp |
| + up.route.HA = false |
| + direct(t, newReq(), up, false, false) |
| + wantNotAsked(t) |
| + }) |
| + t.Run("not activator-managed", func(t *testing.T) { |
| + if err := x.a.reg.SetHA(e2eHomedHost); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := x.a.edge.Reload(); err != nil { |
| + t.Fatal(err) |
| + } |
| + if up, ok := x.a.edge.lookupUpstream(e2eHomedHost); !ok || !up.route.HA || up.hibernating { |
| + t.Fatalf("test bug: %s is not an HA service route: %+v", e2eHomedHost, up) |
| + } |
| + resp, body := x.fetch(t, e2eHomedHost, "/") |
| + if resp.StatusCode != http.StatusOK || e2eParseApp(t, body).marker != e2eHomeMarker { |
| + t.Fatalf("service = %d %q, want annie's own", resp.StatusCode, body) |
| + } |
| + up := haUp |
| + up.hibernating = false |
| + direct(t, newReq(), up, false, false) |
| + wantNotAsked(t) |
| + }) |
| + t.Run("an activator without the interface", func(t *testing.T) { |
| + y := newFwScene(t, fwOpts{aAct: fwPlainAct{}}) |
| + calls := y.b.calls.Load() |
| + _, body := y.fetch(t, fwHost, "/") |
| + local(t, fwHost, body) |
| + if n := y.b.calls.Load() - calls; n != 0 { |
| + t.Fatalf("betty saw %d requests", n) |
| + } |
| + }) |
| + if n := x.bApp.n.Load(); n != 0 { |
| + t.Fatalf("betty's app saw %d requests", n) |
| + } |
| +} |
| + |
| +func TestForwardHANotInView(t *testing.T) { |
| + x := newFwScene(t, fwOpts{aTarget: "carol"}) |
| + if err := x.seed.Delete(context.Background(), "control/edges/carol.json"); err != nil { |
| + t.Fatal(err) |
| + } |
| + x.converge(t) |
| + if _, ok := x.a.homes.boxInView("carol", time.Now()); ok { |
| + t.Fatal("test bug: carol is in view") |
| + } |
| + calls := x.b.calls.Load() |
| + resp, body := x.fetch(t, fwHost, "/") |
| + if resp.StatusCode != http.StatusOK || !strings.HasPrefix(body, "annie|") { |
| + t.Fatalf("GET = %d %q, want annie's own 200", resp.StatusCode, body) |
| + } |
| + if n := x.b.calls.Load() - calls; n != 0 { |
| + t.Fatalf("betty saw %d requests", n) |
| + } |
| + x.wantNote(t, fwNote{fwHost, ForwardResult{Outcome: ForwardNotInView}}) |
| + // Served here, it is recorded here. |
| + annie, _ := x.take(t, fwHost) |
| + if annie.use.Requests != 1 || annie.use.HopRequests != 0 { |
| + t.Fatalf("annie metered %+v, want its own one request", annie.use) |
| + } |
| +} |
| + |
| +func TestForwardHADialFailureIs503RetryTen(t *testing.T) { |
| + stall := func(t *testing.T) { |
| + t.Helper() |
| + old := forwardDial |
| + forwardDial = func(ctx context.Context, _, _ string) (net.Conn, error) { |
| + <-ctx.Done() |
| + return nil, ctx.Err() |
| + } |
| + t.Cleanup(func() { forwardDial = old }) |
| + } |
| + forward := func(t *testing.T, x *fwScene) { |
| + t.Helper() |
| + start := time.Now() |
| + resp, body := x.fetch(t, fwHost, "/") |
| + took := time.Since(start) |
| + if resp.StatusCode != http.StatusServiceUnavailable || resp.Header.Get("Retry-After") != "10" || |
| + body != "instance is waking elsewhere; retry shortly\n" { |
| + t.Fatalf("GET = %d Retry-After %q %q, want the unreachable 503", resp.StatusCode, resp.Header.Get("Retry-After"), body) |
| + } |
| + if took < forwardDialTimeout-100*time.Millisecond || took >= backhaulDialTimeout { |
| + t.Fatalf("the unreachable answer took %v, want about %v", took, forwardDialTimeout) |
| + } |
| + notes := x.aAct.noted() |
| + if len(notes) == 0 || notes[len(notes)-1] != (fwNote{fwHost, ForwardResult{Outcome: ForwardUnreachable}}) { |
| + t.Fatalf("notes = %+v, want ForwardUnreachable last", notes) |
| + } |
| + if n := x.bApp.n.Load(); n != 0 { |
| + t.Fatalf("betty's app saw %d requests", n) |
| + } |
| + } |
| + // backhaulTo the same address: every box here is dialled on annie's |
| + // port, so the hop lands on annie, which serves it itself (a verified |
| + // hop is never forwarded). It succeeds whatever the forward's dial seam |
| + // does, because it dials through its own 5 s transport. |
| + backhaul := func(t *testing.T, x *fwScene) { |
| + t.Helper() |
| + dial, ok := x.a.homes.boxInView("betty", time.Now()) |
| + if !ok { |
| + t.Fatal("test bug: betty is out of view") |
| + } |
| + r := httptest.NewRequest(http.MethodGet, "https://"+fwHost+"/hopped", nil) |
| + r.RemoteAddr = "203.0.113.9:4000" |
| + rec := httptest.NewRecorder() |
| + if !x.a.edge.backhaulTo(rec, r, fwHost, dial, "betty") { |
| + t.Fatal("backhaulTo did not answer") |
| + } |
| + if rec.Code != http.StatusOK || rec.Body.String() != "annie|"+fwHost+"|/hopped" { |
| + t.Fatalf("backhaulTo = %d %q, want the hop served", rec.Code, rec.Body.String()) |
| + } |
| + bt, ok := x.a.edge.backhaulTransports.Load(dial) |
| + if !ok || bt.(*http.Transport).TLSHandshakeTimeout != backhaulDialTimeout { |
| + t.Fatalf("backhaul transport for %s = %v, want its 5 s one", dial, bt) |
| + } |
| + } |
| + wantTwoTransports := func(t *testing.T, x *fwScene) { |
| + t.Helper() |
| + dial, _ := x.a.homes.boxInView("betty", time.Now()) |
| + bt, _ := x.a.edge.backhaulTransports.Load(dial) |
| + ft, ok := x.a.edge.forwardTransports.Load(dial) |
| + if !ok || ft == bt { |
| + t.Fatalf("forward transport %v, backhaul transport %v: want two", ft, bt) |
| + } |
| + } |
| + t.Run("forward then backhaul", func(t *testing.T) { |
| + x := newFwScene(t, fwOpts{}) |
| + stall(t) |
| + forward(t, x) |
| + backhaul(t, x) |
| + wantTwoTransports(t, x) |
| + }) |
| + t.Run("backhaul then forward", func(t *testing.T) { |
| + x := newFwScene(t, fwOpts{}) |
| + stall(t) |
| + backhaul(t, x) |
| + forward(t, x) |
| + wantTwoTransports(t, x) |
| + }) |
| +} |
| + |
| +func TestForwardHAReadsHolderHeader(t *testing.T) { |
| + x := newFwScene(t, fwOpts{}) |
| + n := 0 |
| + note := func(t *testing.T, want ForwardResult) { |
| + t.Helper() |
| + n++ |
| + notes := x.aAct.noted() |
| + if len(notes) != n || notes[n-1] != (fwNote{fwHost, want}) { |
| + t.Fatalf("notes = %+v, want %+v last", notes, want) |
| + } |
| + } |
| + // The platform's refusal on the holder keeps its header, to the client |
| + // and to the note. |
| + for _, ref := range []string{"carol", "none"} { |
| + resp, _ := x.fetch(t, fwHost, "/platform-held?ref="+ref) |
| + if resp.StatusCode != http.StatusServiceUnavailable || resp.Header.Get(holderHeader) != ref { |
| + t.Fatalf("platform refusal = %d %s %q, want betty's 503 naming %s", resp.StatusCode, holderHeader, resp.Header.Get(holderHeader), ref) |
| + } |
| + note(t, ForwardResult{Outcome: ForwardDone, Status: http.StatusServiceUnavailable, Holder: ref}) |
| + } |
| + // An app's own X-Carlos-Holder never leaves the holder: not to the |
| + // client, not into the note. |
| + for _, tc := range []struct { |
| + query string |
| + status int |
| + }{{"ref=carol", http.StatusServiceUnavailable}, {"ref=none&status=200", http.StatusOK}} { |
| + resp, body := x.fetch(t, fwHost, "/holder?"+tc.query) |
| + if resp.StatusCode != tc.status || body != "held\n" { |
| + t.Fatalf("app %s = %d %q, want the app's %d", tc.query, resp.StatusCode, body, tc.status) |
| + } |
| + if v := resp.Header.Values(holderHeader); len(v) != 0 { |
| + t.Fatalf("app %s: the client received %s %q", tc.query, holderHeader, v) |
| + } |
| + note(t, ForwardResult{Outcome: ForwardDone, Status: tc.status}) |
| + } |
| +} |
| + |
| +// An app's X-Carlos-Holder sent as a trailer, announced or not, never |
| +// reaches the client and never names a holder; the app's other trailers do. |
| +func TestForwardHAAppHolderTrailerNeverReachesTheClient(t *testing.T) { |
| + x := newFwScene(t, fwOpts{}) |
| + for i, announced := range []string{"1", "0"} { |
| + resp, body := x.fetch(t, fwHost, "/trailer-holder?announced="+announced) |
| + if resp.StatusCode != http.StatusOK || body != "trailed" { |
| + t.Fatalf("announced=%s: %d %q", announced, resp.StatusCode, body) |
| + } |
| + if _, ok := resp.Trailer[holderHeader]; ok { |
| + t.Fatalf("announced=%s: the client received the %s trailer: %v", announced, holderHeader, resp.Trailer) |
| + } |
| + for _, v := range resp.Header.Values("Trailer") { |
| + if strings.Contains(strings.ToLower(v), strings.ToLower(holderHeader)) { |
| + t.Fatalf("announced=%s: the response announces %s: %q", announced, holderHeader, v) |
| + } |
| + } |
| + if v := resp.Header.Values(holderHeader); len(v) != 0 { |
| + t.Fatalf("announced=%s: the client received the %s header %q", announced, holderHeader, v) |
| + } |
| + if got := resp.Trailer.Get("X-Kept"); got != "1" { |
| + t.Fatalf("announced=%s: X-Kept trailer = %q, want 1 (trailers %v): trailers must still cross", announced, got, resp.Trailer) |
| + } |
| + notes := x.aAct.noted() |
| + if len(notes) != i+1 || notes[i] != (fwNote{fwHost, ForwardResult{Outcome: ForwardDone, Status: http.StatusOK}}) { |
| + t.Fatalf("notes = %+v, want ForwardDone 200 with no holder", notes) |
| + } |
| + } |
| +} |
| + |
| +// The forward relays the encoding the client asked for, so the bytes the |
| +// holder meters are the bytes the client receives: a client that asks for |
| +// no compression gets identity bytes from both boxes. |
| +func TestForwardHAHolderMetersTheBytesDelivered(t *testing.T) { |
| + x := newFwScene(t, fwOpts{}) |
| + tr := x.a.client.Transport.(*http.Transport).Clone() |
| + tr.DisableCompression = true |
| + client := &http.Client{Timeout: 30 * time.Second, Transport: tr} |
| + req, err := http.NewRequest(http.MethodGet, "https://"+fwHost+"/big", nil) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + resp, err := client.Do(req) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + b, err := io.ReadAll(resp.Body) |
| + resp.Body.Close() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if resp.StatusCode != http.StatusOK || string(b) != fwBigBody || resp.Header.Get("Content-Encoding") != "" { |
| + t.Fatalf("GET = %d, %d bytes, Content-Encoding %q; want the identity page", resp.StatusCode, len(b), resp.Header.Get("Content-Encoding")) |
| + } |
| + annie, betty := x.take(t, fwHost) |
| + wantNothing(t, "a large page", annie) |
| + wantOneDelivery(t, "a large page", betty, len(b), http.StatusOK) |
| +} |
| + |
| +func TestForwardHAUpgradeSwitchesProtocols(t *testing.T) { |
| + x := newFwScene(t, fwOpts{}) |
| + raw, err := net.DialTimeout("tcp", x.a.tlsAddr, 10*time.Second) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + c := tls.Client(raw, &tls.Config{ServerName: fwHost, RootCAs: x.ca.pool, MinVersion: tls.VersionTLS12}) |
| + defer c.Close() |
| + c.SetDeadline(time.Now().Add(10 * time.Second)) |
| + fmt.Fprintf(c, "GET /socket HTTP/1.1\r\nHost: %s\r\nConnection: Upgrade\r\nUpgrade: websocket\r\n\r\n", fwHost) |
| + br := bufio.NewReader(c) |
| + resp, err := http.ReadResponse(br, nil) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if resp.StatusCode != http.StatusSwitchingProtocols { |
| + t.Fatalf("handshake = %d, want 101", resp.StatusCode) |
| + } |
| + fmt.Fprint(c, "ping\n") |
| + if line, err := br.ReadString('\n'); err != nil || line != "betty:ping\n" { |
| + t.Fatalf("echo = %q %v, want betty's", line, err) |
| + } |
| + c.Close() |
| + laWaitFor(t, "the forward's note", func() bool { return len(x.aAct.noted()) == 1 }) |
| + x.wantNote(t, fwNote{fwHost, ForwardResult{Outcome: ForwardDone, Status: http.StatusSwitchingProtocols}}) |
| +} |
diff --git a/internal/edge/holderview.go b/internal/edge/holderview.go| new file mode 100644 |
| index 000000000..204bcabdf |
| --- /dev/null |
| +++ b/internal/edge/holderview.go |
| @@ -0,0 +1,59 @@ |
| +package edge |
| + |
| +import ( |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/edgesfile" |
| +) |
| + |
| +// boxInView reports whether the box labelled ref is a valid forward target for |
| +// this box at now, and the address to dial it at. |
| +// |
| +// "In view" is the edge's half of region HA forwarding: ref is another box in |
| +// this box's own region and placement, writing to the same data store with the |
| +// same secrets key. The test is made on the fold's own files, so it needs no |
| +// request to the bucket. It does not age the file: a file's generation moves |
| +// only when the file is rewritten, and the writer skips unchanged rewrites, so |
| +// a healthy box's generation is arbitrarily old. Liveness comes from the |
| +// caller, which names a holder only by an unexpired lease or the platform's |
| +// header, and drops one that fails the dial. Every rule fails closed: a file this build cannot read a field from |
| +// is out of view, and with no file of this box's own there is nothing to |
| +// compare against, so nothing is in view. |
| +// |
| +// - ref is not this box (a box never forwards to itself); |
| +// - its region and placement equal this box's own file's; |
| +// - its data bucket is non-empty and equals this box's; |
| +// - its secrets key fingerprint equals this box's. Both empty is equal: a |
| +// deployment with no key. One empty is a mismatch. |
| +// |
| +// dial is edgesfile.Reader.Dial for the file, built as foldHomes builds its |
| +// reader: this box's own file as Self and this edge's region HA switch. A box |
| +// whose file offers no dialable address is out. now is unused; the signature |
| +// is the one the forwarding callers are written against. |
| +func (m *homeMap) boxInView(ref string, now time.Time) (dial string, ok bool) { |
| + if ref == "" || m.self == "" || ref == m.self { |
| + return "", false |
| + } |
| + var own, peer edgesFileView |
| + ownKnown, peerKnown := false, false |
| + for _, f := range m.snapshot().files { |
| + switch f.Box { |
| + case m.self: |
| + own, ownKnown = f, true |
| + case ref: |
| + peer, peerKnown = f, true |
| + } |
| + } |
| + if !ownKnown || !peerKnown { |
| + return "", false |
| + } |
| + if peer.Region != own.Region || peer.Placement != own.Placement { |
| + return "", false |
| + } |
| + if peer.DataBucket == "" || peer.DataBucket != own.DataBucket || peer.SecretsKeyFP != own.SecretsKeyFP { |
| + return "", false |
| + } |
| + reader := edgesfile.Reader{Box: m.self, Self: own.dialPoint(), SelfKnown: true, PrivateDial: m.privateDial} |
| + dial = reader.Dial(peer.dialPoint()) |
| + return dial, dial != "" |
| +} |
diff --git a/internal/edge/holderview_test.go b/internal/edge/holderview_test.go| new file mode 100644 |
| index 000000000..0f2de8d66 |
| --- /dev/null |
| +++ b/internal/edge/holderview_test.go |
| @@ -0,0 +1,135 @@ |
| +package edge |
| + |
| +import ( |
| + "encoding/json" |
| + "fmt" |
| + "net/http/httptest" |
| + "testing" |
| + "time" |
| +) |
| + |
| +// viewFile is one edges file body for the holder view tests. gen is an RFC 3339 |
| +// generation; the dial fields are the same EIP and private address for every |
| +// box so the dial is the only thing a case reads off the address. |
| +func viewFile(box, region, placement string, gen time.Time, bucket, fp string) string { |
| + return fmt.Sprintf(`{"v":1,"box":%q,"eip":"9.9.9.%d","private_ip":"10.0.1.%d","private_cidr":"10.0.0.0/16","region":%q,"placement":%q,"generation":%q,"data_bucket":%q,"secrets_key_fp":%q,"hosts":{}}`, |
| + box, len(box), len(box), region, placement, gen.UTC().Format(time.RFC3339), bucket, fp) |
| +} |
| + |
| +// boxOf is the box label a test file body carries. |
| +func boxOf(t *testing.T, body string) string { |
| + t.Helper() |
| + var f edgesFileView |
| + if err := json.Unmarshal([]byte(body), &f); err != nil { |
| + t.Fatal(err) |
| + } |
| + return f.Box |
| +} |
| + |
| +func TestHolderViewRules(t *testing.T) { |
| + now := time.Date(2026, 10, 30, 12, 0, 0, 0, time.UTC) |
| + type peer struct { |
| + name string |
| + body string |
| + in bool |
| + } |
| + own := viewFile("a", "ie", "p", now, "bkt", "fp1") |
| + peers := []peer{ |
| + {"fresh", viewFile("b", "ie", "p", now.Add(-time.Minute), "bkt", "fp1"), true}, |
| + // A generation moves only when the file is rewritten, so a healthy |
| + // box's is arbitrarily old: the view does not age files. |
| + {"old", viewFile("c", "ie", "p", now.Add(-12*time.Hour), "bkt", "fp1"), true}, |
| + {"region", viewFile("e", "uk", "p", now, "bkt", "fp1"), false}, |
| + {"placement", viewFile("f", "ie", "q", now, "bkt", "fp1"), false}, |
| + {"nobucket", viewFile("g", "ie", "p", now, "", "fp1"), false}, |
| + {"bucket", viewFile("h", "ie", "p", now, "other", "fp1"), false}, |
| + {"fp", viewFile("i", "ie", "p", now, "bkt", "fp2"), false}, |
| + {"emptyfp", viewFile("j", "ie", "p", now, "bkt", ""), false}, |
| + {"nogen", `{"v":1,"box":"k","eip":"1.2.3.4","region":"ie","placement":"p","data_bucket":"bkt","secrets_key_fp":"fp1","hosts":{}}`, true}, |
| + {"badgen", `{"v":1,"box":"l","eip":"1.2.3.4","region":"ie","placement":"p","generation":"yesterday","data_bucket":"bkt","secrets_key_fp":"fp1","hosts":{}}`, true}, |
| + } |
| + s := meshTestStore(t) |
| + putJSON(t, s, "control/edges/a.json", own) |
| + for _, p := range peers { |
| + putJSON(t, s, "control/edges/"+p.name+".json", p.body) |
| + } |
| + m := newHomeMap(s, "a") |
| + refreshHomeMap(t, m) |
| + for _, p := range peers { |
| + _, ok := m.boxInView(boxOf(t, p.body), now) |
| + if ok != p.in { |
| + t.Errorf("%s: in view = %v, want %v", p.name, ok, p.in) |
| + } |
| + } |
| + if _, ok := m.boxInView("a", now); ok { |
| + t.Error("this box is in its own view") |
| + } |
| + if _, ok := m.boxInView("nobody", now); ok { |
| + t.Error("an unknown box is in view") |
| + } |
| + if _, ok := m.boxInView("", now); ok { |
| + t.Error("the empty label is in view") |
| + } |
| + |
| + // Both empty secrets fingerprints are equal. |
| + s2 := meshTestStore(t) |
| + putJSON(t, s2, "control/edges/a.json", viewFile("a", "ie", "p", now, "bkt", "")) |
| + putJSON(t, s2, "control/edges/b.json", viewFile("b", "ie", "p", now, "bkt", "")) |
| + putJSON(t, s2, "control/edges/c.json", viewFile("c", "ie", "p", now, "bkt", "fp1")) |
| + m2 := newHomeMap(s2, "a") |
| + refreshHomeMap(t, m2) |
| + if _, ok := m2.boxInView("b", now); !ok { |
| + t.Error("both fingerprints empty is a mismatch") |
| + } |
| + if _, ok := m2.boxInView("c", now); ok { |
| + t.Error("own fingerprint empty and the peer's set is in view") |
| + } |
| + |
| + // This box's own file absent: nothing is in view. |
| + s3 := meshTestStore(t) |
| + putJSON(t, s3, "control/edges/b.json", viewFile("b", "ie", "p", now, "bkt", "fp1")) |
| + m3 := newHomeMap(s3, "a") |
| + refreshHomeMap(t, m3) |
| + if _, ok := m3.boxInView("b", now); ok { |
| + t.Error("a box is in view with no file of our own") |
| + } |
| + // Own bucket empty: nothing is in view either. |
| + s4 := meshTestStore(t) |
| + putJSON(t, s4, "control/edges/a.json", viewFile("a", "ie", "p", now, "", "fp1")) |
| + putJSON(t, s4, "control/edges/b.json", viewFile("b", "ie", "p", now, "", "fp1")) |
| + m4 := newHomeMap(s4, "a") |
| + refreshHomeMap(t, m4) |
| + if _, ok := m4.boxInView("b", now); ok { |
| + t.Error("a box is in view with no data bucket on either side") |
| + } |
| +} |
| + |
| +func TestHolderViewDialsPrivateWithRegionHA(t *testing.T) { |
| + now := time.Date(2026, 10, 30, 12, 0, 0, 0, time.UTC) |
| + s := meshTestStore(t) |
| + putJSON(t, s, "control/edges/a.json", viewFile("a", "ie", "p", now, "bkt", "fp")) |
| + putJSON(t, s, "control/edges/bb.json", viewFile("bb", "ie", "p", now, "bkt", "fp")) |
| + for _, ha := range []bool{false, true} { |
| + m := newHomeMap(s, "a") |
| + m.privateDial = ha |
| + refreshHomeMap(t, m) |
| + dial, ok := m.boxInView("bb", now) |
| + want := "9.9.9.2" |
| + if ha { |
| + want = "10.0.1.2" |
| + } |
| + if !ok || dial != want { |
| + t.Errorf("region HA %v: dial = %q (ok=%v), want %q", ha, dial, ok, want) |
| + } |
| + } |
| +} |
| + |
| +func TestHopVerifiedExported(t *testing.T) { |
| + r := httptest.NewRequest("GET", "http://x.test/", nil) |
| + if HopVerified(r) { |
| + t.Error("a plain request is a verified hop") |
| + } |
| + if !HopVerified(r.WithContext(withHopVerified(r.Context()))) { |
| + t.Error("a request marked as a verified hop is not") |
| + } |
| +} |
diff --git a/internal/edge/homemap.go b/internal/edge/homemap.go| index b5e32d997..829b82bdf 100644 |
| --- a/internal/edge/homemap.go |
| +++ b/internal/edge/homemap.go |
| @@ -143,6 +143,13 @@ type edgesFileView struct { |
| PrivateCIDR string `json:"private_cidr"` |
| Region string `json:"region"` |
| Placement string `json:"placement"` |
| + // DataBucket and SecretsKeyFP are what the holder view reads |
| + // (holderview.go): the box's data bucket and the fingerprint of its |
| + // secrets key. The writer's names (internal/edgesfile snapshot.go); |
| + // absent from an older writer, and a file without a bucket is then |
| + // never in view. |
| + DataBucket string `json:"data_bucket"` |
| + SecretsKeyFP string `json:"secrets_key_fp"` |
| } |
| // dialPoint is f's dial fields, as edgesfile reads them. |
| @@ -1220,6 +1227,11 @@ func hopVerified(ctx context.Context) bool { |
| return v |
| } |
| +// HopVerified is hopVerified for the activator, which holds the request and |
| +// not the edge's context plumbing: a request that arrived as a proven hop |
| +// from another edge in this deployment's mesh. |
| +func HopVerified(r *http.Request) bool { return hopVerified(r.Context()) } |
| + |
| // hopDoorKey marks a verified hop whose sender vouched, with |
| // X-Carlos-Hop-Door, that the request came through its door. It never stands |
| // alone: acceptHop sets it only beside hopVerifiedKey. It carries no caller, |
diff --git a/internal/edge/regional.go b/internal/edge/regional.go| index 7009ac93a..76b7ad258 100644 |
| --- a/internal/edge/regional.go |
| +++ b/internal/edge/regional.go |
| @@ -34,7 +34,8 @@ const ( |
| ) |
| // regionalObserve is a test hook: nil in production, an atomic load per call. |
| -// Events: "backhaul" (backhaulTo, before dialling), "asset-fill" |
| +// Events: "backhaul" (backhaulTo, before dialling), "forward" (a region HA |
| +// forward, forwardHA, before dialling), "asset-fill" |
| // (serveAssetFar, when the far catch takes a request, before any fill or |
| // forward), "home" and "exact-home" (Home and ExactHome returning a dial |
| // target). |
diff --git a/internal/host/haforward_wiring_test.go b/internal/host/haforward_wiring_test.go| new file mode 100644 |
| index 000000000..c58a326cf |
| --- /dev/null |
| +++ b/internal/host/haforward_wiring_test.go |
| @@ -0,0 +1,61 @@ |
| +package host |
| + |
| +import ( |
| + "context" |
| + "os" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/activator" |
| + "github.com/carlosframework/platform/internal/edge" |
| + "github.com/carlosframework/platform/internal/registry" |
| +) |
| + |
| +// The activator RunAgent hands the edge forwards born-HA requests (region HA |
| +// P1b-2): the edge finds the forwarder by a type assertion on its Activator, |
| +// so the value the agent assigns must satisfy it, built over the same |
| +// SplitBackend composition, and a box with no activator hands the edge none. |
| +// RunAgent is not callable from a test, so the agent's half is syntactic (like |
| +// TestAgentWiresTheHAWake); the Service half runs against the same shape. |
| +func TestAgentActivatorForwards(t *testing.T) { |
| + src, err := os.ReadFile("agent.go") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + body := string(src) |
| + for _, want := range []string{ |
| + "var act edge.Activator", |
| + "svc = activator.New(*cfg, &activator.SplitBackend{", |
| + "act = svc\n", |
| + "edge.RunWithActivatorReady(args, act, ", |
| + } { |
| + if strings.Count(body, want) != 1 { |
| + t.Fatalf("agent.go has %d of %q, want exactly one", strings.Count(body, want), want) |
| + } |
| + } |
| + if strings.Count(body, "act = ") != 1 { |
| + t.Fatal("the edge's activator is assigned somewhere other than the one place the Service is built") |
| + } |
| + |
| + // What the agent assigns: a Service over a SplitBackend. |
| + svc := activator.New(activator.Config{Bucket: "hib", Idle: time.Hour}, &activator.SplitBackend{ |
| + Exec: &activator.ExecBackend{}, |
| + Unit: &activator.UnitBackend{}, |
| + }, nil) |
| + var act edge.Activator = svc |
| + fw, ok := act.(edge.HAForwarder) |
| + if !ok { |
| + t.Fatal("the activator the agent hands the edge is not an edge.HAForwarder") |
| + } |
| + if got := fw.ForwardTarget(context.Background(), registry.Route{Host: "shop.example.com"}); got != "" { |
| + t.Fatalf("a host that is not born HA forwards to %q, want served here", got) |
| + } |
| + |
| + // No activator configured: act stays an interface with no value, and the |
| + // edge's assertion finds nothing to forward with. |
| + var none edge.Activator |
| + if _, ok := none.(edge.HAForwarder); ok { |
| + t.Fatal("a box with no activator hands the edge a forwarder") |
| + } |
| +} |
diff --git a/internal/provision/testdata/plan14-root-reads-chain.tsv b/internal/provision/testdata/plan14-root-reads-chain.tsv| index 3590b7ccc..ef4e6d799 100644 |
| --- a/internal/provision/testdata/plan14-root-reads-chain.tsv |
| +++ b/internal/provision/testdata/plan14-root-reads-chain.tsv |
| @@ -37,3 +37,4 @@ plan14-root-reads-static-headers.tsv 94b8ccf921f64be24a4773f72d55a8e24ceba3acfb4 |
| plan14-root-reads-rootfs-check-volumes.tsv 042684bf5af6f61ce8b87f10b68a42b08d131ba4cb5bcab16320c7b032a724e6 |
| plan14-root-reads-rootfs-fleet-followups.tsv 78b7e7e30ad3ada44388a4ee16f3950ef888ae03e552477dcbfbb07c51ffb83e |
| plan14-root-reads-rootfs-worker-exit.tsv 7ebc3871ee3c93ff168bfa62d23d6be5a970786c67a9b8aa813e8cc4e39b3d74 |
| +plan14-root-reads-region-ha-p1b2.tsv 5b559ba7a42084908cb0fec08083bb2b9b3c9d960036fd10418f81e56304bb64 |
diff --git a/internal/provision/testdata/plan14-root-reads-region-ha-p1b2.tsv b/internal/provision/testdata/plan14-root-reads-region-ha-p1b2.tsv| new file mode 100644 |
| index 000000000..9a382fe58 |
| --- /dev/null |
| +++ b/internal/provision/testdata/plan14-root-reads-region-ha-p1b2.tsv |
| @@ -0,0 +1,31 @@ |
| +# Census overlay region-ha-p1b2, written by census-propose (#369). census-ruling-region-ha-p1b2, approved on #280 before the merge; the approval card is docs/superpowers/notes/census-proposal-region-ha-p1b2.md. |
| +# 4 body, 1 sites, 2 envelope: each changed unit re-frozen at its existing disposition with its claim appended. |
| +# 9 new dispositions: 1 reads re-frozen at their disposition with the claim, 8 new units frozen accepted-legacy, 0 quiet units retired while they read nothing, 0 other. |
| +@legacy 0efe3f2cef14579266e38109d984be44f66b6cc04a228b18267aa0abdd9059a6 internal/activator/activator.go Service.doWake legacy accepted-legacy accepted-legacy;rev3=census-ruling-292fix;basis=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): main's body (census ruling 292's legacy start mark and lease give-back; census ruling owed's pending record) with the seeded change ruled under census-ruling-seeded-instances (the refreshed row checked against the row the wake began from, twice; the seed's first upload recorded after the wake), and now one more line on a failed start: a start its pre-exec gate refused (launchNotStarted: the exec gate, the pending record or its recheck answered no before root was asked) is recorded as known not started (stopObservation.notStarted) instead of uncertain, only when the wake has started nothing else (wakeStartedNothing); otherwise it goes through cleanupFailedWake and its proofs. A refusal before its lease (step 1), which has started nothing, is recorded the same way. Read sites unchanged; no new read and no root decision;rev3=census-ruling-wake-latency-1;identity=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos);basis=marks the end of each wake step on the woken instance's journal timer (wakeSteps: a.now() and a slice append, journal only); no read added, no step reordered;rev3=census-ruling-region-ha-p1a;basis=the agent as carlos: (1) after the restore it asks the backend for the replication class an HA restore imported from the host's published wake state (restoredReplication(rt)) and, if it differs, logs it and sets rt.Replication and the entry's route to it; (2) an HA lease of the stream class replicates with a 1 s monitor interval (SetMonitorInterval); (3) after Replicate, an HA replica opens the entry's files publisher (openEntryFiles(ctx, e, rt)) and starts it, and a publisher that will not open fails the wake through cleanupFailedWake; (4) every cleanupFailedWake call passes e; (5) final fix F1: the two start-error arms that gave the lease straight back (a start its pre-exec gate refused with nothing started, and the default arm) now call giveBackAfterStart(ctx, rt, w, lease), which gives a legacy lease back exactly as before and an HA one only over an empty host slice. New sites: registry:Replication x5 (the class compare, the log line, the assignment and the HA sync-interval check) and whole:Route x6 (rt handed to restoredReplication, openEntryFiles, the cleanup calls and giveBackAfterStart); no file read in this body; only adds a condition before an HA release, no check removed;rev3=census-ruling-rootfs-apps-3;basis=rootfs Plan 3 Tasks 7 and 8: the rootfs admission runs before the claim path and before Acquire on the refreshed row (rootfsWakeRefusal), again in full if a re-read under the lock changed any gate field, and a resident wake re-checks residentRunnable; for a rootfs row a held lease or refused config is an ownership refusal; a rootfs first boot (no good version, fresh) places the empty database under the lease (placeRootfsDB) and uploads it once (syncRootfsPlaceholder), while fresh with a good version is refused as a lost database; declared processes are logged after the wake (rootfsProcessesHook); binary rows unchanged; fix wave 1 and 2 (6189a9db, then the r2 ruling "refuse interrupted init"): a fresh rootfs first boot goes through rootfsFirstBoot (rootfsmarker.go) instead of placeRootfsDB alone: under the lease it reads the lifetime's first-boot marker from the hibernate bucket (present or unreadable refuses, present as errRootfsReplicaMissing), writes it create-only, reads it back (only a read back that finds it confirms it; a write conflict proves nothing), and only then places the database; a warm wake does nothing with the marker (fix wave 1's settleRootfsFirstBoot call and its whole:Route site are gone, no local pending record); adds refusals only, binary rows unchanged;rev3=census-ruling-rootfs-apps-3-release;basis=rootfs Plan 3 Group R, R3: (1) refuses (errWakeUnproven) while another entry's release record of the host is open; (2) a rootfs row with a plan or a pin reads its declared processes before the lease (declaredProcesses(rt, g): the existing staged-manifest read of ExecBackend.Processes, the manifest root's staging wrote, checked against the identity's path and digest) and refuses before Acquire on an error; (3) the staged-identity start runs releaseInWake(ctx, e, rt, id, lease) before startGenExe, under this wake's lease, and a release that did not pass fails the wake; (4) a rootfs row with no plan, no pin and no staged identity is refused, the lease given back, nothing started; (5) a start error whose release is not proven stopped hands the lease to the release record (oweWakeLeaseToRelease) instead of giving it back. New sites +whole:Route x2 (rt to declaredProcesses and releaseInWake); no new file read beyond the existing staged-manifest read; binary rows unchanged;rev3=census-ruling-rootfs-apps-3-workers;basis=rootfs Plan 3 Group W, W1: step 7 no longer calls rootfsProcessesHook (log only); it calls declareRootfsWorkers(e, rt, w), which registers the workers the wake's generation declares as pending and starts nothing (the resident tick starts them once the entry is awake under its lease watch); a worker is never a failure of the wake; the read of the declaration is the existing staged-manifest read (see registerRootfsWorkers); the same read sites in this body, no new read;rev3=census-ruling-region-ha-p1b2;basis=region HA P1b-2: a successful acquire drops the host's holder-cache entry; same reads registry:DBPath@1703,registry:DBPath@1719,registry:DBPath@1846,registry:DBPath@1857,registry:DBPath@28633,registry:GoodVersion@13796,registry:Host@1532,registry:Host@1607,registry:Host@1685,registry:Host@1837,registry:Host@2171,registry:Host@4121,registry:Host@577,registry:Host@6378,registry:Replication@12419,registry:Replication@12548,registry:Replication@12567,registry:Replication@12648,registry:Replication@28536,registry:Replication@28668,registry:Seed@17354,registry:Socket@1732,registry:Socket@1748,registry:Socket@1871,registry:Socket@1882,whole:Route@10640,whole:Route@11521,whole:Route@12399,whole:Route@12650,whole:Route@13999,whole:Route@15288,whole:Route@15480,whole:Route@16170,whole:Route@1630,whole:Route@17455,whole:Route@17526,whole:Route@19942,whole:Route@2066,whole:Route@2071,whole:Route@2125,whole:Route@2131,whole:Route@21800,whole:Route@2197,whole:Route@2205,whole:Route@22446,whole:Route@23753,whole:Route@23907,whole:Route@24406,whole:Route@24476,whole:Route@25063,whole:Route@26148,whole:Route@26579,whole:Route@26787,whole:Route@26841,whole:Route@27770,whole:Route@27955,whole:Route@28745,whole:Route@29157,whole:Route@29206,whole:Route@29584,whole:Route@30806,whole:Route@30901,whole:Route@3156,whole:Route@31742,whole:Route@3250,whole:Route@3317,whole:Route@357,whole:Route@4011,whole:Route@562,whole:Route@5747,whole:Route@6006,whole:Route@6268,whole:Route@6273,whole:Route@6330,whole:Route@6336,whole:Route@6405,whole:Route@6413,whole:Route@6729,whole:Route@6790,whole:Route@6888,whole:Route@7712,whole:Route@8695,whole:Route@9269,whole:Route@9570 0c6a4433c75c5cf7277a9a152786f05d3bb4f8861233aca9f8989f54a10a9e2d |
| +@legacy d6643307417f8b6ddb679f7705c5c97c69ae2d1bd9a1db07a0d326e9ddaa5633 internal/edge/cookiescope.go Edge.responseModifier legacy accepted-legacy accepted-legacy;rev3=J1;basis=root-route;rev3=census-ruling-edge-asset-cache-3;basis=the ModifyResponse hook now also strips any asset cache header or trailer the app set (stripAssetResponseHeaders, stripAssetTrailers: X-Carlos-Asset-Fill, X-Carlos-Asset-Fill-Ack, X-Carlos-Asset-Expires, Carlos-Cache) between the purge channel and the cookie scoping; it deletes response headers only; read sites unchanged (2); no read added;rev3=census-ruling-region-ha-p1b2;basis=region HA P1b-2: strips an app-supplied X-Carlos-Holder (header, announced trailer name, trailer values at body close) so only the platform names a lease holder; same reads whole:Route@106,whole:Route@316 05398b07ec0baf2e2dd8aa392aae67042c75460702949c24af8561f0cc0d6b33 |
| +@legacy 024972c1934ce7da23d4bf009eb0d6795f783842bc12a514908b9e4982a5e2bc 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 registry:Gate@18885,registry:Gate@18945,registry:Gate@19003,registry:Host@18988,registry:ImportGate@24478,registry:Kind@14548,registry:Kind@17018,registry:Kind@24420,registry:Kind@24449,whole:Route@12356,whole:Route@12568,whole:Route@12760,whole:Route@14551,whole:Route@15854,whole:Route@15949,whole:Route@16025,whole:Route@16069,whole:Route@17021,whole:Route@18888,whole:Route@18948,whole:Route@18991,whole:Route@19006,whole:Route@20639,whole:Route@24423,whole:Route@24452,whole:Route@24481,whole:Route@26313 4f3393d0cb4e933510ee989fc0df016abe68adc051ce6a7bf9043f43e567b31d |
| +@legacy e9e68d4e9c9350499718dc6a23858fcec02221a16428a3befa64f656e38be2de internal/activator/haforward.go ExecBackend.readHolderView legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p1b2;basis=new (region HA P1b-2): one read of the host's lock.json in the box's own hibernate bucket and prefix (lease.ReadLock), keyed by the registry row's host; root never calls it registry:Host@165 a1ee59ca0b934426126623eb5ec37f00432efa66b6b37506cdad1637b1bf6f3a |
| +@legacy 56805a2f8dc664a9997d271e16c6359098712cc5dceff2641006a3d4f2dcf4f8 internal/activator/haforward.go Service.ForwardTarget legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p1b2;basis=new (region HA P1b-2): the agent's activator answers the edge with a holder box ref for an HA route not awake here, from its in-memory holder cache or one bounded (2 s) lock.json read through readHolderView; reads the route's HA flag and host from its own registry row; root never calls it registry:HA@86,registry:Host@1022,registry:Host@208,registry:Host@307,registry:Host@405,whole:Route@142,whole:Route@763 8ac8312bc8d45c3bad6a3df01b6f546bd4106278cb9e70794294f6893443bc4d |
| +@legacy d02f9af3822f3c372d32df5819c451da8665e5dbdda991258c6675c431e6ad40 internal/activator/haforward.go Service.answerForwarded legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p1b2;basis=new (region HA P1b-2): writes the 503 Retry-After 1 with X-Carlos-Holder for a held lease on a verified HA hop; reads the route only to check HA; root never calls it whole:Route@131 f8b4616f37070cf2ce8069e78d48cbbe49ed8fa0366a25ad1469e52ad99b3d3e |
| +@legacy 644205a2a3ba78aa3065543226224c83be75fc92cfce83b902a2cc18dceba19a internal/activator/haforward.go boxSelfRef legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p1b2;basis=new (region HA P1b-2): this box's lease reference from the exec backend's configured identity (lease.CurrentSelf through Config.Self); the census's file:Exec is the SplitBackend.Exec field, not an exec; no I/O; root never calls it file:Exec@109 e182b10a0f0ddb061488e4eab8060d0bb87bd79bf927900c92a5841c9b8eedeb |
| +@legacy 7bdcaba2d7b794cc15d897d357f68cd65ab7548d172d82f367fd2c40f4941cf5 internal/activator/haforward.go forwardedHA legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p1b2;basis=new (region HA P1b-2): true for a verified hop on an HA route (the route's HA flag and edge.HopVerified); no I/O; root never calls it registry:HA@79 8bf49c41eab02be063ed9325369903bfb8cca8bce3a5e0d6ceb08b5924613e63 |
| +@legacy 39f51ba95193af6c8f0a67d2f3000f890b5c60c615e88ce6fabfd32f63d45cdb internal/activator/haforward.go holderReaderFor legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p1b2;basis=new (region HA P1b-2): picks the backend half that serves the route (SplitBackend.pick), as every other call does; no I/O; root never calls it whole:Route@147,whole:Route@152 3c31fb2add1f0933ee27263081a183bdc86bb32e83cc51f3e70e2eb659af7477 |
| +@legacy 2b51d58bc7ab1ac8afd9fe271d00d51cc5c5509c833525119b4d5945709752f6 internal/activator/haforward.go noteNoHolder legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p1b2;basis=new (region HA P1b-2): adds X-Carlos-Holder: none to a refusal of a verified HA hop; reads the route only to check HA; root never calls it whole:Route@109 2a8ed0a11264e58758644ef4042c795a21b66c1b406903339f09ae6808d85c4e |
| +@legacy 285996d7717640e97d1fe357a38122df70264e05e17a6166c6d2063a659c8605 internal/edge/forwardha.go Edge.frontForwardHA legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p1b2;basis=new (region HA P1b-2): the agent's edge decides at the front door whether to forward a visitor request: reads the route's HA flag and host from the box's own registry row and asks the activator; forwards only to a box in view over the existing signed hop; root never calls it registry:HA@225,registry:Host@501,whole:Route@228,whole:Route@407,whole:Route@504 2c9936721e996db822dca79af3597ed2c0fd29aa29e40fa6fc1f7512b3867106 |
| +@legacy 3d59041197161742f3878b0d7d0f2cd97a80375f5244f07e8a84aca9ea06828e internal/activator/activator.go Service.serve legacy accepted-legacy accepted-legacy;rev3=census-ruling-hotfix281;basis=Startup repeats the existing Kind and Hibernate checks; error logging moved to serveWakeError. A request held through startup re-reads its own route's Socket and Addr and can only refuse (wake-timeout 503) when recovery moved them; agent-side, deny-only, no root decision.;rev3=census-ruling-edge-request-records;basis=passes the member request r to begin's new req parameter; no read added;rev3=census-ruling-rootfs-apps-3;basis=rootfs Plan 3 Task 5: the activator-managed test is Route.ActivatorOwned instead of Kind and Hibernate inline, so a resident rootfs instance is the activator's; same deploy-safety for binary rows;rev3=census-ruling-region-ha-p1b2;basis=region HA P1b-2: a verified HA hop this box cannot serve gets the holder diagnostic; two new whole:Route sites pass the route to answerForwarded/noteNoHolder; no new kind of read registry:Addr@934,registry:Addr@948,registry:Host@1059,registry:Host@859,registry:Socket@905,registry:Socket@921,whole:Route@1127,whole:Route@2676,whole:Route@2777,whole:Route@329,whole:Route@3497,whole:Route@3560,whole:Route@884,whole:Route@993 d788f023e71cf3bc6bdadf106da3ed981b96e06a2a3408220b48dcf65fba419d |
| +internal/activator/activator.go Service.doWake legacy accepted-legacy accepted-legacy;rev3=census-ruling-292fix;basis=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): main's body (census ruling 292's legacy start mark and lease give-back; census ruling owed's pending record) with the seeded change ruled under census-ruling-seeded-instances (the refreshed row checked against the row the wake began from, twice; the seed's first upload recorded after the wake), and now one more line on a failed start: a start its pre-exec gate refused (launchNotStarted: the exec gate, the pending record or its recheck answered no before root was asked) is recorded as known not started (stopObservation.notStarted) instead of uncertain, only when the wake has started nothing else (wakeStartedNothing); otherwise it goes through cleanupFailedWake and its proofs. A refusal before its lease (step 1), which has started nothing, is recorded the same way. Read sites unchanged; no new read and no root decision;rev3=census-ruling-wake-latency-1;identity=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos);basis=marks the end of each wake step on the woken instance's journal timer (wakeSteps: a.now() and a slice append, journal only); no read added, no step reordered;rev3=census-ruling-region-ha-p1a;basis=the agent as carlos: (1) after the restore it asks the backend for the replication class an HA restore imported from the host's published wake state (restoredReplication(rt)) and, if it differs, logs it and sets rt.Replication and the entry's route to it; (2) an HA lease of the stream class replicates with a 1 s monitor interval (SetMonitorInterval); (3) after Replicate, an HA replica opens the entry's files publisher (openEntryFiles(ctx, e, rt)) and starts it, and a publisher that will not open fails the wake through cleanupFailedWake; (4) every cleanupFailedWake call passes e; (5) final fix F1: the two start-error arms that gave the lease straight back (a start its pre-exec gate refused with nothing started, and the default arm) now call giveBackAfterStart(ctx, rt, w, lease), which gives a legacy lease back exactly as before and an HA one only over an empty host slice. New sites: registry:Replication x5 (the class compare, the log line, the assignment and the HA sync-interval check) and whole:Route x6 (rt handed to restoredReplication, openEntryFiles, the cleanup calls and giveBackAfterStart); no file read in this body; only adds a condition before an HA release, no check removed;rev3=census-ruling-rootfs-apps-3;basis=rootfs Plan 3 Tasks 7 and 8: the rootfs admission runs before the claim path and before Acquire on the refreshed row (rootfsWakeRefusal), again in full if a re-read under the lock changed any gate field, and a resident wake re-checks residentRunnable; for a rootfs row a held lease or refused config is an ownership refusal; a rootfs first boot (no good version, fresh) places the empty database under the lease (placeRootfsDB) and uploads it once (syncRootfsPlaceholder), while fresh with a good version is refused as a lost database; declared processes are logged after the wake (rootfsProcessesHook); binary rows unchanged; fix wave 1 and 2 (6189a9db, then the r2 ruling "refuse interrupted init"): a fresh rootfs first boot goes through rootfsFirstBoot (rootfsmarker.go) instead of placeRootfsDB alone: under the lease it reads the lifetime's first-boot marker from the hibernate bucket (present or unreadable refuses, present as errRootfsReplicaMissing), writes it create-only, reads it back (only a read back that finds it confirms it; a write conflict proves nothing), and only then places the database; a warm wake does nothing with the marker (fix wave 1's settleRootfsFirstBoot call and its whole:Route site are gone, no local pending record); adds refusals only, binary rows unchanged;rev3=census-ruling-rootfs-apps-3-release;basis=rootfs Plan 3 Group R, R3: (1) refuses (errWakeUnproven) while another entry's release record of the host is open; (2) a rootfs row with a plan or a pin reads its declared processes before the lease (declaredProcesses(rt, g): the existing staged-manifest read of ExecBackend.Processes, the manifest root's staging wrote, checked against the identity's path and digest) and refuses before Acquire on an error; (3) the staged-identity start runs releaseInWake(ctx, e, rt, id, lease) before startGenExe, under this wake's lease, and a release that did not pass fails the wake; (4) a rootfs row with no plan, no pin and no staged identity is refused, the lease given back, nothing started; (5) a start error whose release is not proven stopped hands the lease to the release record (oweWakeLeaseToRelease) instead of giving it back. New sites +whole:Route x2 (rt to declaredProcesses and releaseInWake); no new file read beyond the existing staged-manifest read; binary rows unchanged;rev3=census-ruling-rootfs-apps-3-workers;basis=rootfs Plan 3 Group W, W1: step 7 no longer calls rootfsProcessesHook (log only); it calls declareRootfsWorkers(e, rt, w), which registers the workers the wake's generation declares as pending and starts nothing (the resident tick starts them once the entry is awake under its lease watch); a worker is never a failure of the wake; the read of the declaration is the existing staged-manifest read (see registerRootfsWorkers); the same read sites in this body, no new read;rev3=census-ruling-region-ha-p1b2;basis=region HA P1b-2: a successful acquire drops the host's holder-cache entry; same reads registry:DBPath@1703,registry:DBPath@1719,registry:DBPath@1846,registry:DBPath@1857,registry:DBPath@28633,registry:GoodVersion@13796,registry:Host@1532,registry:Host@1607,registry:Host@1685,registry:Host@1837,registry:Host@2171,registry:Host@4121,registry:Host@577,registry:Host@6378,registry:Replication@12419,registry:Replication@12548,registry:Replication@12567,registry:Replication@12648,registry:Replication@28536,registry:Replication@28668,registry:Seed@17354,registry:Socket@1732,registry:Socket@1748,registry:Socket@1871,registry:Socket@1882,whole:Route@10640,whole:Route@11521,whole:Route@12399,whole:Route@12650,whole:Route@13999,whole:Route@15288,whole:Route@15480,whole:Route@16170,whole:Route@1630,whole:Route@17455,whole:Route@17526,whole:Route@19942,whole:Route@2066,whole:Route@2071,whole:Route@2125,whole:Route@2131,whole:Route@21800,whole:Route@2197,whole:Route@2205,whole:Route@22446,whole:Route@23753,whole:Route@23907,whole:Route@24406,whole:Route@24476,whole:Route@25063,whole:Route@26148,whole:Route@26579,whole:Route@26787,whole:Route@26841,whole:Route@27770,whole:Route@27955,whole:Route@28745,whole:Route@29157,whole:Route@29206,whole:Route@29584,whole:Route@30806,whole:Route@30901,whole:Route@3156,whole:Route@31742,whole:Route@3250,whole:Route@3317,whole:Route@357,whole:Route@4011,whole:Route@562,whole:Route@5747,whole:Route@6006,whole:Route@6268,whole:Route@6273,whole:Route@6330,whole:Route@6336,whole:Route@6405,whole:Route@6413,whole:Route@6729,whole:Route@6790,whole:Route@6888,whole:Route@7712,whole:Route@8695,whole:Route@9269,whole:Route@9570 0c6a4433c75c5cf7277a9a152786f05d3bb4f8861233aca9f8989f54a10a9e2d |
| +internal/activator/activator.go type Service authority B,C,D,F,J4 rev3=PROPOSED-seed; existing activator lifecycle and due-wake state plus owned seed exclusion and incarnation-keyed diagnostics; normal refusal and preparation ordering remain authoritative; PROPOSED-plans-2-box-limits adds the idleFor hook field, which only narrows idle windows;rev3=census-ruling-plans-4c-box-throttle;basis=gains the maxRunFor hook field beside idleFor (plans 4c). No read added.;rev3=census-ruling-plans-4d-lapse;basis=gains the disabledFor hook field beside maxRunFor (plans 4d). No read added.;rev3=census-ruling-remote-instance-metrics;basis=gains tenancySeq, hostTenants and hostMixed, in-memory fields for Tenancies; no read added;rev3=census-ruling-region-ha-p1a;basis=the agent as carlos: one more field, markers (markerRetry: an atomic running flag and the last log time) for retryOwedMarkers; no read added; merge of origin/main d7ae1d76: main's fields are kept as main has them (census-ruling-remote-instance-metrics: tenancySeq, hostTenants, hostMixed); this branch's change is the same as above;rev3=census-ruling-rootfs-apps-3;basis=rootfs Plan 3 Tasks 7 and 8: new fields for rootfs admission (rootfsArmed, rootfsSwept), the per-host gate ask and refusal memo, and residency state (lister, backoff, start ceiling, cursor, test seam); no read;rev3=census-ruling-rootfs-apps-3-release;basis=rootfs Plan 3 Group R: one new field, releaseOps (host to the in-memory release record, under a.mu); no read;rev3=census-ruling-rootfs-apps-3-workers;basis=rootfs Plan 3 Group W: one new field, leaseNow (a clock seam for a worker start's headroom against the lease deadline, nil is the real clock); no read;rev3=census-ruling-region-ha-p1b2;basis=region HA P1b-2: gains the holder cache and its single-flight state; no read 6a76d768e4d999fc6e280cdd1d775881fec148c6722b974c3c03085dfc7dec5d |
| +internal/edge/cookiescope.go Edge.responseModifier legacy accepted-legacy accepted-legacy;rev3=J1;basis=root-route;rev3=census-ruling-edge-asset-cache-3;basis=the ModifyResponse hook now also strips any asset cache header or trailer the app set (stripAssetResponseHeaders, stripAssetTrailers: X-Carlos-Asset-Fill, X-Carlos-Asset-Fill-Ack, X-Carlos-Asset-Expires, Carlos-Cache) between the purge channel and the cookie scoping; it deletes response headers only; read sites unchanged (2); no read added;rev3=census-ruling-region-ha-p1b2;basis=region HA P1b-2: strips an app-supplied X-Carlos-Holder (header, announced trailer name, trailer values at body close) so only the platform names a lease holder; same reads whole:Route@106,whole:Route@316 05398b07ec0baf2e2dd8aa392aae67042c75460702949c24af8561f0cc0d6b33 |
| +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 registry:Gate@18885,registry:Gate@18945,registry:Gate@19003,registry:Host@18988,registry:ImportGate@24478,registry:Kind@14548,registry:Kind@17018,registry:Kind@24420,registry:Kind@24449,whole:Route@12356,whole:Route@12568,whole:Route@12760,whole:Route@14551,whole:Route@15854,whole:Route@15949,whole:Route@16025,whole:Route@16069,whole:Route@17021,whole:Route@18888,whole:Route@18948,whole:Route@18991,whole:Route@19006,whole:Route@20639,whole:Route@24423,whole:Route@24452,whole:Route@24481,whole:Route@26313 4f3393d0cb4e933510ee989fc0df016abe68adc051ce6a7bf9043f43e567b31d |
| +internal/activator/haforward.go ExecBackend.readHolderView legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p1b2;basis=new (region HA P1b-2): one read of the host's lock.json in the box's own hibernate bucket and prefix (lease.ReadLock), keyed by the registry row's host; root never calls it registry:Host@165 a1ee59ca0b934426126623eb5ec37f00432efa66b6b37506cdad1637b1bf6f3a |
| +internal/activator/haforward.go Service.ForwardTarget legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p1b2;basis=new (region HA P1b-2): the agent's activator answers the edge with a holder box ref for an HA route not awake here, from its in-memory holder cache or one bounded (2 s) lock.json read through readHolderView; reads the route's HA flag and host from its own registry row; root never calls it registry:HA@86,registry:Host@1022,registry:Host@208,registry:Host@307,registry:Host@405,whole:Route@142,whole:Route@763 8ac8312bc8d45c3bad6a3df01b6f546bd4106278cb9e70794294f6893443bc4d |
| +internal/activator/haforward.go Service.answerForwarded legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p1b2;basis=new (region HA P1b-2): writes the 503 Retry-After 1 with X-Carlos-Holder for a held lease on a verified HA hop; reads the route only to check HA; root never calls it whole:Route@131 f8b4616f37070cf2ce8069e78d48cbbe49ed8fa0366a25ad1469e52ad99b3d3e |
| +internal/activator/haforward.go boxSelfRef legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p1b2;basis=new (region HA P1b-2): this box's lease reference from the exec backend's configured identity (lease.CurrentSelf through Config.Self); the census's file:Exec is the SplitBackend.Exec field, not an exec; no I/O; root never calls it file:Exec@109 e182b10a0f0ddb061488e4eab8060d0bb87bd79bf927900c92a5841c9b8eedeb |
| +internal/activator/haforward.go forwardedHA legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p1b2;basis=new (region HA P1b-2): true for a verified hop on an HA route (the route's HA flag and edge.HopVerified); no I/O; root never calls it registry:HA@79 8bf49c41eab02be063ed9325369903bfb8cca8bce3a5e0d6ceb08b5924613e63 |
| +internal/activator/haforward.go holderReaderFor legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p1b2;basis=new (region HA P1b-2): picks the backend half that serves the route (SplitBackend.pick), as every other call does; no I/O; root never calls it whole:Route@147,whole:Route@152 3c31fb2add1f0933ee27263081a183bdc86bb32e83cc51f3e70e2eb659af7477 |
| +internal/activator/haforward.go noteNoHolder legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p1b2;basis=new (region HA P1b-2): adds X-Carlos-Holder: none to a refusal of a verified HA hop; reads the route only to check HA; root never calls it whole:Route@109 2a8ed0a11264e58758644ef4042c795a21b66c1b406903339f09ae6808d85c4e |
| +internal/edge/forwardha.go Edge.frontForwardHA legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p1b2;basis=new (region HA P1b-2): the agent's edge decides at the front door whether to forward a visitor request: reads the route's HA flag and host from the box's own registry row and asks the activator; forwards only to a box in view over the existing signed hop; root never calls it registry:HA@225,registry:Host@501,whole:Route@228,whole:Route@407,whole:Route@504 2c9936721e996db822dca79af3597ed2c0fd29aa29e40fa6fc1f7512b3867106 |
| +internal/activator/activator.go Service.serveWakeError diagnostic C,J4 rev3=PROPOSED-seed; incarnation-keyed missing-files diagnostics and indexed retry results; throttles output only and grants no retry, stop or launch;rev3=census-ruling-region-ha-p1a;basis=the agent as carlos: one more case, errLeaseRefused (a born-HA host outside the nested layout or an HA acquire's refusal): logged at most once per diagnostic window (allowFilesDiagnostic(rt.Host, ...)) and answered 503 with Retry-After: 10; the other cases unchanged; +registry:Host x2 are rt.Host in that call and the log line; it only answers;rev3=census-ruling-rootfs-apps-3;basis=rootfs Plan 3 Tasks 7 and 8: two new answers, a resident inside its backoff gets 503 with Retry-After (RFS-3-C16), and a rootfs row refused before the lease (errRootfsNotAdmitted) gets the existing wake-failed 503; no read added;rev3=census-ruling-region-ha-p1b2;basis=region HA P1b-2: for a verified HA hop, a held lease answers 503 Retry-After 1 with X-Carlos-Holder (answerForwarded) and every other refusal adds X-Carlos-Holder: none (noteNoHolder); legacy routes and cancellation unchanged; same reads registry:Host@1070,registry:Host@1134,registry:Host@2836,registry:Host@2900,whole:Route@204 a8834927132e29ac5cdf44b5caced8dc010d538f6552979f90b226a09fd13c2f |
| +internal/activator/activator.go Service.serve legacy accepted-legacy accepted-legacy;rev3=census-ruling-hotfix281;basis=Startup repeats the existing Kind and Hibernate checks; error logging moved to serveWakeError. A request held through startup re-reads its own route's Socket and Addr and can only refuse (wake-timeout 503) when recovery moved them; agent-side, deny-only, no root decision.;rev3=census-ruling-edge-request-records;basis=passes the member request r to begin's new req parameter; no read added;rev3=census-ruling-rootfs-apps-3;basis=rootfs Plan 3 Task 5: the activator-managed test is Route.ActivatorOwned instead of Kind and Hibernate inline, so a resident rootfs instance is the activator's; same deploy-safety for binary rows;rev3=census-ruling-region-ha-p1b2;basis=region HA P1b-2: a verified HA hop this box cannot serve gets the holder diagnostic; two new whole:Route sites pass the route to answerForwarded/noteNoHolder; no new kind of read registry:Addr@934,registry:Addr@948,registry:Host@1059,registry:Host@859,registry:Socket@905,registry:Socket@921,whole:Route@1127,whole:Route@2676,whole:Route@2777,whole:Route@329,whole:Route@3497,whole:Route@3560,whole:Route@884,whole:Route@993 d788f023e71cf3bc6bdadf106da3ed981b96e06a2a3408220b48dcf65fba419d |
| +@coverage internal/activator bdc13358991df745255bee547ee6d7f87a67af81cddb7ccb322908c913696a0b |
| +@coverage internal/edge f4fc674afe445ff97533f8fa9e550252e97e650ad8c51e35c5060cc8f74e4c99 |