region HA: floor counts every edges file; drain asks the floor's list
Held floor capability (spec 25.9). The edges file publishes ha_handover unconditionally; the floor counts every present file by that capability, whatever its age, and refuses DR-4 when a declared fixed box has no file (fixed_boxes or no_fixed_boxes: true in the group config). The drain carries the floor's single list (drain --peers) through the root verb, the drain-call child and the agent socket; the member's fold only adds peers, and every answer is MAC-signed (unsigned fails closed). A floor row without the all-files-v1 provenance marker, or with a live list that is not a present array of valid refs, refuses before draining. Astra R1-R3; F3.1/F3.2 cut and Fable 5.2 spot-checked, no P1. Follow-ups in discussion 813. The SSM operator document needs a redeploy. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Squashed from held-floor-capability into main.
45 files changed,
+1,594
−286
docs/superpowers/notes/census-proposal-held-floor-capability.md+33 −0docs/superpowers/specs/2026-10-26-region-ha-without-claims-design.md+15 −6docs/superpowers/specs/2026-11-09-group-roll-verb-design.md+7 −2infra/modules/region-group-operator-document/README.md+1 −1infra/modules/region-group-operator-document/tool-pattern.txt+1 −1internal/edge/hadrain.go+94 −8internal/edge/hadrain_test.go+268 −7internal/edge/hadrainconns.go+15 −16internal/edge/hadrainconns_test.go+37 −10internal/edge/hatake_test.go+7 −4internal/edge/testdata/edges-forward-hub.json+1 −1internal/grouproll/box.go+31 −1internal/grouproll/box_test.go+61 −7internal/grouproll/config.go+48 −1internal/grouproll/config_test.go+37 −19internal/grouproll/depart.go+48 −2internal/grouproll/depart_test.go+159 −11internal/grouproll/engine.go+7 −0internal/grouproll/fake_test.go+31 −10internal/grouproll/floor.go+50 −21internal/grouproll/floor_test.go+142 −43internal/grouproll/testdata/parity-ledger.tsv+4 −4internal/grouproll/testdata/remotecommand/main.go+4 −1internal/grouproll/text.go+7 −1internal/grouproll/text_test.go+5 −2internal/host/edgesfile.go+9 −0internal/host/edgesfile_test.go+12 −6internal/host/egress_nopolicy_linux_test.go+2 −2internal/host/group_maintenance_drain.go+4 −4internal/host/group_maintenance_verbs.go+22 −5internal/host/group_names_test.go+1 −1internal/host/hadrain.go+46 −18internal/host/hadrain_call.go+85 −16internal/host/hadrain_call_linux.go+5 −5internal/host/hadrain_call_linux_test.go+29 −13internal/host/hadrain_call_other.go+1 −1internal/host/hadrain_socket.go+24 −8internal/host/hadrain_test.go+123 −14internal/host/hadrainfence_linux_test.go+35 −0internal/host/testdata/edges-p2b-golden.json+1 −1internal/provision/testdata/plan14-root-reads-chain.tsv+1 −0internal/provision/testdata/plan14-root-reads-held-floor-capability.tsv+20 −0scripts/region-group-roll.py+1 −0scripts/region_group_document_test.py+58 −11testdata/clireg-golden.jsonl+2 −2
CI passed — run details
diff --git a/docs/superpowers/notes/census-proposal-held-floor-capability.md b/docs/superpowers/notes/census-proposal-held-floor-capability.md| new file mode 100644 |
| index 000000000..cbacab8ac |
| --- /dev/null |
| +++ b/docs/superpowers/notes/census-proposal-held-floor-capability.md |
| @@ -0,0 +1,33 @@ |
| +# Census approval: held-floor-capability |
| + |
| +Ruling `census-ruling-held-floor-capability`. The independent reviewer approves or rejects every change below, 1 with a new disposition; nothing goes to the census owner (Paul, #280, 2026-10-26). |
| + |
| +| unit | change | read sites | what changed | |
| +|---|---|---|---| |
| +| `infra/modules/region-group-operator-document/tool-pattern.txt` `external` | body | unchanged (1) | held floor capability (Astra r2 F2.1): the drain alternative of the operator document's allowedPattern becomes `group-maintenance drain --peers=[A-Za-z0-9._,-]* <transaction>`: the verb's acknowledgement list, shell-safe characters only (no space, quote, semicolon or dollar), validated again by root's maintenanceArguments. Every other alternative is unchanged. Needs the document redeployed before a verb on this build can drain. | |
| +| `internal/edge/hadrain.go` `Edge.serveHAControl` | body | unchanged (1) | held floor capability (region HA §25.4 step 1, agent manager 8a3d302, 2026-11-10): a drain ask must also carry a nonce of 32 lower-case hex digits (else a bare 404, like any other malformed ask), and the JSON answer gains sig, an HMAC-SHA256 under the same mesh key (signingKey of the mirrored pair) over a distinct domain, this box, the asker, the transaction, the phase, the publication id, the nonce and the seen value. Computed in memory from the already verified ask; no read added, no file, record or store access added; the take path is unchanged. | |
| +| `internal/host/edgesfile.go` `edgesFileWriteClaims` | body | unchanged (70) | held floor capability (region HA §25.9, agent manager 8a3d302, 2026-11-10): sets the constant ha_handover=1 on the box's own edges file on every pass, whatever its capabilities (this build understands the held-requests headers and the drain acknowledgement); the group roll floor reads it. Not from config or any read; ha_take unchanged; a report other tools read, not a root decision; no read added; F,J1 authority retained. One-off cost: the first pass after the upgrade writes once per box. | |
| +| `internal/host/hadrain.go` `drainDriver.moveSteps` | body | unchanged (2) | held floor capability (Astra r2 F2.1): takes the verb's acknowledgement list (listed) and passes it to the drained-phase publishAndAck, which asks every listed box plus any the fold adds; nothing else changes. No read added; in-memory only. | |
| +| `internal/host/hadrain_call_linux.go` `drainCallExec` | body | unchanged (1) | held floor capability (Astra r2 F2.1): root's drain-call child command gains a third argument for withdraw and move, --peers=<refs joined by commas>, when root was given a list; execDrainCall refuses a list that is not valid (validDrainPeers: at most 256 references in the edges-key grammar [A-Za-z0-9][A-Za-z0-9._-]{0,127}, no duplicates) before any child starts. Same pinned executable, empty environment, "/" directory, no stdin; the child still drops to the agent user before reading anything. No read added. | |
| +| `internal/host/hadrain_socket.go` `drainDriver.handler` | body | unchanged (1) | held floor capability (Astra r2 F2.1): the agent's drain socket accepts an optional peers array on withdraw and move (strict JSON, unknown fields still refused; a peers field on cancel, or an invalid list, is a 400), the body bound rises from 4 KiB to 64 KiB for up to 256 references, and the list goes to drainDriver.start, which refuses a step without a valid list (errDrainNoPeers) before anything runs. Peer-credential check unchanged; no file or store read added. | |
| + |
| +Envelopes re-pinned: `infra/modules/region-group-operator-document`, `internal/edge`, `internal/grouproll`, `internal/host`. |
| + |
| +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: |
| + |
| +- `infra/modules/region-group-operator-document/tool-pattern.txt` `external`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-region-ha-p3b2-ops;basis=new: Branch T grammar admitting only region-group-roll.py remote_command forms (status/prepare/permit/revoke/apply/rollback);rev3=census-ruling-region-ha-held-build;basis=region HA held-requests Task 6 fix 1: Branch T admits exactly the tool forms status, revoke, prepare --sha256 SHA, permit && status, apply and rollback (900 s), plus the planned-handover forms "timeout --signal=TERM --kill-after=30s 3600s ... group-maintenance drain TX", "timeout --signal=TERM --kill-after=30s 300s ... group-maintenance drain --cancel TX && ... status", "... group-maintenance fence-clear TX && ... status" and "timeout --signal=TERM --kill-after=10s 120s /usr/bin/systemctl stop carlos-edge.service; /usr/bin/systemctl show --property=MainPID --property=ActiveState carlos-edge.service", where TX is [A-Za-z0-9_][A-Za-z0-9_-]{0,79}; nothing else |
| +- `internal/edge/hadrain.go` `Edge.serveHAControl`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-region-ha-held-build;basis=new: answers a signed drain ask. Reads the request body (io.ReadAll under MaxBytesReader 4 KiB and a 2 s read deadline), verifies its own mesh-key MAC, requires a phase (draining or drained) and a nonzero publication id, and may refresh the edges fold (the existing refreshHosts: LIST plus GET of control/edges/ in the deployment bucket); reads no local file; answers JSON seen true or false, or a bare 404. Fix round 1: the ask names phase and publication id instead of a generation. held-requests Task 4: accepts POST /.carlos/ha-take beside /.carlos/ha-drain, with the same bounded body read; the signature is verified over the request's own path (one of the two reserved constants), then a take goes to serveHATake (strict JSON with transaction, asker, host, lifetime and a positive marker generation, else a bare 404); no read added here |
| +- `internal/host/edgesfile.go` `edgesFileWriteClaims`: authority, task F,J1. Basis: rev3=census-ruling-self-serve-moves-1;basis=root-route;kept=F;scope=protected-decision-only; the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): region-ha-2a's body, which with the box's lifetimes switch on also publishes each served row's lifetime pair (registry:Incarnation and registry:ServingSeq, two new sites on the rows it already lists) and an alias's or served catch-all's primary's pair, and names that primary as target_host whatever the switch; a report the edge orders unstamped entries by, not a decision; no record, /data, release or claim read added; F,J1 authority retained; self-serve moves 1 Task 8;rev3=census-ruling-instance-egress-sizes-328-329;basis=#328 plan 2 Task 8: takes a localAddrs reader (instancectl.LocalAddresses in production, which reads /proc/net/fib_trie and /proc/net/if_inet6 in the agent) and publishes its non-loopback entries as the edges file's addrs before the write gate (boxAddrs, no read of its own), so an address change writes once. The same 44 sites, offsets moved; no record, /data, release or claim read added; a report the console's egress grant check reads, not a root decision; F,J1 authority retained.;rev3=census-ruling-edge-asset-cache-3;basis=starts with assets = assets.active(), so a policy whose box has not opened its asset store publishes no assets blocks and reads no manifests, and copies the decision's Primary (the route host the block was decided for, drift D4) into the published assets block; read sites unchanged (44); no read added. Merged onto main's #328 body, which takes the localAddrs reader: the assets.active() line sits after that signature and the loop passes pub and instancectl.LocalAddresses;rev3=census-ruling-region-ha-p1a;basis=the agent as carlos: the claims argument (*edgesClaims) becomes addrs (AddressSource) and the applyEdgesClaims(ctx, claims, routes, hosts) call is deleted with edgesclaims.go, which is the one whole:Route site removed: no host claim is read and every served row publishes as with region HA off; the box-address publication is the same code reading addrs.BoxAddresses() instead of claims.addrs; a report the edge reads, not a root decision; no read added; merge of origin/main d7ae1d76: main's edge asset cache plan 3 body is kept (census-ruling-edge-asset-cache-3): the first line is assets = assets.active(), so a policy whose store has not opened publishes no assets blocks and reads no manifests, and edgesFileLoop passes pub (assets.active() for that tick) in the assets argument; main's claims *edgesClaims argument is this branch's addrs AddressSource, and no edgesClaims, applyEdgesClaims or hostclaim reference remains;rev3=census-ruling-alias-wake-338;basis=#338 follow-up: skips publishing a platform alias edge.PlatformAliasFold refuses (and so anything attached to it); reads the same route listing;rev3=census-ruling-fleet-public-routes;basis=fleet public routes (spec 2026-10-29 rev 4, §4.2 writer rule): Task 6 and its fix rounds: publishes by FleetArmVerdict (via fleetRefusedFor): withheld rows left out; a forward host's path rows left out of its owner; no assets for forward rows; the alias loop replays Reload's alias fold from the served rows so a chained alias carries its root primary's owner; certRefused and parentRefused leave out a refused claim's wildcard parent (+registry:Alias x5, +registry:Host x4, +whole:Route, +whole:RouteAlias x2, +whole:RoutePath x7, +whole:WildcardDomain). Rows already read in the pass; keeps authority F,J1; publishes less, never more.;rev3=census-ruling-probe-burst-limit;basis=sets the constant BurstNotices=true on the box's own edges file (this build's edge answers probe-burst notices, so peers may send them); not from config or any read; the same 65 sites; a report other edges read, not a root decision; F,J1 authority retained; no new root read or write kind;rev3=census-ruling-region-ha-p3a;basis=Publish one injected role snapshot with box_role/admitted/drained; retain legacy route and alias rows during booting, cutting namespace withdrawal under the 2026-11-04 ruling; acknowledge the exact published tuple only after PUT; existing registry reads unchanged.;rev3=census-ruling-region-ha-p2b;basis=region HA P2b-1 T0 (Q1 ruling): before building the comparison copy and the body, a nil NamedPools on the identity becomes []string{} so the additive named_pools field is always an explicit array; the list itself is computed once at arm by edgesFileEligibility from the same provisionTickConfig(os.Getenv) parse as serves_shared_pool (CARLOS_POOLS through provision.ParseBoxPools, filtered to nonempty provision.ValidPool names, sorted, unique). A report the console reads for create admission, not a root decision; no record, /data, release or claim read added; read sites unchanged (65); F,J1 authority retained. One-off cost: the first pass after the upgrade writes once per box (seeded gate null vs []).;rev3=census-ruling-region-ha-p3b;basis=Require cached GroupReadersReady before first group publication and append additive names-2 capability even for supplied identities. Agent writes the same edges object/index with existing registry reads; known readers come from root boot configuration, snapshot from existing fold, no added GET/LIST or root authority.;rev3=census-ruling-region-ha-g2-fixes;basis=Omit non-forward, non-platform-alias rows outside local served pools from home publication; added Host/Pool field reads and local configuration use, existing registry/store operations retained.;rev3=census-ruling-edge-page-cache-1;basis=prunes the manifest cache through the new atomic pointer (assets.manifests.Load().prune(...), nil-safe); nothing else changes; read sites unchanged (67); no read added;rev3=census-ruling-region-ha-held-build;basis=writes also when DrainPublishRequired, and reports the written drain state, its ha_drain mark (transaction and publication id) and generation to DrainSource (in-memory); the file gains ha_drained and ha_drain beside the existing draining; no read added. held-requests Task 4: sets the constant ha_take=1 on the box's own file when its in-memory capabilities include region-ha-1 (this build's edge answers take requests); not from config or any read; a report other edges read, not a root decision; no read added;rev3=census-ruling-warm-set-published-724;basis=#724: the agent as carlos: reads PLATFORM_APPS_DOMAIN from the environment once per pass (the variable domainsLoop already reads) and sets an additive dns_pointing mark on each published custom name through dnsPointingMark: true on a published alias (registry:Alias, already published only when its dns_status is pointing), and on a route with a hostname outside the apps domain whether its registry:DNSStatus is pointing (registry:Host, registry:DNSStatus on rows the pass already lists). No mark under the apps domain, on a wildcard row, or with no apps domain set. A report the issuer cert warm reads to leave a not-yet-pointing custom name out of its set, not a root decision; it publishes the same names as before. No record, /data, release or claim read added; no new registry query; F,J1 authority retained. One-off cost: the first pass after the upgrade writes once on a box homing a custom name. |
| +- `internal/host/hadrain.go` `drainDriver.moveSteps`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-region-ha-held-build;basis=new (split from move): drain steps 2-5 over the activator and edge APIs; reads route Host from the activator's in-memory DrainHosts; releases and moves under one 4-way semaphore; no store or file read of its own |
| +- `internal/host/hadrain_call_linux.go` `drainCallExec`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-region-ha-held-build;basis=new (branch review r1, Astra B1.3): builds the __drain-call child command: the pinned executable /proc/self/fd/3 (registryExecutable, as the registry child), fixed arguments (op from a fixed set, the validated transaction), empty environment, Dir "/", no stdin; the child drops to the agent user before it dials the agent socket; root reads only its bounded stdout (drainCallMax) |
| +- `internal/host/hadrain_socket.go` `drainDriver.handler`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-region-ha-held-build;basis=new: agent drain socket handler: reads the request body bounded to 4 KiB, strict JSON with one transaction field; served only to a peer SO_PEERCRED reports as root; not a file read |
| + |
| +New dispositions, which census-propose wrote and the reviewer checks against the unit's reads and the diff: |
| + |
| +- new `internal/edge/hadrain.go:Edge.AskDrainSeen`: reads +file:Read; written legacy, accepted-legacy, frozen |
| + |
| +Seal: `6d3ea7fccce1a7f4bc507b6eb8d368ed0b62f83022504aa04c7684c72c93aa9a` → `b60c83f8ba4311222174284420b5327e92002882b4a1c6f291e74e69234c6f59`. |
| + |
| +Overlay: `internal/provision/testdata/plan14-root-reads-held-floor-capability.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`. |
diff --git a/docs/superpowers/specs/2026-10-26-region-ha-without-claims-design.md b/docs/superpowers/specs/2026-10-26-region-ha-without-claims-design.md| index 6e5f7f5ff..b38b1f889 100644 |
| --- a/docs/superpowers/specs/2026-10-26-region-ha-without-claims-design.md |
| +++ b/docs/superpowers/specs/2026-10-26-region-ha-without-claims-design.md |
| @@ -1000,11 +1000,13 @@ the same rule for every box. |
| | C16 | Console and CLI region names | Blind: any member can name its AWS region. | |
| | C17 | Asset status home election | Blind, with the same member routing rules as E2. | |
| | C18 | Domain attach conflict check | Blind: live member routes reserve names, as H2. | |
| -| Scripts | Group roll and boot witness | Aware operator tools: inspect members by reference and check that a completed witness left no member files. The roll tool's §25.9 floor check reads `ha_take` on every live box of the region's view, fixed forwarders included, and refuses a drain unless each says the number 1. A file older than 15 minutes (60 s skew allowed) is skipped: a dead box sends nothing, so it needs no take capability. | |
| +| Scripts | Group roll and boot witness | Aware operator tools: inspect members by reference and check that a completed witness left no member files. The roll tool's §25.9 floor check (E14) reads `ha_handover` on every edges file in the deployment's listing, fixed forwarders included, whatever the file's age, and refuses a drain unless each says the number 1, and unless every box in the config's `fixed_boxes` has a file. There is no age test: a box that is not HA publishes only on change, hours apart, so an age test skipped quiet live boxes. The file is only a hint. A present file without the capability keeps the region on DR-4, naming the box; a present file with it, of any age, still has to acknowledge the withdrawal (E15), or the drain fails. The superseded script still has the old rule (`ha_take`, files under 15 minutes old) and is not used. | |
| | E10 | Silence rule (`Edge.PeerDraining`, read by the activator's `NoteForward`; §25.5) | Blind: a box whose file says `draining` or `ha_drained` is not made silent or suspect for a held answer. Dial failures still make any box suspect. A terminated member that was draining keeps that file until departure, so only its silence is ignored. | |
| | E11 | Holder-cache drop (`notePeerDrained`, §25.4 step 4) | Blind: a file that says `ha_drained` drops this box's holder-cache entries naming that box, once per publication (its `ha_drain` id, else its generation), before the drained acknowledgement. From then until a later publication of that box no longer says `ha_drained`, neither cache installs or follows the box as a holder: a lock read that was in flight across the drop, and a delayed holder answer naming it, are not used (build ruling, 2026-11-09). A stale drained file drops nothing new. A box that is only `draining` stays a holder. | |
| -| E12 | Drain acknowledgement receiver (`/.carlos/ha-drain`, `foldedDrain`, §25.4 step 1) | Blind: it reads the asker's own file by its exact key and answers whether its fold shows `draining` or `ha_drained` under the asked `ha_drain` transaction and id. A file that no longer matches, a stale one included, is answered as not seen. | |
| -| E13 | Take capability (`takeCapable`, `Edge.PeerTakes`; §25.7) | Blind: a box is asked to take only when its file says `ha_take` as the number 1. Absent, other numbers, strings and booleans mean no. A stale member file can still name a successor; the take then fails its dial, and the drain tries the next candidate or fails. | |
| +| E12 | Drain acknowledgement receiver (`/.carlos/ha-drain`, `foldedDrain`, §25.4 step 1) | Blind: it reads the asker's own file by its exact key and answers whether its fold shows `draining` or `ha_drained` under the asked `ha_drain` transaction and id. A file that no longer matches, a stale one included, is answered as not seen. Each ask carries a fresh random nonce, covered by the ask's signature. The answer is signed under the mesh key over a separate domain, the answering box, the asking box, the transaction, the phase, the drain id, the nonce and the answer itself. | |
| +| E13 | Take capability (`takeCapable`, `Edge.PeerTakes`; §25.7) | Blind: a box is asked to take only when its file says `ha_take` as the number 1. Absent, other numbers, strings and booleans mean no. A stale member file can still name a successor; the take then fails its dial, and the drain tries the next candidate or fails. `ha_handover` is not a take capability: a box that is not HA says `ha_handover: 1` and no `ha_take`, and is never asked to take. | |
| +| E14 | Held-requests floor (`ha_handover`, read by the group roll verb's `Engine.Floor`, `internal/grouproll/floor.go`; §25.9) | Blind: every edges file in the deployment's listing counts, member or fixed box, whatever its age. Each must say `ha_handover` as the number 1. Absent, other numbers, `1.0`, strings and booleans are a DR-4 reason naming the box; an unreadable file refuses the transaction. A box in the config's `fixed_boxes` with no file is a DR-4 reason naming it. The config must declare either a non-empty `fixed_boxes` or `"no_fixed_boxes": true`; neither, or both, refuses the transaction. The floor cannot tell a live box from a dead one. A terminated box's leftover file without the capability keeps the region on DR-4; one with the capability passes the floor and then fails the drain at E15, naming the box. Either way it counts until departure removes a member's file or the operator removes a fixed box's (runbook, "A fixed box has been terminated"). | |
| +| E15 | Drain acknowledgement population (the roll verb's floor listing, carried as `drain --peers=`; `publishAndAck` in `internal/host/hadrain.go`, which adds `Edge.DrainAckPeers`; §25.4 step 1) | Blind: one population, read once, by the party that decides. The verb lists `control/edges/` once for the transaction's floor (§25.9), and every box it counted, the member excluded, travels in the drain request. A asks every box on that list, and also any other box with an edges file in its own fold, named by its key, whatever the file's age. The fold may only add boxes. Its completeness is never evidence: after a failed LIST, unreadable files, or no poll since a box published, it is a last-good map. A listed box the fold lacks is asked after one fresh fold read; if it still cannot be read or answer, the drain fails naming it. A drain request without the list, from an older tool, is refused before anything runs. The file is a hint and the live answer is the proof: only a binary with held requests can sign an answer for the ask (E12). Anything else is not an acknowledgement: an unsigned body, a bad signature, an answer to another ask (its nonce differs), a 404, or a tenant app's page behind an older binary. A box rolled back to an older binary keeps the newer binary's capable file but cannot answer, and a dead box's leftover file cannot answer, so the drain fails before any move, naming each box. A box that first publishes after the verb's listing is on the list only if A's fold has read it by then; §25.9 says why that window is bounded. | |
| The drain state reuses the existing box-level `draining` field, so the |
| placement readers already listed (E5, C1, C6, C10, H5, and db-read |
| @@ -1098,7 +1100,7 @@ The roll tool runs a new root verb, `carlos system group-maintenance drain`, ove |
| 1. **Withdraw, acknowledged.** A publishes a box-level drain state in its edges file, and from then on places nothing on itself. The field withdraws placement only. Name authority, admission and holder reachability are unchanged, so A keeps answering as a holder and a forwarder (R2.9). Placement reads it as local-denied (`internal/edge/wakeplacement.go:36-42`), and that includes §6.3 rule 1, so a clean marker naming A no longer sends a wake to A. The builder fixes the field with a reader table under §24's rule. |
| - A timer does not prove that peers folded the change (R2.9). So A sends a signed `/.carlos/ha-drain` hop to every live box of the deployment that views its region, fixed forwarders and other regions included. Each receiver refreshes its fold of A's edges file at once, which is one normal fold read, and answers whether it now sees A draining. A asks again every 5 s. Each request names the drain transaction and the generation of A's edges file. A receiver that has already folded that generation answers from memory with no new read, so each receiver costs one fold read per round however often it is asked (R3.9). The drain goes on only once every such box has acknowledged. A box that cannot be reached, or does not acknowledge within 2 minutes, makes the drain fail (failures, below). |
| + A timer does not prove that peers folded the change (R2.9). So A sends a signed `/.carlos/ha-drain` hop to every box on the roll verb's list, plus any other box with an edges file in A's own fold, whatever the file's age (E15), fixed forwarders and other regions included. The list is the verb's single read of `control/edges/` for the transaction's floor, every box it counted except A, carried in the drain request (`drain --peers=`); a request without it is refused before anything runs. A's fold may add boxes to the list but never remove one, and a listed box A's fold lacks is asked after one fresh fold read. Each receiver refreshes its fold of A's edges file at once, which is one normal fold read, and answers whether it now sees A draining. Each ask carries a fresh random nonce, and the answer is signed under the mesh key over the two boxes, the transaction, the phase, the drain id, the nonce and the answer (E12). A counts only an answer signed for that ask. An older binary cannot sign one, and a tenant app it might pass the path to cannot either, so neither acknowledges. A asks again every 5 s. Each request names the drain transaction and the generation of A's edges file. A receiver that has already folded that generation answers from memory with no new read, so each receiver costs one fold read per round however often it is asked (R3.9). The drain goes on only once every such box has acknowledged. A box that cannot be reached, or does not acknowledge within 2 minutes, makes the drain fail (failures, below). |
| 2. **Quiesce (H5).** A closes its local start gate for tenant leases. It then settles everything that crossed the gate before it closed: wakes that are restoring, acquires waiting on their conditional PUT, and lost-lease recovery workers. Each either ends awake, and is then moved in step 3, or fails. Pending stops and marker obligations are kept and settled (§5.2). Nothing is cancelled in a way that would drop a writer proof. |
| 3. **Move each awake host H,** up to 4 at a time, busiest first: |
| 1. *Hold.* From now `MoveState(H)` is `holding` (§25.5). |
| @@ -1196,7 +1198,13 @@ Both control paths, `/.carlos/ha-take` and `/.carlos/ha-drain`, are reserved on |
| ### 25.9 The floor |
| A drain is only safe when every box that may send A a request understands the new headers, and successors understand a take. So: |
| -- `drain` refuses unless every live box of the deployment that views the region publishes `ha_take: 1`. The same release adds every behaviour in this section. Fixed forwarders such as adi count. |
| +- `drain` refuses unless every box of the deployment publishes `ha_handover: 1`. Every box on a release with this section writes it, HA or not, with no setting: it says the binary understands the held-requests headers (`X-Carlos-Handover`, the replay mark) and the drain acknowledgement. Fixed forwarders such as adi count. A take still needs `ha_take: 1` and a box serving the pool (E13); `ha_handover` never makes a box a take candidate. |
| +- The floor counts every edges file present in the deployment's `control/edges/` listing, whatever its age (E14). An age test would hide quiet live boxes: a box that is not HA publishes only on change, often hours apart, and could forward to the member on an old binary. |
| +- The file is a hint, not proof of what the box runs now. A start does not always republish it: a writer that does not know `ha_handover` decodes the stored file into its own struct, drops the field, finds nothing changed and skips the write. So a box rolled back to an older binary keeps the newer binary's `ha_handover: 1`. The proof is the withdrawal's acknowledgement (§25.4 step 1, E15): every box with a file, capable or not, of any age, must answer it, and only a binary with held requests can. A box that cannot answer, rolled back or dead, fails the drain before any move, naming it, and the member returns as for any failed drain. |
| +- One population, read once, by the party that decides: the verb's listing of `control/edges/` for this floor is also the drain's acknowledgement population. The verb passes every box it counted, the member excluded, in the drain request, and the member asks every one of them, plus any box its own fold adds (E15). An empty list is valid only when the floor counted no other box. S3 LIST is strongly consistent, so a box whose file existed at the floor's read is on the list. The floor row records this rule as `"population": "all-files-v1"`, and the drain list is built only from a row with that marker and a `live` array of valid, distinct references. A transaction whose floor predates the marker, written by an older tool that kept only fresh files, cannot be resumed into a drain: the tool refuses and the operator ends it with abandon, return, cancel-drain or close-lost. |
| +- The residual is a brand-new box that first publishes during the drain window: it is not on the list, and is asked only if the member's fold reads it in time. This is bounded. A group member cannot serve before it is admitted, and admission requires its own booting publication to have succeeded (`internal/host/group_admission.go:139-145, 170`; `internal/groupadmission/state.go:12`). New fixed boxes are added by the operator, so the operator does not add one while a transaction is running (one sentence for the runbook). |
| +- A present file without the capability keeps DR-4, naming the box. A capable leftover file of a dead box passes the floor and fails the drain until departure removes a member's file or the operator removes a fixed box's (runbook, "A fixed box has been terminated"). |
| +- A fixed box can serve and forward with no edges file: its publisher runs beside the edge, and a first write that fails does not stop it serving. So the verb's config lists every fixed box of the deployment that may forward, in any region, as `fixed_boxes`, and a listed box with no file keeps DR-4, naming it. A deployment with no fixed boxes says so with `"no_fixed_boxes": true`. The config must have exactly one of a non-empty `fixed_boxes` and `"no_fixed_boxes": true`; neither (a missing or empty list with `no_fixed_boxes` false or absent), or both, refuses the transaction. Silence is never read as "no fixed boxes". No existing source gives the verb this set: the operator role reads only `control/edges/*` and no SSM parameter, and `CARLOS_HA_FIXED_BOX_IDENTITIES` lists only a region's fixed boxes, optionally, in host.env and SSM. Group members need no list: a member takes no traffic until it is admitted, and admission waits for its first booting publication to succeed (`internal/groupadmission/state.go:12`, `internal/host/group_admission.go:139-145, 170`). |
| - `replace` also checks that the release the pinned launch template boots (`group_config.release`, `infra/modules/region-host/group.tf:50`) is at or above the floor. After the launch, it checks that the replacement publishes `ha_take: 1`. |
| - **First install.** Rolling a group onto the first release with §25 cannot drain. That roll uses today's DR-4 rule, replacing only lock-free members, and the tool says which rule it applied. |
| - A rollback below the floor brings DR-4 back. The tool checks the floor on every transaction. |
| @@ -1267,7 +1275,8 @@ W1 to W4 passing on a release at the floor is what retires the DR-4 rule. |
| - **Shape:** |
| - the nested layout; |
| - the region in group mode (`infra/modules/region-host`), with its NLB, launch hook, terminations queue and rule; |
| - - `CARLOS_REGION_HA` and `CARLOS_GROUP_ADMISSION` on the members, and `CARLOS_REGION_HA=1` on every fixed box that forwards into the region: a box without it publishes no `ha_take`, and the §25.9 floor keeps the region on DR-4; |
| + - `CARLOS_REGION_HA` and `CARLOS_GROUP_ADMISSION` on the members. Fixed boxes need no `CARLOS_REGION_HA` for the §25.9 floor, only a release at the floor: every box on such a release publishes `ha_handover: 1`, and answers the drain's acknowledgement. A fixed box whose edges file has no `ha_handover: 1` keeps the region on DR-4. A fixed box rolled back below the floor, or terminated with its file left behind, fails each drain, naming it, until it is updated or its file is removed; |
| + - the roll tool's config lists every fixed box of the deployment that may forward into the region in `fixed_boxes`, whatever its region, or sets `"no_fixed_boxes": true` when the deployment has none; |
| - chrony, and SSM on the members for the roll tool. |
| - **Pool:** a named HA pool in `CONSOLE_HA_CAPACITY_CONFIG` (`ha_pools`), and `CONSOLE_HA_REGIONS` on the console (§23). |
| - **Which instances benefit:** only born-HA instances in that pool (N-HA7). Existing instances need the operator migration slice, which is not built. Until it is, they resize the old way. |
diff --git a/docs/superpowers/specs/2026-11-09-group-roll-verb-design.md b/docs/superpowers/specs/2026-11-09-group-roll-verb-design.md| index 0d0d2c484..2520d4409 100644 |
| --- a/docs/superpowers/specs/2026-11-09-group-roll-verb-design.md |
| +++ b/docs/superpowers/specs/2026-11-09-group-roll-verb-design.md |
| @@ -109,7 +109,12 @@ flags-after-positionals trap of `cli-default-console-flagship` cannot arise. |
| - **The config file is the script's config file.** The same JSON keys, the same |
| validation (`validate_config`, `:506-545`, plus the `held-floor-sha-map` |
| keys `release_public_key`, `release_channels`, `release_platform`), so one file |
| - serves both tools during the overlap (§11). No key is added. |
| + serves both tools during the overlap (§11). Two keys are added after the |
| + overlap (held floor capability, 2026-11-10, region HA spec §25.9), which |
| + the superseded script refuses: `fixed_boxes`, a list of the fixed box |
| + references that may forward to a member, and `no_fixed_boxes`, a |
| + boolean. The floor needs exactly one of a non-empty `fixed_boxes` and |
| + `"no_fixed_boxes": true`; neither or both refuses the transaction. |
| - **Exit codes and output** follow the script: 0 on success, 1 on a refusal with |
| `Refused: <reason>` on stderr, phase lines `phase: detail` on stdout, the JSON |
| drain summary line, and `status` printing the saved transaction as one JSON |
| @@ -192,7 +197,7 @@ with a `_other.go` sibling, per the cross-compile gate. |
| | | Target health in each target group | |
| | `Classify` (the script's `classify()`) and `TerminateDecision` (`terminate_decision()`) | Lower or raise minimum; raise desired (H4: never lower) | |
| | Preflight shape rules, readiness, identity, permit and process checks over box status | Park a member: `EnterStandby` with decrement; unpark: `ExitStandby` | |
| -| The floor: edges files, `ha_take`, the pinned and the prepared release (§9) | Terminate a parked member without decrement | |
| +| The floor: every present edges file's `ha_handover` (no age test; region HA §25.9), the pinned and the prepared release (§9) | Terminate a parked member without decrement | |
| | The drain, the H5 pre-action check, the lock sweep (S3-compatible reads of the data bucket) | Scaling activities for one member, classified enter, exit or terminate | |
| | The depart watch and its reports | The lifecycle hook description; whether a member is online for sessions; whether an instance is gone | |
| | The box-verb protocol: the framed remote command and parsing its output | Running one framed remote command on one member (Session Manager) | |
diff --git a/infra/modules/region-group-operator-document/README.md b/infra/modules/region-group-operator-document/README.md| index 3e0829112..0483cf6cb 100644 |
| --- a/infra/modules/region-group-operator-document/README.md |
| +++ b/infra/modules/region-group-operator-document/README.md |
| @@ -59,7 +59,7 @@ printf %s B64 | base64 -d | /opt/carlos/carlos system group-maintenance permit & |
| /opt/carlos/carlos system group-maintenance revoke |
| /usr/bin/timeout --signal=TERM --kill-after=30s 900s /opt/carlos/carlos system group-maintenance apply |
| /usr/bin/timeout --signal=TERM --kill-after=30s 900s /opt/carlos/carlos system group-maintenance rollback |
| -/usr/bin/timeout --signal=TERM --kill-after=30s 3600s /opt/carlos/carlos system group-maintenance drain TX |
| +/usr/bin/timeout --signal=TERM --kill-after=30s 3600s /opt/carlos/carlos system group-maintenance drain --peers=PEERS TX |
| /usr/bin/timeout --signal=TERM --kill-after=30s 300s /opt/carlos/carlos system group-maintenance drain --cancel TX && /opt/carlos/carlos system group-maintenance status |
| /opt/carlos/carlos system group-maintenance fence-clear TX && /opt/carlos/carlos system group-maintenance status |
| /usr/bin/timeout --signal=TERM --kill-after=10s 120s /usr/bin/systemctl stop carlos-edge.service; /usr/bin/systemctl show --property=MainPID --property=ActiveState carlos-edge.service |
diff --git a/infra/modules/region-group-operator-document/tool-pattern.txt b/infra/modules/region-group-operator-document/tool-pattern.txt| index cfbd1c7b1..7d9224b5d 100644 |
| --- a/infra/modules/region-group-operator-document/tool-pattern.txt |
| +++ b/infra/modules/region-group-operator-document/tool-pattern.txt |
| @@ -1 +1 @@ |
| -/usr/bin/env -i PATH=/usr/sbin:/usr/bin:/sbin:/bin HOME=/root /bin/sh -c '\[ "\$\(id -u\)" = 0 \] \|\| exit 77; printf '"'"'\\n[0-9a-f]{32}:BEGIN\\n'"'"'; \((/opt/carlos/carlos system group-maintenance (status|revoke)|/opt/carlos/carlos system group-maintenance prepare --sha256 [0-9a-f]{64}|printf %s [A-Za-z0-9+/=]+ \| base64 -d \| /opt/carlos/carlos system group-maintenance permit && /opt/carlos/carlos system group-maintenance status|/usr/bin/timeout --signal=TERM --kill-after=30s 900s /opt/carlos/carlos system group-maintenance (apply|rollback)|/usr/bin/timeout --signal=TERM --kill-after=30s 3600s /opt/carlos/carlos system group-maintenance drain [A-Za-z0-9_][A-Za-z0-9_-]{0,79}|/usr/bin/timeout --signal=TERM --kill-after=30s 300s /opt/carlos/carlos system group-maintenance drain --cancel [A-Za-z0-9_][A-Za-z0-9_-]{0,79} && /opt/carlos/carlos system group-maintenance status|/opt/carlos/carlos system group-maintenance fence-clear [A-Za-z0-9_][A-Za-z0-9_-]{0,79} && /opt/carlos/carlos system group-maintenance status|/usr/bin/timeout --signal=TERM --kill-after=10s 120s /usr/bin/systemctl stop carlos-edge\.service; /usr/bin/systemctl show --property=MainPID --property=ActiveState carlos-edge\.service)\); result=\$\?; printf '"'"'\\n[0-9a-f]{32}:END:%s\\n'"'"' "\$result"' |
| +/usr/bin/env -i PATH=/usr/sbin:/usr/bin:/sbin:/bin HOME=/root /bin/sh -c '\[ "\$\(id -u\)" = 0 \] \|\| exit 77; printf '"'"'\\n[0-9a-f]{32}:BEGIN\\n'"'"'; \((/opt/carlos/carlos system group-maintenance (status|revoke)|/opt/carlos/carlos system group-maintenance prepare --sha256 [0-9a-f]{64}|printf %s [A-Za-z0-9+/=]+ \| base64 -d \| /opt/carlos/carlos system group-maintenance permit && /opt/carlos/carlos system group-maintenance status|/usr/bin/timeout --signal=TERM --kill-after=30s 900s /opt/carlos/carlos system group-maintenance (apply|rollback)|/usr/bin/timeout --signal=TERM --kill-after=30s 3600s /opt/carlos/carlos system group-maintenance drain --peers=[A-Za-z0-9._,-]* [A-Za-z0-9_][A-Za-z0-9_-]{0,79}|/usr/bin/timeout --signal=TERM --kill-after=30s 300s /opt/carlos/carlos system group-maintenance drain --cancel [A-Za-z0-9_][A-Za-z0-9_-]{0,79} && /opt/carlos/carlos system group-maintenance status|/opt/carlos/carlos system group-maintenance fence-clear [A-Za-z0-9_][A-Za-z0-9_-]{0,79} && /opt/carlos/carlos system group-maintenance status|/usr/bin/timeout --signal=TERM --kill-after=10s 120s /usr/bin/systemctl stop carlos-edge\.service; /usr/bin/systemctl show --property=MainPID --property=ActiveState carlos-edge\.service)\); result=\$\?; printf '"'"'\\n[0-9a-f]{32}:END:%s\\n'"'"' "\$result"' |
diff --git a/internal/edge/hadrain.go b/internal/edge/hadrain.go| index 8bcf2269b..662644f10 100644 |
| --- a/internal/edge/hadrain.go |
| +++ b/internal/edge/hadrain.go |
| @@ -4,6 +4,7 @@ import ( |
| "bytes" |
| "context" |
| "crypto/hmac" |
| + "crypto/rand" |
| "crypto/sha256" |
| "encoding/hex" |
| "encoding/json" |
| @@ -46,6 +47,11 @@ import ( |
| // carries its own mesh-key signature over the receiver, the method, the |
| // path, the drain transaction, the timestamp and the body. The ordinary hop |
| // signature binds only host and time (mesh.go), so it is not enough here. |
| +// A drain ask also carries a fresh nonce, and the answer is signed under |
| +// the mesh key over the receiver, the asker, the transaction, the phase, |
| +// the id, that nonce and the answer (haDrainAnswerMAC). The asker counts |
| +// nothing else as an acknowledgement: an older binary, or a tenant app |
| +// behind one, cannot sign, and an answer to another ask fails its nonce. |
| // |
| // This reader is member-blind (§24.3): it reads the asker's own file, by |
| // its exact key, whatever its name shape, region or pool. A terminated |
| @@ -78,18 +84,25 @@ const ( |
| // hopDoorDomain makes. |
| const haControlDomain = "carlos-ha-control\x00" |
| +// haDrainAnswerDomain separates the drain answer's MAC from the ask's and |
| +// every other mesh-key MAC. |
| +const haDrainAnswerDomain = "carlos-ha-drain-answer\x00" |
| + |
| // The phases an ask names. |
| const ( |
| DrainPhaseDraining = "draining" |
| DrainPhaseDrained = "drained" |
| ) |
| -// haDrainAsk is the ask's JSON body. |
| +// haDrainAsk is the ask's JSON body. Nonce is 16 fresh random bytes in |
| +// lower-case hex, chosen by the asker for this ask alone: the answer's MAC |
| +// covers it, so an answer to another ask cannot be replayed. |
| type haDrainAsk struct { |
| From string `json:"from"` |
| Txn string `json:"txn"` |
| Phase string `json:"phase"` |
| ID uint64 `json:"id"` |
| + Nonce string `json:"nonce"` |
| } |
| // haDrainMarkView is a file's ha_drain object. |
| @@ -98,9 +111,54 @@ type haDrainMarkView struct { |
| ID uint64 `json:"id"` |
| } |
| -// haDrainAnswer is the receiver's answer. |
| +// haDrainAnswer is the receiver's answer: seen, and Sig, the hex MAC |
| +// (haDrainAnswerMAC) under the mesh key. Only a receiver that holds the |
| +// mesh key and runs this build can sign it, so an older binary, or a |
| +// tenant app behind one, cannot acknowledge (held floor capability |
| +// ruling, 2026-11-10). Seen is a pointer so an answer without it is |
| +// refused, never read as false or true. |
| type haDrainAnswer struct { |
| - Seen bool `json:"seen"` |
| + Seen *bool `json:"seen"` |
| + Sig string `json:"sig"` |
| +} |
| + |
| +// haDrainNonce is a valid ask nonce: 32 lower-case hex digits. |
| +func haDrainNonce(s string) bool { |
| + if len(s) != 32 { |
| + return false |
| + } |
| + for i := 0; i < len(s); i++ { |
| + if c := s[i]; (c < '0' || c > '9') && (c < 'a' || c > 'f') { |
| + return false |
| + } |
| + } |
| + return true |
| +} |
| + |
| +// haDrainAnswerMAC is the answer's HMAC over the domain, the receiver |
| +// (answering) box, the asking box, the transaction, the phase, the |
| +// publication id, the ask's nonce and the answer. |
| +func haDrainAnswerMAC(key []byte, receiver string, ask haDrainAsk, seen bool) []byte { |
| + mac := hmac.New(sha256.New, key) |
| + for _, part := range []string{haDrainAnswerDomain, receiver, ask.From, ask.Txn, ask.Phase, |
| + strconv.FormatUint(ask.ID, 10), ask.Nonce, strconv.FormatBool(seen)} { |
| + mac.Write([]byte(part)) |
| + mac.Write([]byte("\n")) |
| + } |
| + return mac.Sum(nil) |
| +} |
| + |
| +// verifyHADrainAnswer checks an answer's MAC under either mirrored key, in |
| +// constant time. |
| +func verifyHADrainAnswer(current, next []byte, receiver string, ask haDrainAsk, seen bool, sig string) bool { |
| + got, err := hex.DecodeString(sig) |
| + if err != nil || len(got) != sha256.Size { |
| + return false |
| + } |
| + if len(next) > 0 && hmac.Equal(got, haDrainAnswerMAC(next, receiver, ask, seen)) { |
| + return true |
| + } |
| + return len(current) > 0 && hmac.Equal(got, haDrainAnswerMAC(current, receiver, ask, seen)) |
| } |
| // haControlPath reports whether p, cleaned, is one of the reserved control |
| @@ -231,16 +289,17 @@ func (e *Edge) serveHAControl(w http.ResponseWriter, r *http.Request) { |
| } |
| var ask haDrainAsk |
| if json.Unmarshal(body, &ask) != nil || ask.Txn != txn || !haControlField(ask.From) || ask.From == e.box || ask.ID == 0 || |
| - (ask.Phase != DrainPhaseDraining && ask.Phase != DrainPhaseDrained) { |
| + (ask.Phase != DrainPhaseDraining && ask.Phase != DrainPhaseDrained) || !haDrainNonce(ask.Nonce) { |
| refuseHAControl(w) |
| return |
| } |
| ctx, cancel := context.WithTimeout(r.Context(), haDrainRefreshTimeout) |
| defer cancel() |
| seen := m.drainSeen(ctx, ask) |
| + sig := hex.EncodeToString(haDrainAnswerMAC(signingKey(current, next), e.box, ask, seen)) |
| w.Header().Set("Content-Type", "application/json") |
| w.Header().Set("Cache-Control", "no-store") |
| - json.NewEncoder(w).Encode(haDrainAnswer{Seen: seen}) |
| + json.NewEncoder(w).Encode(haDrainAnswer{Seen: &seen, Sig: sig}) |
| } |
| // drainAcks is the receiver's memory of answered asks (R3.9). mu also |
| @@ -466,10 +525,28 @@ func (e *Edge) AskDrainSeen(ctx context.Context, peer, txn, phase string, id uin |
| return false, errors.New("ha-drain: no mesh key to sign with") |
| } |
| dial, host, err := m.controlTarget(peer, e.certs.Load()) |
| + if errors.Is(err, errNoControlFile) { |
| + // A box on the verb's list that this fold has not read yet (it |
| + // published after the last poll, or polls have failed): read the |
| + // fold once now, as a receiver does for an ask, then try again. |
| + // Still absent, or unreadable, the ask fails and names the box. |
| + rctx, rcancel := context.WithTimeout(ctx, haDrainRefreshTimeout) |
| + rerr := m.refreshHostsNow(rctx) |
| + rcancel() |
| + if rerr != nil { |
| + return false, fmt.Errorf("%w (fold read: %v)", err, rerr) |
| + } |
| + dial, host, err = m.controlTarget(peer, e.certs.Load()) |
| + } |
| if err != nil { |
| return false, err |
| } |
| - body, err := json.Marshal(haDrainAsk{From: e.box, Txn: txn, Phase: phase, ID: id}) |
| + var nonce [16]byte |
| + if _, err := rand.Read(nonce[:]); err != nil { |
| + return false, fmt.Errorf("ha-drain: nonce: %w", err) |
| + } |
| + ask := haDrainAsk{From: e.box, Txn: txn, Phase: phase, ID: id, Nonce: hex.EncodeToString(nonce[:])} |
| + body, err := json.Marshal(ask) |
| if err != nil { |
| return false, err |
| } |
| @@ -499,9 +576,18 @@ func (e *Edge) AskDrainSeen(ctx context.Context, peer, txn, phase string, id uin |
| if err := json.NewDecoder(io.LimitReader(resp.Body, 4<<10)).Decode(&ans); err != nil { |
| return false, fmt.Errorf("ha-drain: %s's answer: %w", peer, err) |
| } |
| - return ans.Seen, nil |
| + // An answer is an acknowledgement only when signed for this ask: an |
| + // unsigned body, a bad MAC or another ask's answer fails closed. |
| + current, next = m.meshKeys() |
| + if ans.Seen == nil || !verifyHADrainAnswer(current, next, peer, ask, *ans.Seen, ans.Sig) { |
| + return false, fmt.Errorf("ha-drain: %s's answer is not signed for this ask", peer) |
| + } |
| + return *ans.Seen, nil |
| } |
| +// errNoControlFile is a peer with no edges file in this edge's fold. |
| +var errNoControlFile = errors.New("ha-drain: no edges file") |
| + |
| // controlTarget is where a control request to peer goes: its dial address, |
| // by the same rule a hop uses, and a name to ask for. Every edge serves |
| // every mirrored certificate (certsync.go), and a group member may publish |
| @@ -516,7 +602,7 @@ func (m *homeMap) controlTarget(peer string, certs *certMirror) (dial, host stri |
| snap := m.snapshot() |
| f, ok := snap.files[edgesPrefix+peer+".json"] |
| if !ok || f.Box != peer { |
| - return "", "", fmt.Errorf("ha-drain: no edges file for %s", peer) |
| + return "", "", fmt.Errorf("%w for %s", errNoControlFile, peer) |
| } |
| own, ownKnown := snap.files[edgesPrefix+m.self+".json"] |
| ownKnown = ownKnown && own.Box == m.self |
diff --git a/internal/edge/hadrain_test.go b/internal/edge/hadrain_test.go| index ffdc6e2ce..efec042a7 100644 |
| --- a/internal/edge/hadrain_test.go |
| +++ b/internal/edge/hadrain_test.go |
| @@ -3,11 +3,15 @@ package edge |
| import ( |
| "bytes" |
| "context" |
| + "crypto/hmac" |
| + "crypto/sha256" |
| + "encoding/hex" |
| "encoding/json" |
| "errors" |
| "io" |
| "net/http" |
| "net/http/httptest" |
| + "slices" |
| "strings" |
| "sync" |
| "sync/atomic" |
| @@ -31,6 +35,8 @@ type drainStore struct { |
| lists int |
| gets int |
| fail bool |
| + // failList and failGet fail only that half. |
| + failList, failGet bool |
| } |
| func (d *drainStore) List(ctx context.Context, prefix string) ([]string, error) { |
| @@ -38,7 +44,7 @@ func (d *drainStore) List(ctx context.Context, prefix string) ([]string, error) |
| defer d.mu.Unlock() |
| if prefix == edgesPrefix { |
| d.lists++ |
| - if d.fail { |
| + if d.fail || d.failList { |
| return nil, errors.New("SlowDown: please reduce your request rate") |
| } |
| } |
| @@ -49,7 +55,7 @@ func (d *drainStore) Get(ctx context.Context, key string) ([]byte, string, error |
| d.mu.Lock() |
| if strings.HasPrefix(key, edgesPrefix) { |
| d.gets++ |
| - if d.fail { |
| + if d.fail || d.failGet { |
| d.mu.Unlock() |
| return nil, "", errors.New("SlowDown: please reduce your request rate") |
| } |
| @@ -78,8 +84,18 @@ type drainBox struct { |
| // door counts requests reaching this box's 443; app counts those its |
| // app saw, by path. |
| door atomic.Int64 |
| - mu sync.Mutex |
| - app []string |
| + // old makes the box run a binary from before held requests: nothing |
| + // answers the control paths (404), whatever its stored file says. |
| + old atomic.Bool |
| + // tenant is what an old binary's tenant app answers on the control |
| + // path (200, this body) instead of a 404, when set. |
| + tenant string |
| + // replay makes the box answer every control request with the first |
| + // answer its edge gave. |
| + replay bool |
| + replayed []byte |
| + mu sync.Mutex |
| + app []string |
| } |
| func (x *drainBox) edge() *Edge { return x.be.live.Load().edge } |
| @@ -137,6 +153,31 @@ func (s *drainScene) addWith(t *testing.T, box, ip, host, region string, act Act |
| x.be = be |
| srv := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| x.door.Add(1) |
| + if x.old.Load() && haControlPath(r.URL.Path) { |
| + if x.tenant != "" { |
| + w.Header().Set("Content-Type", "application/json") |
| + io.WriteString(w, x.tenant) |
| + return |
| + } |
| + http.NotFound(w, r) |
| + return |
| + } |
| + if x.replay && haControlPath(r.URL.Path) { |
| + x.mu.Lock() |
| + saved := x.replayed |
| + x.mu.Unlock() |
| + if saved == nil { |
| + rec := httptest.NewRecorder() |
| + be.live.Load().edge.ServeHTTP(rec, r) |
| + saved = rec.Body.Bytes() |
| + x.mu.Lock() |
| + x.replayed = saved |
| + x.mu.Unlock() |
| + } |
| + w.Header().Set("Content-Type", "application/json") |
| + w.Write(saved) |
| + return |
| + } |
| be.live.Load().edge.ServeHTTP(w, r) |
| })) |
| srv.Listener.Close() |
| @@ -565,7 +606,7 @@ func TestHADrainRefusesForgery(t *testing.T) { |
| s.file(t, b, drainGen0, notDrain) |
| s.sync(t) |
| now := time.Now() |
| - body := []byte(`{"from":"annie","txn":"txn-1","phase":"draining","id":101}`) |
| + body := []byte(`{"from":"annie","txn":"txn-1","phase":"draining","id":101,"nonce":"00112233445566778899aabbccddeeff"}`) |
| good := func() (string, string, []byte) { |
| return signHAControl(s.key, "betty", http.MethodPost, HADrainPath, "txn-1", now, body), "txn-1", body |
| } |
| @@ -587,10 +628,14 @@ func TestHADrainRefusesForgery(t *testing.T) { |
| } |
| other := []byte("0123456789abcdef0123456789abcdef") |
| big := bytes.Repeat([]byte("x"), haControlMaxBody+1) |
| - for name, tc := range map[string]struct { |
| + type req = struct { |
| method, auth, txn string |
| body []byte |
| - }{ |
| + } |
| + signed := func(b []byte) req { |
| + return req{http.MethodPost, signHAControl(s.key, "betty", http.MethodPost, HADrainPath, "txn-1", now, b), "txn-1", b} |
| + } |
| + for name, tc := range map[string]req{ |
| "no auth": {http.MethodPost, "", txn, body}, |
| "no txn": {http.MethodPost, auth, "", body}, |
| "other txn": {http.MethodPost, auth, "txn-2", body}, |
| @@ -602,6 +647,9 @@ func TestHADrainRefusesForgery(t *testing.T) { |
| "tampered body": {http.MethodPost, auth, txn, bytes.Replace(body, []byte("annie"), []byte("betty"), 1)}, |
| "hop signature": {http.MethodPost, signHop(s.key, "blog.example.com", now), txn, body}, |
| "oversized": {http.MethodPost, signHAControl(s.key, "betty", http.MethodPost, HADrainPath, "txn-1", now, big), txn, big}, |
| + "no nonce": signed(bytes.Replace(body, []byte(`,"nonce":"00112233445566778899aabbccddeeff"`), nil, 1)), |
| + "short nonce": signed(bytes.Replace(body, []byte(`"00112233445566778899aabbccddeeff"`), []byte(`"0011"`), 1)), |
| + "upper nonce": signed(bytes.Replace(body, []byte(`"00112233445566778899aabbccddeeff"`), []byte(`"00112233445566778899AABBCCDDEEFF"`), 1)), |
| } { |
| if w := post(tc.method, tc.auth, tc.txn, tc.body); w.Code != http.StatusNotFound || w.Body.Len() != 0 { |
| t.Errorf("%s: answered %d %q, want a bare 404", name, w.Code, w.Body.String()) |
| @@ -703,3 +751,216 @@ func TestHAControlSignatureBindsEachPart(t *testing.T) { |
| } |
| } |
| } |
| + |
| +// oldSchemaFile is an edges file as a writer from before ha_handover |
| +// decodes it: the field is not in its struct. |
| +type oldSchemaFile struct { |
| + V int `json:"v"` |
| + Box string `json:"box"` |
| + EIP string `json:"eip"` |
| + Region string `json:"region"` |
| + Generation string `json:"generation"` |
| + Hosts map[string]any `json:"hosts"` |
| +} |
| + |
| +// oldWriterPass is an older writer's restart against x's stored file, the |
| +// shape of seedEdgesFileGate then the pass's write gate: it seeds its gate |
| +// by decoding the stored object into its own struct (dropping |
| +// ha_handover), builds the same file from its unchanged state, and skips |
| +// the PUT when the two match. It reports whether it wrote. |
| +func (s *drainScene) oldWriterPass(t *testing.T, x *drainBox) bool { |
| + t.Helper() |
| + stored, _, err := release.NewDirStore(s.bucket).Get(context.Background(), edgesPrefix+x.box+".json") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + var seed oldSchemaFile |
| + if err := json.Unmarshal(stored, &seed); err != nil { |
| + t.Fatal(err) |
| + } |
| + seed.Generation = "" |
| + gate, _ := json.Marshal(seed) |
| + next, _ := json.Marshal(oldSchemaFile{V: 1, Box: x.box, EIP: x.ip, Region: x.region, |
| + Hosts: map[string]any{x.host: map[string]any{"role": "home"}}}) |
| + if string(gate) == string(next) { |
| + return false |
| + } |
| + putJSON(t, s.seed, edgesPrefix+x.box+".json", string(next)) |
| + return true |
| +} |
| + |
| +// The withdrawal's acknowledgement is the proof the floor's file cannot be |
| +// (held floor capability ruling, 2026-11-10). Every box with a file is |
| +// asked, whatever the file's age: |
| +// - a box rolled back to a binary from before held requests keeps the |
| +// newer binary's capable file (its writer drops the field it does not |
| +// know and skips the PUT), but cannot answer: the ask fails, naming it; |
| +// - a quiet live box whose file is hours old answers, so the drain can |
| +// go on; |
| +// - a dead box's capable leftover file is asked and cannot answer. |
| +func TestHADrainAckEveryFiledBox(t *testing.T) { |
| + s := newDrainScene(t) |
| + s.extra = map[string]map[string]any{"olden": {"ha_handover": 1}, "gone": {"ha_handover": 1}, "quiet": {"ha_handover": 1}} |
| + a := s.add(t, "annie", "127.0.0.11", "shop.example.com", "eu-west-1") |
| + olden := s.add(t, "olden", "127.0.0.12", "blog.example.com", "eu-west-1") |
| + quiet := s.add(t, "quiet", "127.0.0.13", "news.example.com", "us-east-1") |
| + old := time.Now().Add(-6 * time.Hour) |
| + s.file(t, a, drainGen0, notDrain) |
| + s.file(t, olden, old, notDrain) |
| + s.file(t, quiet, old, notDrain) |
| + // gone: a terminated box's leftover file, nothing listening. |
| + gone := &drainBox{box: "gone", ip: "127.0.0.14", host: "gone.example.com", region: "eu-west-1"} |
| + s.file(t, gone, old, notDrain) |
| + s.sync(t) |
| + |
| + olden.old.Store(true) |
| + if s.oldWriterPass(t, olden) { |
| + t.Fatal("the old writer wrote: an unchanged restart skips the PUT") |
| + } |
| + stored, _, err := release.NewDirStore(s.bucket).Get(context.Background(), edgesPrefix+"olden.json") |
| + if err != nil || !strings.Contains(string(stored), `"ha_handover":1`) { |
| + t.Fatalf("the rolled-back box's stored file lost the capability: %s %v", stored, err) |
| + } |
| + |
| + if peers, want := a.edge().DrainAckPeers(), []string{"gone", "olden", "quiet"}; !slices.Equal(peers, want) { |
| + t.Fatalf("peers %v; want %v", peers, want) |
| + } |
| + s.file(t, a, drainGen0.Add(time.Minute), draining1) |
| + if seen, err := askDrain1(a, "quiet"); err != nil || !seen { |
| + t.Fatalf("the quiet live box: seen=%v err=%v, want seen", seen, err) |
| + } |
| + if seen, err := askDrain1(a, "olden"); err == nil || seen || !strings.Contains(err.Error(), "olden answered 404") { |
| + t.Fatalf("the rolled-back box: seen=%v err=%v, want its 404 named", seen, err) |
| + } |
| + if seen, err := askDrain1(a, "gone"); err == nil || seen || !strings.Contains(err.Error(), "gone") { |
| + t.Fatalf("the dead box: seen=%v err=%v, want a failed ask naming it", seen, err) |
| + } |
| +} |
| + |
| +// The answer's wire shape, pinned: {"seen":<bool>,"sig":"<hex HMAC>"} with |
| +// the HMAC-SHA256 under the mesh key over the answer domain, the receiver, |
| +// the asker, the transaction, the phase, the id, the nonce and the answer, |
| +// each followed by a newline. |
| +func TestHADrainAnswerWireShape(t *testing.T) { |
| + s := newDrainScene(t) |
| + a := s.add(t, "annie", "127.0.0.11", "shop.example.com", "eu-west-1") |
| + b := s.add(t, "betty", "127.0.0.12", "blog.example.com", "eu-west-1") |
| + s.file(t, a, drainGen0, draining1) |
| + s.file(t, b, drainGen0, notDrain) |
| + s.sync(t) |
| + nonce := "00112233445566778899aabbccddeeff" |
| + body := []byte(`{"from":"annie","txn":"txn-1","phase":"draining","id":101,"nonce":"` + nonce + `"}`) |
| + r := httptest.NewRequest(http.MethodPost, "http://blog.example.com"+HADrainPath, bytes.NewReader(body)) |
| + r.Header.Set(haControlAuthHeader, signHAControl(s.key, "betty", http.MethodPost, HADrainPath, "txn-1", time.Now(), body)) |
| + r.Header.Set(haControlTxnHeader, "txn-1") |
| + w := httptest.NewRecorder() |
| + b.edge().ServeHTTP(w, r) |
| + mac := hmac.New(sha256.New, s.key) |
| + io.WriteString(mac, "carlos-ha-drain-answer\x00\nbetty\nannie\ntxn-1\ndraining\n101\n"+nonce+"\ntrue\n") |
| + want := `{"seen":true,"sig":"` + hex.EncodeToString(mac.Sum(nil)) + `"}` + "\n" |
| + if w.Code != http.StatusOK || w.Body.String() != want { |
| + t.Fatalf("answer %d %q, want %q", w.Code, w.Body.String(), want) |
| + } |
| +} |
| + |
| +// The asker takes only an answer signed for its own ask (held floor |
| +// capability ruling, 2026-11-10). A tenant app behind an old binary that |
| +// answers {"seen":true}, an unsigned or wrongly signed body, and another |
| +// ask's answer replayed (its nonce differs) are each not acknowledged. A |
| +// correct signed answer is. |
| +func TestHADrainAnswerMustBeSignedForTheAsk(t *testing.T) { |
| + s := newDrainScene(t) |
| + a := s.add(t, "annie", "127.0.0.11", "shop.example.com", "eu-west-1") |
| + s.add(t, "betty", "127.0.0.12", "blog.example.com", "eu-west-1") |
| + old := s.add(t, "olden", "127.0.0.13", "news.example.com", "eu-west-1") |
| + rep := s.add(t, "rerun", "127.0.0.14", "shop2.example.com", "eu-west-1") |
| + for _, x := range s.boxes { |
| + s.file(t, x, drainGen0, notDrain) |
| + } |
| + s.sync(t) |
| + s.file(t, a, drainGen0.Add(time.Minute), draining1) |
| + if seen, err := askDrain1(a, "betty"); err != nil || !seen { |
| + t.Fatalf("a signed answer: seen=%v err=%v", seen, err) |
| + } |
| + old.old.Store(true) |
| + for _, body := range []string{ |
| + `{"seen":true}`, |
| + `{"seen":true,"sig":""}`, |
| + `{"seen":true,"sig":"` + strings.Repeat("00", 32) + `"}`, |
| + `{"sig":"` + strings.Repeat("00", 32) + `"}`, |
| + `<!doctype html><html>an app</html>`, |
| + } { |
| + old.tenant = body |
| + if seen, err := askDrain1(a, "olden"); err == nil || seen { |
| + t.Fatalf("tenant answer %s: seen=%v err=%v, want refused", body, seen, err) |
| + } |
| + } |
| + rep.replay = true |
| + if seen, err := askDrain1(a, "rerun"); err != nil || !seen { |
| + t.Fatalf("the first, recorded answer: seen=%v err=%v", seen, err) |
| + } |
| + if seen, err := askDrain1(a, "rerun"); err == nil || seen || !strings.Contains(err.Error(), "not signed for this ask") { |
| + t.Fatalf("a replayed answer: seen=%v err=%v, want refused", seen, err) |
| + } |
| +} |
| + |
| +// Astra r2 F2.1: the member's fold is a last-good map. After a failed |
| +// LIST, a LIST whose every GET fails, or with no poll since olden first |
| +// published, the fold does not hold olden. So the fold cannot be the |
| +// population: the verb's list is, and the member asks every box on it. An |
| +// ask for a box the fold lacks reads the fold once; if olden still cannot |
| +// be read, the ask fails naming it. Once the store answers again, within |
| +// the same bound, olden is read and answers (the recovery case). |
| +func TestHADrainAckListedBoxTheFoldLacks(t *testing.T) { |
| + for _, tc := range []string{"failed LIST", "every GET fails", "no poll since"} { |
| + t.Run(tc, func(t *testing.T) { |
| + s := newDrainScene(t) |
| + a := s.add(t, "annie", "127.0.0.11", "shop.example.com", "eu-west-1") |
| + olden := s.add(t, "olden", "127.0.0.12", "blog.example.com", "eu-west-1") |
| + s.file(t, a, drainGen0, notDrain) |
| + // annie's fold is read before olden publishes. |
| + if err := a.be.mirror.Refresh(context.Background()); err != nil { |
| + t.Fatal(err) |
| + } |
| + refreshHomeMap(t, a.be.homes) |
| + s.file(t, olden, drainGen0, notDrain) |
| + if err := olden.be.mirror.Refresh(context.Background()); err != nil { |
| + t.Fatal(err) |
| + } |
| + refreshHomeMap(t, olden.be.homes) |
| + s.key, _ = a.be.homes.meshKeys() |
| + s.file(t, a, drainGen0.Add(time.Minute), draining1) |
| + switch tc { |
| + case "failed LIST": |
| + a.store.mu.Lock() |
| + a.store.failList = true |
| + a.store.mu.Unlock() |
| + case "every GET fails": |
| + a.store.mu.Lock() |
| + a.store.failGet = true |
| + a.store.mu.Unlock() |
| + } |
| + if tc != "no poll since" { |
| + // A poll runs and fails: the fold keeps its last-good map. |
| + if err := a.be.homes.Refresh(context.Background()); err == nil { |
| + t.Fatal("the failing poll succeeded") |
| + } |
| + } |
| + if slices.Contains(a.edge().DrainAckPeers(), "olden") { |
| + t.Fatal("the fold already holds olden: the case is vacuous") |
| + } |
| + if tc != "no poll since" { |
| + if seen, err := askDrain1(a, "olden"); err == nil || seen || !strings.Contains(err.Error(), "olden") { |
| + t.Fatalf("a listed box the fold cannot read: seen=%v err=%v, want a failed ask naming it", seen, err) |
| + } |
| + a.store.mu.Lock() |
| + a.store.failList, a.store.failGet = false, false |
| + a.store.mu.Unlock() |
| + } |
| + // The ask reads the fold once and olden answers. |
| + if seen, err := askDrain1(a, "olden"); err != nil || !seen { |
| + t.Fatalf("recovery: seen=%v err=%v", seen, err) |
| + } |
| + }) |
| + } |
| +} |
diff --git a/internal/edge/hadrainconns.go b/internal/edge/hadrainconns.go| index fcbb6eda2..e290c3681 100644 |
| --- a/internal/edge/hadrainconns.go |
| +++ b/internal/edge/hadrainconns.go |
| @@ -11,6 +11,7 @@ import ( |
| "net" |
| "net/http" |
| "slices" |
| + "strings" |
| "sync" |
| "sync/atomic" |
| "time" |
| @@ -19,29 +20,27 @@ import ( |
| "github.com/carlosframework/platform/internal/registry" |
| ) |
| -// DrainAckPeers is every other box of the deployment whose edges file is |
| -// live now (its generation fresh, boxchoice.HeadroomFresh): fixed boxes, |
| -// group members and boxes of other regions alike, since every live box |
| -// folds the whole deployment and so views this box's region (§25.4 step |
| -// 1). Memory only. Sorted. |
| -func (e *Edge) DrainAckPeers(now time.Time) []string { |
| +// DrainAckPeers is every other box with an edges file in this edge's fold, |
| +// by its key, whatever the file's age. It only ADDS to a drain's |
| +// acknowledgement population: the population is the verb's list, read once |
| +// from its own listing of control/edges/ and carried in the drain request |
| +// (§25.4 step 1; held floor capability ruling, 2026-11-10). The fold is a |
| +// last-good routing map, so its completeness is never evidence: a failed |
| +// LIST, unreadable files or a poll not yet run leave it as it was. A box |
| +// the fold adds (one that published after the verb's listing) is asked |
| +// like any other. Memory only. Sorted. |
| +func (e *Edge) DrainAckPeers() []string { |
| m := e.homes.Load() |
| if m == nil { |
| return nil |
| } |
| - snap := m.snapshot() |
| - seen := map[string]bool{} |
| var out []string |
| - for _, f := range snap.files { |
| - if f.Box == "" || f.Box == m.self || seen[f.Box] { |
| + for key := range m.snapshot().files { |
| + box := strings.TrimSuffix(strings.TrimPrefix(key, edgesPrefix), ".json") |
| + if box == "" || box == m.self { |
| continue |
| } |
| - var gen string |
| - if !placementField(f.Generation, &gen) || !boxchoice.HeadroomFresh(gen, now) { |
| - continue |
| - } |
| - seen[f.Box] = true |
| - out = append(out, f.Box) |
| + out = append(out, box) |
| } |
| slices.Sort(out) |
| return out |
diff --git a/internal/edge/hadrainconns_test.go b/internal/edge/hadrainconns_test.go| index af23ecf1a..831810156 100644 |
| --- a/internal/edge/hadrainconns_test.go |
| +++ b/internal/edge/hadrainconns_test.go |
| @@ -17,27 +17,54 @@ import ( |
| "github.com/carlosframework/platform/internal/registry" |
| ) |
| -// The drain asks every other live box, whatever its region or kind, and |
| -// no box whose file is stale. |
| -func TestDrainAckPeersAreTheLiveBoxes(t *testing.T) { |
| +// ackMap is a home map read in full from files keyed by their box. |
| +func ackMap(t *testing.T, files ...map[string]any) *homeMap { |
| + t.Helper() |
| + m := newHomeMap(nil, "self") |
| + snap := &homeSnapshot{files: map[string]edgesFileView{}, read: true, departureComplete: true} |
| + for _, f := range files { |
| + key := edgesPrefix + f["box"].(string) + ".json" |
| + if k, ok := f["key"].(string); ok { |
| + key = k |
| + delete(f, "key") |
| + } |
| + parsed, err := parseEdgesFile(key, wakeBody(t, f)) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + snap.files[key] = parsed |
| + } |
| + snap.hosts, _ = foldHomes(snap.files, m.self, false) |
| + m.snap = snap |
| + return m |
| +} |
| + |
| +// The fold adds every other box with an edges file, whatever its region, |
| +// kind or the file's age, named by its key. It is never proof of a |
| +// complete population (held floor capability ruling, 2026-11-10): that is |
| +// the verb's list, so its flags are not read here. |
| +func TestDrainAckPeersAreEveryFiledBox(t *testing.T) { |
| now := time.Now().UTC() |
| - fresh, stale := now.Format(time.RFC3339), now.Add(-time.Hour).Format(time.RFC3339) |
| - m := wakeMap(t, |
| + fresh, stale := now.Format(time.RFC3339), now.Add(-6*time.Hour).Format(time.RFC3339) |
| + m := ackMap(t, |
| map[string]any{"v": 1, "box": "self", "generation": fresh, "region": "ie"}, |
| map[string]any{"v": 1, "box": "b", "generation": fresh, "region": "ie"}, |
| map[string]any{"v": 1, "box": "g-0123456789abcdef0123", "generation": fresh, "region": "ie"}, |
| map[string]any{"v": 1, "box": "far", "generation": fresh, "region": "us-east-1"}, |
| - map[string]any{"v": 1, "box": "dead", "generation": stale, "region": "ie"}, |
| + map[string]any{"v": 1, "box": "dead", "generation": stale, "region": "ie", "ha_handover": 1}, |
| map[string]any{"v": 1, "box": "nogen", "region": "ie"}, |
| + // A file whose box is not its key's is asked by its key, so the |
| + // ask fails (controlTarget) and the drain names it. |
| + map[string]any{"v": 1, "box": "other", "key": edgesPrefix + "misfiled.json", "generation": fresh}, |
| ) |
| + m.snap.departureComplete = false // not read: the fold only adds |
| e := &Edge{} |
| e.homes.Store(m) |
| - got := e.DrainAckPeers(now) |
| - if want := []string{"b", "far", "g-0123456789abcdef0123"}; !slices.Equal(got, want) { |
| + if got, want := e.DrainAckPeers(), []string{"b", "dead", "far", "g-0123456789abcdef0123", "misfiled", "nogen"}; !slices.Equal(got, want) { |
| t.Fatalf("peers %v, want %v", got, want) |
| } |
| - if (&Edge{}).DrainAckPeers(now) != nil { |
| - t.Fatal("peers without a fold") |
| + if p := (&Edge{}).DrainAckPeers(); p != nil { |
| + t.Fatalf("peers without a fold: %v", p) |
| } |
| } |
diff --git a/internal/edge/hatake_test.go b/internal/edge/hatake_test.go| index 3171b52fd..6fc2645df 100644 |
| --- a/internal/edge/hatake_test.go |
| +++ b/internal/edge/hatake_test.go |
| @@ -209,15 +209,18 @@ func TestTakeAnswersWithoutAHolder(t *testing.T) { |
| } |
| // A peer whose file does not say ha_take: 1 is never sent a take: on an |
| -// older box the path would reach a tenant's app. |
| +// older box the path would reach a tenant's app. ha_handover: 1 alone (a |
| +// box that understands held requests but is not HA, §25.9) is not a take |
| +// capability either. |
| func TestTakeOnlyToAPeerThatSaysSo(t *testing.T) { |
| - for name, v := range map[string]any{"absent": nil, "0": 0, "2": 2, "a string": "1", "true": true} { |
| + for name, fields := range map[string]map[string]any{"absent": nil, "0": {"ha_take": 0}, "2": {"ha_take": 2}, |
| + "a string": {"ha_take": "1"}, "true": {"ha_take": true}, "ha_handover alone": {"ha_handover": 1}} { |
| t.Run(name, func(t *testing.T) { |
| s := newTakeScene(t) |
| - if v == nil { |
| + if fields == nil { |
| delete(s.extra, "betty") |
| } else { |
| - s.extra["betty"] = map[string]any{"ha_take": v} |
| + s.extra["betty"] = fields |
| } |
| s.file(t, s.betty, drainGen0.Add(time.Second), notDrain) |
| s.sync(t) |
diff --git a/internal/edge/testdata/edges-forward-hub.json b/internal/edge/testdata/edges-forward-hub.json| index afc899c1b..5d64d4f05 100644 |
| --- a/internal/edge/testdata/edges-forward-hub.json |
| +++ b/internal/edge/testdata/edges-forward-hub.json |
| @@ -1 +1 @@ |
| -{"v":1,"box":"hub","eip":"198.51.100.7","hibernation_configured":false,"serves_shared_pool":false,"accepts_inbound":false,"named_pools":[],"burst_notices":true,"capabilities":["names-2"],"moves_protocol":0,"seeds_protocol":0,"addrs":null,"generation":"2026-10-30T00:00:00Z","hosts":{"*.bah-certonly.example.com":{"role":"wildcard","platform":false,"wildcard":true},"*.bah-certs.example.com":{"role":"wildcard","platform":false,"wildcard":true},"*.bah-regional.example.com":{"role":"wildcard","platform":false,"wildcard":true},"*.bah-wild.example.com":{"role":"home","platform":false,"alias":true,"wildcard":true,"account":"bah","app":"shop","target_host":"shop.bah.example.com"},"bah-certonly.example.com":{"role":"home","platform":false,"alias":true,"account":"bah","app":"shop","target_host":"shop.bah.example.com"},"shop.bah-custom.example.com":{"role":"home","platform":false,"alias":true,"account":"bah","app":"shop","target_host":"shop.bah.example.com"},"shop.bah.example.com":{"role":"home","platform":true,"account":"bah","app":"shop"},"tickets.example.com":{"role":"home","platform":false,"alias":true,"account":"bah","app":"shop","target_host":"shop.bah.example.com"}}} |
| +{"v":1,"box":"hub","eip":"198.51.100.7","hibernation_configured":false,"serves_shared_pool":false,"accepts_inbound":false,"named_pools":[],"burst_notices":true,"ha_handover":1,"capabilities":["names-2"],"moves_protocol":0,"seeds_protocol":0,"addrs":null,"generation":"2026-10-30T00:00:00Z","hosts":{"*.bah-certonly.example.com":{"role":"wildcard","platform":false,"wildcard":true},"*.bah-certs.example.com":{"role":"wildcard","platform":false,"wildcard":true},"*.bah-regional.example.com":{"role":"wildcard","platform":false,"wildcard":true},"*.bah-wild.example.com":{"role":"home","platform":false,"alias":true,"wildcard":true,"account":"bah","app":"shop","target_host":"shop.bah.example.com"},"bah-certonly.example.com":{"role":"home","platform":false,"alias":true,"account":"bah","app":"shop","target_host":"shop.bah.example.com"},"shop.bah-custom.example.com":{"role":"home","platform":false,"alias":true,"account":"bah","app":"shop","target_host":"shop.bah.example.com"},"shop.bah.example.com":{"role":"home","platform":true,"account":"bah","app":"shop"},"tickets.example.com":{"role":"home","platform":false,"alias":true,"account":"bah","app":"shop","target_host":"shop.bah.example.com"}}} |
diff --git a/internal/grouproll/box.go b/internal/grouproll/box.go| index d543a4cc3..8da092302 100644 |
| --- a/internal/grouproll/box.go |
| +++ b/internal/grouproll/box.go |
| @@ -49,6 +49,32 @@ type BoxArgs struct { |
| SHA256 string |
| Transaction string |
| Permit map[string]any |
| + // Peers is drain's acknowledgement population (region HA §25.4 step |
| + // 1): every box the floor counted, the member excluded, read once by |
| + // the verb. drain refuses nil; an empty list is a floor that counted |
| + // no other box. |
| + Peers []string |
| +} |
| + |
| +// MaxDrainPeers bounds the boxes one drain request names (the member's |
| +// drain socket and the session command carry the list whole). |
| +const MaxDrainPeers = 256 |
| + |
| +// drainPeersArg is drain's --peers argument for peers: references in the |
| +// edges-key grammar, comma separated, no duplicates, at most |
| +// MaxDrainPeers. Every character is shell-safe. ok is false otherwise. |
| +func drainPeersArg(peers []string) (string, bool) { |
| + if peers == nil || len(peers) > MaxDrainPeers { |
| + return "", false |
| + } |
| + seen := map[string]bool{} |
| + for _, p := range peers { |
| + if !boxRef.MatchString(p) || seen[p] { |
| + return "", false |
| + } |
| + seen[p] = true |
| + } |
| + return "--peers=" + strings.Join(peers, ","), true |
| } |
| // Box runs one maintenance verb on a member. Run reports each Session |
| @@ -109,7 +135,11 @@ func RemoteCommand(verb string, a BoxArgs, nonce string) (string, error) { |
| command = fmt.Sprintf("/usr/bin/timeout --signal=TERM --kill-after=30s %ds %s system group-maintenance "+ |
| "drain --cancel %s && %s system group-maintenance status", CancelBound, carlosBinary, tx, carlosBinary) |
| case "drain": |
| - command = fmt.Sprintf("/usr/bin/timeout --signal=TERM --kill-after=30s %ds %s %s", DrainBound, command, tx) |
| + peers, ok := drainPeersArg(a.Peers) |
| + if !ok { |
| + return "", Refusal{Key: "record"} |
| + } |
| + command = fmt.Sprintf("/usr/bin/timeout --signal=TERM --kill-after=30s %ds %s %s %s", DrainBound, command, peers, tx) |
| default: |
| command += " " + tx + status |
| } |
diff --git a/internal/grouproll/box_test.go b/internal/grouproll/box_test.go| index 818b1f75f..735ca714a 100644 |
| --- a/internal/grouproll/box_test.go |
| +++ b/internal/grouproll/box_test.go |
| @@ -8,6 +8,7 @@ import ( |
| "os" |
| "reflect" |
| "regexp" |
| + "slices" |
| "strings" |
| "testing" |
| ) |
| @@ -89,17 +90,30 @@ func goldenArgs(t *testing.T, raw json.RawMessage) BoxArgs { |
| return a |
| } |
| +// goldenDrain is the one deliberate divergence from the script's drain |
| +// command (held floor capability ruling, 2026-11-10): the verb always names |
| +// the acknowledgement population, so the script's drain rows run with an |
| +// empty list and gain "--peers= " before the transaction. |
| +func goldenDrain(verb string, a BoxArgs, command string) (BoxArgs, string) { |
| + if verb != "drain" { |
| + return a, command |
| + } |
| + a.Peers = []string{} |
| + return a, strings.Replace(command, " drain "+a.Transaction+")", " drain --peers= "+a.Transaction+")", 1) |
| +} |
| + |
| func TestRemoteCommandGolden(t *testing.T) { |
| g := loadBoxGolden(t) |
| verbs := map[string]bool{} |
| for _, c := range g.RemoteCommands { |
| t.Run(c.Name, func(t *testing.T) { |
| - got, err := RemoteCommand(c.Verb, goldenArgs(t, c.Args), c.Nonce) |
| + a, want := goldenDrain(c.Verb, goldenArgs(t, c.Args), c.Command) |
| + got, err := RemoteCommand(c.Verb, a, c.Nonce) |
| if err != nil { |
| t.Fatal(err) |
| } |
| - if got != c.Command { |
| - t.Fatalf("command differs from the script's\n got: %s\nwant: %s", got, c.Command) |
| + if got != want { |
| + t.Fatalf("command differs from the script's\n got: %s\nwant: %s", got, want) |
| } |
| }) |
| verbs[c.Verb] = true |
| @@ -181,7 +195,8 @@ func TestRemoteCommandMatchesDocumentPattern(t *testing.T) { |
| re := documentPattern(t) |
| g := loadBoxGolden(t) |
| for _, c := range g.RemoteCommands { |
| - got, err := RemoteCommand(c.Verb, goldenArgs(t, c.Args), c.Nonce) |
| + a, _ := goldenDrain(c.Verb, goldenArgs(t, c.Args), c.Command) |
| + got, err := RemoteCommand(c.Verb, a, c.Nonce) |
| if err != nil { |
| t.Fatal(err) |
| } |
| @@ -204,7 +219,18 @@ func TestRemoteCommandMatchesDocumentPattern(t *testing.T) { |
| for n := rng.Intn(80); n > 0; n-- { |
| tx += string(txChars[rng.Intn(len(txChars))]) |
| } |
| - a := BoxArgs{SHA256: hex(64), Transaction: tx, Permit: map[string]any{ |
| + refChars := "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789._-" |
| + peers := []string{} |
| + for n := rng.Intn(6); n > 0; n-- { |
| + p := string(refChars[rng.Intn(62)]) |
| + for m := rng.Intn(30); m > 0; m-- { |
| + p += string(refChars[rng.Intn(len(refChars))]) |
| + } |
| + if !slices.Contains(peers, p) { |
| + peers = append(peers, p) |
| + } |
| + } |
| + a := BoxArgs{SHA256: hex(64), Transaction: tx, Peers: peers, Permit: map[string]any{ |
| "v": int64(1), "transaction": tx, "boot_id": hex(8) + "-\u00e9", "expires": rng.Int63(), |
| "allow_rollback": rng.Intn(2) == 0}} |
| for _, verb := range []string{"status", "prepare", "permit", "revoke", "apply", "rollback", "drain", |
| @@ -220,9 +246,11 @@ func TestRemoteCommandMatchesDocumentPattern(t *testing.T) { |
| } |
| // The pattern is not vacuous: a leading-dash transaction (which |
| // RemoteCommand refuses) and an altered frame both fail it. |
| - drain, _ := RemoteCommand("drain", BoxArgs{Transaction: "t6"}, hex(32)) |
| + drain, _ := RemoteCommand("drain", BoxArgs{Transaction: "t6", Peers: []string{"adi", "g-0123456789abcdef0123"}}, hex(32)) |
| for _, bad := range []string{ |
| - strings.Replace(drain, "drain t6", "drain -t6", 1), |
| + strings.Replace(drain, "drain --peers=adi,g-0123456789abcdef0123 t6", "drain --peers=adi,g-0123456789abcdef0123 -t6", 1), |
| + strings.Replace(drain, "--peers=adi,g-0123456789abcdef0123", "--peers=adi;g-0123456789abcdef0123", 1), |
| + strings.Replace(drain, "--peers=adi,g-0123456789abcdef0123 ", "", 1), |
| strings.Replace(drain, "3600s", "3601s", 1), |
| strings.Replace(drain, "exit 77", "exit 78", 1), |
| drain + "\n", |
| @@ -454,3 +482,29 @@ func TestUncertainDetails(t *testing.T) { |
| } |
| } |
| } |
| + |
| +// drain always names its acknowledgement population: the exact --peers |
| +// argument, and refusals for no list, a bad reference, a duplicate and too |
| +// many boxes (held floor capability ruling, 2026-11-10). |
| +func TestRemoteCommandDrainPeers(t *testing.T) { |
| + nonce := "0123456789abcdef0123456789abcdef" |
| + got, err := RemoteCommand("drain", BoxArgs{Transaction: "t6", Peers: []string{"adi", "g-0123456789abcdef0123", "edge.b_1"}}, nonce) |
| + if err != nil || !strings.Contains(got, "(/usr/bin/timeout --signal=TERM --kill-after=30s 3600s /opt/carlos/carlos system group-maintenance drain --peers=adi,g-0123456789abcdef0123,edge.b_1 t6);") { |
| + t.Fatalf("got %s, %v", got, err) |
| + } |
| + many := make([]string, MaxDrainPeers+1) |
| + for i := range many { |
| + many[i] = fmt.Sprintf("b%d", i) |
| + } |
| + for name, peers := range map[string][]string{ |
| + "no list": nil, "blank": {""}, "comma": {"a,b"}, "space": {"a b"}, "dash first": {"-a"}, |
| + "quote": {"a'b"}, "duplicate": {"adi", "adi"}, "too many": many, |
| + } { |
| + if _, err := RemoteCommand("drain", BoxArgs{Transaction: "t6", Peers: peers}, nonce); refusalKey(err) != "record" { |
| + t.Errorf("%s: %v, want record", name, err) |
| + } |
| + } |
| + if _, err := RemoteCommand("drain", BoxArgs{Transaction: "t6", Peers: many[:MaxDrainPeers]}, nonce); err != nil { |
| + t.Errorf("%d peers: %v", MaxDrainPeers, err) |
| + } |
| +} |
diff --git a/internal/grouproll/config.go b/internal/grouproll/config.go| index e5453c771..d47fa9f34 100644 |
| --- a/internal/grouproll/config.go |
| +++ b/internal/grouproll/config.go |
| @@ -37,6 +37,17 @@ type Config struct { |
| ReleasePublicKey *string `json:"release_public_key,omitempty"` |
| ReleaseChannels []string `json:"release_channels,omitempty"` |
| ReleasePlatform *string `json:"release_platform,omitempty"` |
| + |
| + // FixedBoxes is every fixed box of the deployment that may forward a |
| + // request to a member, by reference, whatever its region (held floor |
| + // capability ruling, 2026-11-10). The floor refuses a drain unless each |
| + // has an edges file: a fixed box whose first publication failed can |
| + // still serve and forward. nil is absent. NoFixedBoxes true says the |
| + // deployment has none. The floor needs exactly one of a non-empty |
| + // FixedBoxes and NoFixedBoxes true; anything else is a floor error. |
| + // The Go verb's own keys: the superseded script refuses them. |
| + FixedBoxes []string `json:"fixed_boxes,omitempty"` |
| + NoFixedBoxes *bool `json:"no_fixed_boxes,omitempty"` |
| } |
| // The script's patterns (:242-266 and validate_config), anchored as |
| @@ -62,7 +73,10 @@ var requiredKeys = []string{"deployment", "account", "region", "group", "group_a |
| "target_groups", "bucket", "document", "state_dir", "profile", "min_release"} |
| var optionalKeys = []string{"ha_floor", "data_prefix", "data_bucket", |
| - "release_public_key", "release_channels", "release_platform"} |
| + "release_public_key", "release_channels", "release_platform", "fixed_boxes", "no_fixed_boxes"} |
| + |
| +// boxRef is a box reference as an edges key names it (EdgesKey). |
| +var boxRef = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$`) |
| // LoadConfig reads and validates the config at path. A file that cannot be |
| // read or decoded is "record" (the script's decode and main); a decoded |
| @@ -134,6 +148,29 @@ func ValidateConfig(v any) (Config, error) { |
| out.ReleaseChannels = append(out.ReleaseChannels, s) |
| } |
| } |
| + if raw, present := c["fixed_boxes"]; present { |
| + list, ok := raw.([]any) |
| + if !ok || len(list) > 1024 { |
| + return Config{}, invalid |
| + } |
| + out.FixedBoxes = []string{} |
| + seen := map[string]bool{} |
| + for _, e := range list { |
| + s, ok := e.(string) |
| + if !ok || !boxRef.MatchString(s) || strings.HasSuffix(s, ".json") || seen[s] { |
| + return Config{}, invalid |
| + } |
| + seen[s] = true |
| + out.FixedBoxes = append(out.FixedBoxes, s) |
| + } |
| + } |
| + if raw, present := c["no_fixed_boxes"]; present { |
| + b, ok := raw.(bool) |
| + if !ok { |
| + return Config{}, invalid |
| + } |
| + out.NoFixedBoxes = &b |
| + } |
| if out.ReleasePlatform, ok = optional("release_platform", releasePlatform.MatchString); !ok { |
| return Config{}, invalid |
| } |
| @@ -251,6 +288,16 @@ func (c Config) Map() map[string]any { |
| } |
| m["release_channels"] = chs |
| } |
| + if c.FixedBoxes != nil { |
| + boxes := make([]any, len(c.FixedBoxes)) |
| + for i, s := range c.FixedBoxes { |
| + boxes[i] = s |
| + } |
| + m["fixed_boxes"] = boxes |
| + } |
| + if c.NoFixedBoxes != nil { |
| + m["no_fixed_boxes"] = *c.NoFixedBoxes |
| + } |
| return m |
| } |
diff --git a/internal/grouproll/config_test.go b/internal/grouproll/config_test.go| index 5c7da7aef..31211261e 100644 |
| --- a/internal/grouproll/config_test.go |
| +++ b/internal/grouproll/config_test.go |
| @@ -84,6 +84,13 @@ func TestConfigMatchesScriptValidation(t *testing.T) { |
| "nested prefix": with(heldConfig(), "data_prefix", "a/b.c/d_e-f"), |
| "other document": with(baseConfig(), "document", "Carlos-Group-Operator"), |
| "state_dir other absolute": with(baseConfig(), "state_dir", "/var/lib/x/./y"), |
| + "fixed boxes": with(heldConfig(), "fixed_boxes", []any{"adi", "tito-1", "g.x_y"}), |
| + // An empty list is a valid config; the floor refuses it. |
| + "fixed boxes empty": with(heldConfig(), "fixed_boxes", []any{}), |
| + // The floor judges the combinations; the config checks types. |
| + "no fixed boxes true": with(heldConfig(), "no_fixed_boxes", true), |
| + "no fixed boxes false": with(heldConfig(), "no_fixed_boxes", false), |
| + "both": with(heldConfig(), "no_fixed_boxes", true, "fixed_boxes", []any{"adi"}), |
| } |
| for name, c := range accept { |
| t.Run("accept "+name, func(t *testing.T) { |
| @@ -136,25 +143,36 @@ func TestConfigMatchesScriptValidation(t *testing.T) { |
| "platform case": with(release, "release_platform", "Linux-arm64"), |
| "platform null": with(release, "release_platform", nil), |
| // validate_config's remaining rules |
| - "not an object": nil, |
| - "deployment empty": with(baseConfig(), "deployment", ""), |
| - "deployment long": with(baseConfig(), "deployment", longName(129)), |
| - "region": with(baseConfig(), "region", "eu-west"), |
| - "bucket": with(baseConfig(), "bucket", "Example"), |
| - "state_dir dotdot": with(baseConfig(), "state_dir", "/var/../etc"), |
| - "state_dir long": with(baseConfig(), "state_dir", "/"+longName(1024)), |
| - "AWS- document": with(baseConfig(), "document", "AWS-RunShellScript"), |
| - "group mismatch": with(baseConfig(), "group", "other-group"), |
| - "group_arn account": with(baseConfig(), "group_arn", "arn:aws:autoscaling:eu-west-1:111111111111:autoScalingGroup:example:autoScalingGroupName/example-group"), |
| - "one target group": with(baseConfig(), "target_groups", []any{"arn:aws:elasticloadbalancing:eu-west-1:000000000000:targetgroup/example-8/8888888888888888"}), |
| - "same target groups": with(baseConfig(), "target_groups", []any{"arn:aws:elasticloadbalancing:eu-west-1:000000000000:targetgroup/example-8/8888888888888888", "arn:aws:elasticloadbalancing:eu-west-1:000000000000:targetgroup/example-8/8888888888888888"}), |
| - "target partition": with(baseConfig(), "target_groups", []any{"arn:aws-cn:elasticloadbalancing:eu-west-1:000000000000:targetgroup/a/0123456789abcdef", "arn:aws-cn:elasticloadbalancing:eu-west-1:000000000000:targetgroup/b/0123456789abcdef"}), |
| - "target short id": with(baseConfig(), "target_groups", []any{"arn:aws:elasticloadbalancing:eu-west-1:000000000000:targetgroup/a/0123", "arn:aws:elasticloadbalancing:eu-west-1:000000000000:targetgroup/b/0123456789abcdef"}), |
| - "profile number": with(baseConfig(), "profile", int64(7)), |
| - "trailing newline": with(baseConfig(), "account", "000000000000\n"), |
| - "no state_dir": without(baseConfig(), "state_dir"), |
| - "prefix long": with(heldConfig(), "data_prefix", longName(1025)), |
| - "ha_floor not string": with(heldConfig(), "ha_floor", int64(1)), |
| + "not an object": nil, |
| + "deployment empty": with(baseConfig(), "deployment", ""), |
| + "deployment long": with(baseConfig(), "deployment", longName(129)), |
| + "region": with(baseConfig(), "region", "eu-west"), |
| + "bucket": with(baseConfig(), "bucket", "Example"), |
| + "state_dir dotdot": with(baseConfig(), "state_dir", "/var/../etc"), |
| + "state_dir long": with(baseConfig(), "state_dir", "/"+longName(1024)), |
| + "AWS- document": with(baseConfig(), "document", "AWS-RunShellScript"), |
| + "group mismatch": with(baseConfig(), "group", "other-group"), |
| + "group_arn account": with(baseConfig(), "group_arn", "arn:aws:autoscaling:eu-west-1:111111111111:autoScalingGroup:example:autoScalingGroupName/example-group"), |
| + "one target group": with(baseConfig(), "target_groups", []any{"arn:aws:elasticloadbalancing:eu-west-1:000000000000:targetgroup/example-8/8888888888888888"}), |
| + "same target groups": with(baseConfig(), "target_groups", []any{"arn:aws:elasticloadbalancing:eu-west-1:000000000000:targetgroup/example-8/8888888888888888", "arn:aws:elasticloadbalancing:eu-west-1:000000000000:targetgroup/example-8/8888888888888888"}), |
| + "target partition": with(baseConfig(), "target_groups", []any{"arn:aws-cn:elasticloadbalancing:eu-west-1:000000000000:targetgroup/a/0123456789abcdef", "arn:aws-cn:elasticloadbalancing:eu-west-1:000000000000:targetgroup/b/0123456789abcdef"}), |
| + "target short id": with(baseConfig(), "target_groups", []any{"arn:aws:elasticloadbalancing:eu-west-1:000000000000:targetgroup/a/0123", "arn:aws:elasticloadbalancing:eu-west-1:000000000000:targetgroup/b/0123456789abcdef"}), |
| + "profile number": with(baseConfig(), "profile", int64(7)), |
| + "trailing newline": with(baseConfig(), "account", "000000000000\n"), |
| + "no state_dir": without(baseConfig(), "state_dir"), |
| + "prefix long": with(heldConfig(), "data_prefix", longName(1025)), |
| + "ha_floor not string": with(heldConfig(), "ha_floor", int64(1)), |
| + "fixed boxes string": with(heldConfig(), "fixed_boxes", "adi"), |
| + "fixed boxes number": with(heldConfig(), "fixed_boxes", []any{int64(1)}), |
| + "fixed boxes duplicate": with(heldConfig(), "fixed_boxes", []any{"adi", "adi"}), |
| + "fixed boxes blank": with(heldConfig(), "fixed_boxes", []any{""}), |
| + "fixed boxes slash": with(heldConfig(), "fixed_boxes", []any{"a/b"}), |
| + "fixed boxes json": with(heldConfig(), "fixed_boxes", []any{"adi.json"}), |
| + "fixed boxes null": with(heldConfig(), "fixed_boxes", nil), |
| + "no fixed boxes string": with(heldConfig(), "no_fixed_boxes", "true"), |
| + "no fixed boxes number": with(heldConfig(), "no_fixed_boxes", int64(1)), |
| + "no fixed boxes null": with(heldConfig(), "no_fixed_boxes", nil), |
| + "no fixed boxes list": with(heldConfig(), "no_fixed_boxes", []any{}), |
| } |
| for name, c := range refuse { |
| t.Run("refuse "+name, func(t *testing.T) { |
diff --git a/internal/grouproll/depart.go b/internal/grouproll/depart.go| index 91a9d6256..9536191cf 100644 |
| --- a/internal/grouproll/depart.go |
| +++ b/internal/grouproll/depart.go |
| @@ -332,6 +332,48 @@ func (e *Engine) drainFailed(reasons []string, report any) error { |
| return stopped("drain-failed", "drain_failed") |
| } |
| +// drainPeers is the drain's acknowledgement population (§25.4 step 1, held |
| +// floor capability ruling, 2026-11-10: one population, read once, by the |
| +// party that decides): the boxes this transaction's floor row counted from |
| +// its listing of control/edges/, the member itself excluded. The member |
| +// asks every one of them, plus any its own fold adds; its fold never |
| +// removes one. A transaction with no drain floor row is a damaged record. |
| +func (e *Engine) drainPeers() ([]string, error) { |
| + row, ok := e.last("floor", nil) |
| + if !ok || row["rule"] != "drain" { |
| + return nil, refuse("record") |
| + } |
| + // A row without this build's marker is an older tool's (Astra r3 |
| + // F3.1): its live list skipped quiet boxes. It is never the population; |
| + // the transaction is closed, not resumed into a drain. |
| + if row["population"] != floorPopulation { |
| + return nil, refuse("floor_legacy") |
| + } |
| + // live must be a present array of valid, distinct references (F3.2): |
| + // missing evidence never means "no peers". |
| + live, ok := row["live"].([]any) |
| + if !ok { |
| + return nil, refuse("floor_population") |
| + } |
| + self, _ := e.hIdentity()["box_ref"].(string) |
| + peers := []string{} |
| + seen := map[string]bool{} |
| + for _, v := range live { |
| + s, ok := v.(string) |
| + if !ok || !boxRef.MatchString(s) || seen[s] { |
| + return nil, refuse("floor_population") |
| + } |
| + seen[s] = true |
| + if s != self { |
| + peers = append(peers, s) |
| + } |
| + } |
| + if len(peers) > MaxDrainPeers { |
| + return nil, refuse("drain_peers_many", "count", strconv.Itoa(len(peers)), "max", strconv.Itoa(MaxDrainPeers)) |
| + } |
| + return peers, nil |
| +} |
| + |
| // drain is the script's Operator.drain: up to DrainTries drain sessions |
| // (an uncertain one is run again and joins the move), then the report |
| // must be this transaction's finished move, fenced, from a known agent |
| @@ -341,10 +383,14 @@ func (e *Engine) drain(ctx context.Context) error { |
| if _, err := e.event("phase", map[string]any{"phase": "drain"}); err != nil { |
| return err |
| } |
| + peers, err := e.drainPeers() |
| + if err != nil { |
| + return err |
| + } |
| var r BoxResult |
| for attempt := 1; ; attempt++ { |
| var err error |
| - r, err = e.box(ctx, iid, "drain", BoxArgs{Transaction: tx}) |
| + r, err = e.box(ctx, iid, "drain", BoxArgs{Transaction: tx, Peers: peers}) |
| if err == nil { |
| break |
| } |
| @@ -385,7 +431,7 @@ func (e *Engine) drain(ctx context.Context) error { |
| } |
| return e.drainFailed(reasons, report) |
| } |
| - _, err := e.event("drained", map[string]any{"incarnation": incarnation, "report": report}) |
| + _, err = e.event("drained", map[string]any{"incarnation": incarnation, "report": report}) |
| return err |
| } |
diff --git a/internal/grouproll/depart_test.go b/internal/grouproll/depart_test.go| index b1dca97ab..48f52e1f2 100644 |
| --- a/internal/grouproll/depart_test.go |
| +++ b/internal/grouproll/depart_test.go |
| @@ -7,6 +7,7 @@ import ( |
| "fmt" |
| "math" |
| "reflect" |
| + "slices" |
| "sort" |
| "strings" |
| "testing" |
| @@ -36,14 +37,15 @@ func newHeldHarnessAt(t *testing.T, root string, members int, configure func(c * |
| h := newHarnessWith(t, root, members, func(c *Config) { |
| floor, prefix, bucket := "v0.35.0", "instances", "example-bucket" |
| c.HAFloor, c.DataPrefix, c.DataBucket = &floor, &prefix, &bucket |
| + c.FixedBoxes = []string{"adi"} |
| if configure != nil { |
| configure(c) |
| } |
| }) |
| f := h.f |
| f.version = "v0.35.0" |
| - f.haTake = map[string]any{} |
| - f.fixed = map[string]fixedEdges{"adi": {haTake: int64(1), age: 5 * time.Second}} |
| + f.haTake, f.haHandover = map[string]any{}, map[string]any{} |
| + f.fixed = map[string]fixedEdges{"adi": {haHandover: int64(1), age: 5 * time.Second}} |
| f.templateRelease = "v0.35.0" |
| f.pointers = map[string][]byte{"stable": floorFixture(t, "router-pointer-golden.json")} |
| f.held = newHeldFake(f) |
| @@ -1069,17 +1071,17 @@ func mustFloorRefused(t *testing.T, h *harness, reason string) { |
| } |
| func TestDepartFloorRefused(t *testing.T) { |
| - t.Run("member without ha_take", func(t *testing.T) { |
| + t.Run("member without ha_handover", func(t *testing.T) { |
| h := newHeldHarness(t, 2, nil) |
| - h.f.haTake[ref(fakePeer)] = nil |
| + h.f.haHandover[ref(fakePeer)] = nil |
| mustFloorRefused(t, h, Text("floor_box", "box", ref(fakePeer))) |
| }) |
| - t.Run("member with other ha_take", func(t *testing.T) { |
| + t.Run("member with other ha_handover", func(t *testing.T) { |
| h := newHeldHarness(t, 2, nil) |
| - h.f.haTake[ref(fakeIID)] = int64(2) |
| + h.f.haHandover[ref(fakeIID)] = int64(2) |
| mustFloorRefused(t, h, Text("floor_box", "box", ref(fakeIID))) |
| }) |
| - t.Run("fixed forwarder without ha_take", func(t *testing.T) { |
| + t.Run("fixed forwarder without ha_handover", func(t *testing.T) { |
| h := newHeldHarness(t, 2, nil) |
| h.f.fixed["adi"] = fixedEdges{age: 5 * time.Second} |
| mustFloorRefused(t, h, Text("floor_box", "box", "adi")) |
| @@ -1152,16 +1154,162 @@ func TestDepartFloorErrorRefusesWithoutDR4(t *testing.T) { |
| } |
| // test_stale_box_is_not_live, through a whole replace. |
| -func TestDepartStaleBoxIsNotLive(t *testing.T) { |
| +// The floor counts every present edges file whatever its age (held floor |
| +// capability ruling, 2026-11-10): an hours-old file that says |
| +// ha_handover: 1 is counted and met, and one without it is DR-4. |
| +func TestDepartCountsOldEdgesFiles(t *testing.T) { |
| h := newHeldHarness(t, 2, nil) |
| - h.f.fixed["old"] = fixedEdges{age: 16 * time.Minute} |
| + h.f.fixed["old"] = fixedEdges{haHandover: int64(1), age: 6 * time.Hour} |
| if err := h.depart("replace", heldTx); err != nil { |
| t.Fatal(err) |
| } |
| floor, _ := h.txJournal(heldTx).Last("floor", nil) |
| - if h.f.states[fakeIID] != "Terminated" || containsValue(floor["live"], "old") { |
| + if h.f.states[fakeIID] != "Terminated" || floor["rule"] != "drain" || !containsValue(floor["live"], "old") { |
| t.Fatalf("state %s floor %v", h.f.states[fakeIID], floor) |
| } |
| + h = newHeldHarness(t, 2, nil) |
| + h.f.fixed["old"] = fixedEdges{haTake: int64(1), age: 6 * time.Hour} |
| + mustFloorRefused(t, h, Text("floor_box", "box", "old")) |
| +} |
| + |
| +// A declared fixed box whose first PUT failed has no file: the depart is |
| +// floor-refused, naming it, before any write. |
| +func TestDepartDeclaredFixedBoxWithoutAFile(t *testing.T) { |
| + h := newHeldHarness(t, 2, nil) |
| + delete(h.f.fixed, "adi") |
| + mustFloorRefused(t, h, Text("floor_fixed_missing", "box", "adi")) |
| +} |
| + |
| +// The drain request names the floor's population, read once: every box |
| +// the floor row counted, the member excluded (held floor capability |
| +// ruling, 2026-11-10). An old file and a fixed box are on it like a peer. |
| +func TestDepartDrainNamesTheFloorPopulation(t *testing.T) { |
| + h := newHeldHarness(t, 2, nil) |
| + h.f.fixed["olden"] = fixedEdges{haHandover: int64(1), age: 6 * time.Hour} |
| + if err := h.depart("replace", heldTx); err != nil { |
| + t.Fatal(err) |
| + } |
| + j := h.txJournal(heldTx) |
| + var peers any |
| + for _, r := range j.Rows() { |
| + if a, ok := r["args"].(map[string]any); ok && r["kind"] == "intent" && a["verb"] == "drain" { |
| + peers = a["peers"] |
| + } |
| + } |
| + if !sameValue(peers, []any{"adi", ref(fakePeer), "olden"}) { |
| + t.Fatalf("drain peers %v, want the floor's live list without the member", peers) |
| + } |
| +} |
| + |
| +// drainPeersFrom journals one floor row and builds the drain list from it, |
| +// as a resumed transaction would. |
| +func drainPeersFrom(t *testing.T, row map[string]any) ([]string, error) { |
| + t.Helper() |
| + h := newHeldHarness(t, 2, nil) |
| + e := h.journaled() |
| + e.header = Row{"iid": fakeIID, "identity": map[string]any{"box_ref": ref(fakeIID)}} |
| + if _, err := e.event("floor", row); err != nil { |
| + t.Fatal(err) |
| + } |
| + return e.drainPeers() |
| +} |
| + |
| +func markedFloor(live any, present bool) map[string]any { |
| + row := map[string]any{"rule": "drain", "reasons": []any{}, "population": floorPopulation, |
| + "ha_floor": "v0.35.0", "releases": map[string]any{}} |
| + if present { |
| + row["live"] = live |
| + } |
| + return row |
| +} |
| + |
| +// Astra r3 F3.2: the floor row's live list must be a present JSON array of |
| +// valid, distinct box references. Absent, null or another type, a bad |
| +// element and a duplicate each refuse; they never mean "no peers". The |
| +// empty list is an actual empty array, or one holding only the member. |
| +func TestDrainPeersNeedAStrictLiveList(t *testing.T) { |
| + for name, c := range map[string]struct { |
| + live any |
| + present bool |
| + }{ |
| + "absent": {nil, false}, "null": {nil, true}, "string": {"adi", true}, "bool": {true, true}, |
| + "object": {map[string]any{"adi": true}, true}, "number": {int64(1), true}, |
| + "bad element": {[]any{"adi", "a b"}, true}, "non-string element": {[]any{"adi", int64(1)}, true}, |
| + "duplicate": {[]any{"adi", "adi"}, true}, "dash first": {[]any{"-adi"}, true}, |
| + } { |
| + t.Run(name, func(t *testing.T) { |
| + peers, err := drainPeersFrom(t, markedFloor(c.live, c.present)) |
| + if refusalKey(err) != "floor_population" || peers != nil { |
| + t.Fatalf("peers %v, %v; want floor_population", peers, err) |
| + } |
| + }) |
| + } |
| + for name, live := range map[string][]any{"empty": {}, "only the member": {ref(fakeIID)}} { |
| + if peers, err := drainPeersFrom(t, markedFloor(live, true)); err != nil || peers == nil || len(peers) != 0 { |
| + t.Fatalf("%s: peers %#v, %v; want an empty list", name, peers, err) |
| + } |
| + } |
| + peers, err := drainPeersFrom(t, markedFloor([]any{"adi", ref(fakeIID), ref(fakePeer)}, true)) |
| + if err != nil || !slices.Equal(peers, []string{"adi", ref(fakePeer)}) { |
| + t.Fatalf("a marked row: %v, %v", peers, err) |
| + } |
| +} |
| + |
| +// Astra r3 F3.1: a floor row without this build's population marker was |
| +// written by an older tool, whose live list kept only fresh files. It is |
| +// never the drain's population: drainPeers refuses it, whatever its live |
| +// list says. |
| +func TestDrainPeersRefuseALegacyFloor(t *testing.T) { |
| + for name, pop := range map[string]any{"absent": nil, "other": "fresh-files", "number": int64(1)} { |
| + row := markedFloor([]any{"adi", ref(fakePeer)}, true) |
| + if pop == nil { |
| + delete(row, "population") |
| + } else { |
| + row["population"] = pop |
| + } |
| + if peers, err := drainPeersFrom(t, row); refusalKey(err) != "floor_legacy" || peers != nil { |
| + t.Fatalf("%s: peers %v, %v; want floor_legacy", name, peers, err) |
| + } |
| + } |
| +} |
| + |
| +// Astra r3 F3.1, end to end: the old verb writes its floor row (no |
| +// population marker, and a live list that skipped adi, whose file is six |
| +// hours old), then the process dies right after that durable row. The new |
| +// verb resumes the transaction: it refuses before any drain request, and |
| +// the journal holds no drain session intent. |
| +func TestDepartResumeOfALegacyFloorRefusesBeforeTheDrain(t *testing.T) { |
| + h := newHeldHarness(t, 2, nil) |
| + h.f.fixed["adi"] = fixedEdges{haTake: int64(1), haHandover: int64(1), age: 6 * time.Hour} |
| + // The old Floor's row, exactly its keys: origin/main kept only files |
| + // at most 15 minutes old, so adi is not in live. |
| + h.beforeEvent = func(kind string, data map[string]any) { |
| + if kind == "floor" { |
| + delete(data, "population") |
| + data["live"] = []any{ref(fakeIID), ref(fakePeer)} |
| + } |
| + } |
| + h.afterEvent = func(kind string, _ Row) { |
| + if kind == "floor" { |
| + panic(fakeDeath{"after the floor"}) |
| + } |
| + } |
| + if !expectDeath(t, func() { h.depart("replace", heldTx) }) { |
| + t.Fatal("no death after the floor row") |
| + } |
| + h.beforeEvent, h.afterEvent = nil, nil |
| + err := h.resume() |
| + if refusalKey(err) != "floor_legacy" { |
| + t.Fatalf("resume: %v, want floor_legacy", err) |
| + } |
| + for _, r := range h.txJournal(heldTx).Rows() { |
| + if a, ok := r["args"].(map[string]any); ok && r["kind"] == "intent" && a["verb"] == "drain" { |
| + t.Fatalf("a drain session intent: %v", r) |
| + } |
| + } |
| + if floor, _ := h.txJournal(heldTx).Last("floor", nil); floor["population"] != nil || containsValue(floor["live"], "adi") { |
| + t.Fatalf("the legacy floor row was rewritten: %v", floor) |
| + } |
| } |
| // RemoveTests and RemoveMinimumTests. |
| @@ -1383,7 +1531,7 @@ func TestDrainedRollLockAfterPermitReturnsAndRevokes(t *testing.T) { |
| // test_roll_below_floor_uses_dr4_and_says_so. |
| func TestDrainedRollBelowFloorUsesDR4AndSaysSo(t *testing.T) { |
| h := newHeldHarness(t, 2, nil) |
| - h.f.haTake[ref(fakePeer)] = nil |
| + h.f.haHandover[ref(fakePeer)] = nil |
| if err := h.heldRoll(); err != nil { |
| t.Fatal(err) |
| } |
diff --git a/internal/grouproll/engine.go b/internal/grouproll/engine.go| index 68a4cbef6..a6c795c19 100644 |
| --- a/internal/grouproll/engine.go |
| +++ b/internal/grouproll/engine.go |
| @@ -353,6 +353,13 @@ func (e *Engine) box(ctx context.Context, iid, verb string, a BoxArgs) (BoxResul |
| if a.Permit != nil { |
| args["permit"] = a.Permit |
| } |
| + if a.Peers != nil { |
| + peers := make([]any, len(a.Peers)) |
| + for i, p := range a.Peers { |
| + peers[i] = p |
| + } |
| + args["peers"] = peers |
| + } |
| var res BoxResult |
| _, err := e.call(ctx, "session", args, time.Time{}, func(ctx context.Context, onSession func(string)) (any, error) { |
| r, err := e.b.Run(ctx, iid, verb, a, onSession) |
diff --git a/internal/grouproll/fake_test.go b/internal/grouproll/fake_test.go| index 8f5e8b423..b465620cb 100644 |
| --- a/internal/grouproll/fake_test.go |
| +++ b/internal/grouproll/fake_test.go |
| @@ -125,12 +125,14 @@ type fake struct { |
| // The floor's objects (held-floor-sha-map's HeldFake). haTake is |
| // each member box's ha_take by box ref when set (an absent ref |
| // publishes 1, a nil value publishes none); a nil map publishes no |
| - // ha_take at all. fixed are boxes outside the group with an edges |
| - // file; pointers are the router pointers' bytes by channel (an absent |
| - // channel fails the GET). |
| - haTake map[string]any |
| - fixed map[string]fixedEdges |
| - pointers map[string][]byte |
| + // ha_take at all. haHandover is the same for ha_handover, the |
| + // capability the floor counts. fixed are boxes outside the group with |
| + // an edges file; pointers are the router pointers' bytes by channel (an |
| + // absent channel fails the GET). |
| + haTake map[string]any |
| + haHandover map[string]any |
| + fixed map[string]fixedEdges |
| + pointers map[string][]byte |
| // held is the planned handovers' provider and agent (the held |
| // branch's HeldFake); nil keeps the roll fake as it was. |
| @@ -144,11 +146,11 @@ type fake struct { |
| locks map[string]any |
| } |
| -// fixedEdges is a box outside the group: its ha_take (nil: none) and how |
| -// old its edges file's generation is. |
| +// fixedEdges is a box outside the group: its ha_take and ha_handover |
| +// (nil: none) and how old its edges file's generation is. |
| type fixedEdges struct { |
| - haTake any |
| - age time.Duration |
| + haTake, haHandover any |
| + age time.Duration |
| } |
| // newFake is a group of n members (the script's Fake has two): the |
| @@ -660,6 +662,13 @@ func (f *fake) Run(ctx context.Context, iid, verb string, a BoxArgs, onSession f |
| if a.Permit != nil { |
| args["permit"] = a.Permit |
| } |
| + if a.Peers != nil { |
| + peers := make([]any, len(a.Peers)) |
| + for i, p := range a.Peers { |
| + peers[i] = p |
| + } |
| + args["peers"] = peers |
| + } |
| r, err := f.request("session", args, func() (any, error) { |
| if f.sessions != nil { |
| for _, id := range f.sessions(iid, verb) { |
| @@ -851,6 +860,9 @@ func (s fakeStore) Get(ctx context.Context, key string) ([]byte, string, error) |
| if fx.haTake != nil { |
| e["ha_take"] = fx.haTake |
| } |
| + if fx.haHandover != nil { |
| + e["ha_handover"] = fx.haHandover |
| + } |
| return e, nil |
| }) |
| if err != nil { |
| @@ -904,6 +916,15 @@ func (s fakeStore) Get(ctx context.Context, key string) ([]byte, string, error) |
| e["ha_take"] = take |
| } |
| } |
| + if f.haHandover != nil { |
| + handover, set := f.haHandover[ref] |
| + if !set { |
| + handover = int64(1) |
| + } |
| + if handover != nil { |
| + e["ha_handover"] = handover |
| + } |
| + } |
| if f.held != nil { |
| if pools, ok := f.held.pools[ref]; ok { |
| e["served_pools"] = pools |
diff --git a/internal/grouproll/floor.go b/internal/grouproll/floor.go| index 8d1ee85b8..e06d4f13f 100644 |
| --- a/internal/grouproll/floor.go |
| +++ b/internal/grouproll/floor.go |
| @@ -12,26 +12,42 @@ import ( |
| "github.com/carlosframework/platform/internal/release" |
| ) |
| -// DrainAckPeers' liveness for an edges file (script :258): a generation |
| -// at most 15 minutes old and at most 60 s ahead. |
| -const ( |
| - edgesMaxAge = 15 * time.Minute |
| - edgesSkew = 60 * time.Second |
| -) |
| - |
| // The release mapping's defaults (script release_for_sha). |
| var ( |
| defaultReleaseChannels = []string{"stable"} |
| defaultReleasePlatform = "linux-arm64" |
| ) |
| +// floorPopulation marks a floor row whose live list is this build's |
| +// population: every edges file in the listing, whatever its age (Astra r3 |
| +// F3.1). An older tool's row has no marker and kept only fresh files, so |
| +// drainPeers never builds a drain list from it. |
| +const floorPopulation = "all-files-v1" |
| + |
| // Floor is the script's Operator.floor (held-floor-sha-map; region HA |
| // spec §25.9, group roll verb spec §9): which rule a departure or a roll |
| -// takes. "drain" when every live box publishes ha_take: 1 and the release |
| -// the transaction leaves running is at or above ha_floor; "dr4" when a |
| +// takes. "drain" when every box with an edges file publishes |
| +// ha_handover: 1, every declared fixed box has one, and the release the |
| +// transaction leaves running is at or above ha_floor; "dr4" when a |
| // definite finding says otherwise. kind is "replace", "remove" or "roll"; |
| // version is the release the member prepared (roll only). |
| // |
| +// The floor counts every edges file in the deployment's control/edges/ |
| +// listing, whatever its age (§25.9; held floor capability ruling, |
| +// 2026-11-10): an age test hid quiet live boxes, since a box that is not |
| +// HA publishes only on change, hours apart. The file is a hint, not proof: |
| +// a start does not always republish it (an older writer drops ha_handover |
| +// from its gate and skips the PUT), so a box rolled back below the floor |
| +// can keep a capable file. A present file without the capability is DR-4, |
| +// naming the box. Every present file, capable or not, must also be |
| +// acknowledged at drain time (§25.4 step 1, Edge.DrainAckPeers), or the |
| +// drain fails before any move. Every box in the config's fixed_boxes |
| +// must have a file, or it is DR-4 naming the box: a fixed box can serve |
| +// with no file. The config must declare a non-empty fixed_boxes or |
| +// no_fixed_boxes true, not both; anything else is a floor error. ha_take is |
| +// not read here: it says a box answers takes (region HA), which only take |
| +// candidates need. The journaled live list is the boxes counted. |
| +// |
| // A floor that cannot be read (an unreadable edges file or listing, a |
| // template release that cannot be compared, a SHA-256 that cannot be |
| // mapped through the signed router pointers, a prepared release the |
| @@ -52,15 +68,28 @@ func (e *Engine) Floor(ctx context.Context, kind, version string) (rule string, |
| } else { |
| floor := *e.c.HAFloor |
| err := func() error { |
| + // The fixed-box declaration is explicit: a non-empty list, or |
| + // no_fixed_boxes true, never both and never neither. Silence |
| + // is never read as "no fixed boxes": an unlisted forwarder |
| + // with no file would be invisible. |
| + none := e.c.NoFixedBoxes != nil && *e.c.NoFixedBoxes |
| + switch { |
| + case len(e.c.FixedBoxes) > 0 && none: |
| + errs = append(errs, Text("floor_fixed_both")) |
| + case len(e.c.FixedBoxes) == 0 && !none: |
| + errs = append(errs, Text("floor_fixed_boxes")) |
| + } |
| keys, err := e.edgesList(ctx) |
| if err != nil { |
| return err |
| } |
| + filed := map[string]bool{} |
| for _, key := range keys { |
| m := EdgesKey.FindStringSubmatch(key) |
| if m == nil { |
| continue |
| } |
| + filed[m[1]] = true |
| v, err := e.edgesKey(ctx, key) |
| if err != nil { |
| if !refusalOrUncertain(err) { |
| @@ -70,21 +99,21 @@ func (e *Engine) Floor(ctx context.Context, kind, version string) (rule string, |
| continue |
| } |
| edges, _ := v.(map[string]any) |
| - generation, err := instant(edges["generation"]) |
| - if err != nil { |
| - continue |
| - } |
| - // DrainAckPeers' liveness: a file outside it is not a live box. |
| - if age := e.clock().Sub(generation); age < -edgesSkew || age > edgesMaxAge { |
| - continue |
| - } |
| + // Every present file counts, with no age test. |
| live = append(live, m[1]) |
| - // type(take) is int and take == 1: the decoder keeps 1.0 and 1e0 |
| - // as json.Number and true as bool, so only the integer 1 counts. |
| - if take, ok := edges["ha_take"].(int64); !ok || take != 1 { |
| + // Only the integer 1 counts: the decoder keeps 1.0 and 1e0 as |
| + // json.Number and true as bool. |
| + if handover, ok := edges["ha_handover"].(int64); !ok || handover != 1 { |
| reasons = append(reasons, Text("floor_box", "box", m[1])) |
| } |
| } |
| + // A declared fixed box with no file may still serve and |
| + // forward (its first PUT failed): DR-4, naming it. |
| + for _, box := range e.c.FixedBoxes { |
| + if !filed[box] { |
| + reasons = append(reasons, Text("floor_fixed_missing", "box", box)) |
| + } |
| + } |
| if kind == "replace" { |
| rel, err := e.templateRelease(ctx) |
| if err != nil { |
| @@ -158,7 +187,7 @@ func (e *Engine) Floor(ctx context.Context, kind, version string) (rule string, |
| if len(reasons) > 0 { |
| rule = "dr4" |
| } |
| - if _, err := e.event("floor", map[string]any{"rule": rule, "reasons": reasons, "live": live, |
| + if _, err := e.event("floor", map[string]any{"rule": rule, "reasons": reasons, "live": live, "population": floorPopulation, |
| "ha_floor": haFloor, "releases": releases}); err != nil { |
| return "", err |
| } |
diff --git a/internal/grouproll/floor_test.go b/internal/grouproll/floor_test.go| index 5c2db3ab4..fc7479177 100644 |
| --- a/internal/grouproll/floor_test.go |
| +++ b/internal/grouproll/floor_test.go |
| @@ -80,22 +80,24 @@ func floorPointer(current map[string]any, channel string, extra map[string]any) |
| } |
| // newFloorHarness is HeldBase.setUp: ha_floor v0.35.0 with a data bucket |
| -// and prefix, every live box publishing ha_take 1 (the members and the |
| -// fixed box adi), the template pinned at v0.35.0, and the golden pointer |
| -// in the stable channel. withKey adds the golden release_public_key |
| +// and prefix, the fixed box adi declared in fixed_boxes, every box publishing ha_handover 1 (the members, which also |
| +// publish ha_take 1, and the fixed box adi, which is not HA and publishes |
| +// no ha_take), the template pinned at v0.35.0, and the golden pointer in |
| +// the stable channel. withKey adds the golden release_public_key |
| // (ReleaseMapTests). |
| func newFloorHarness(t *testing.T, withKey bool) *harness { |
| t.Helper() |
| h := newHarness(t, 2) |
| floor, prefix, bucket := "v0.35.0", "instances", "example-bucket" |
| h.c.HAFloor, h.c.DataPrefix, h.c.DataBucket = &floor, &prefix, &bucket |
| + h.c.FixedBoxes = []string{"adi"} |
| if withKey { |
| pub := strings.TrimSpace(string(floorFixture(t, "router-pointer-golden.pub"))) |
| h.c.ReleasePublicKey = &pub |
| } |
| h.f.c = h.c |
| - h.f.haTake = map[string]any{} |
| - h.f.fixed = map[string]fixedEdges{"adi": {haTake: int64(1), age: 5 * time.Second}} |
| + h.f.haTake, h.f.haHandover = map[string]any{}, map[string]any{} |
| + h.f.fixed = map[string]fixedEdges{"adi": {haHandover: int64(1), age: 5 * time.Second}} |
| h.f.templateRelease = "v0.35.0" |
| h.f.pointers = map[string][]byte{"stable": floorFixture(t, "router-pointer-golden.json")} |
| return h |
| @@ -247,18 +249,39 @@ func TestFloorMetDrains(t *testing.T) { |
| } |
| } |
| -func TestFloorMemberWithoutHATake(t *testing.T) { |
| +func TestFloorMemberWithoutHAHandover(t *testing.T) { |
| h := newFloorHarness(t, false) |
| - h.f.haTake[ref(fakePeer)] = nil |
| + h.f.haHandover[ref(fakePeer)] = nil |
| h.refused(t, h.floor("replace", ""), Text("floor_box", "box", ref(fakePeer))) |
| + // ha_take is not the floor's capability: a member that says ha_take: 1 |
| + // and no ha_handover is still below the floor. |
| + if h.f.haTake[ref(fakePeer)] != nil { |
| + t.Fatal("the peer's ha_take was overridden") |
| + } |
| } |
| -// The script's test is `type(take) is int and take == 1`: only the JSON |
| -// integer 1 is the floor value. 1.0 and 1e0 are floats to json.loads, and |
| -// True is a bool, so each is a DR-4 reason, never a refusal; the edges_key |
| -// row journals 1.0 and 1e0 as 1 (the journal's float ruling) while the |
| -// floor reads the raw token the decoder kept as a json.Number. |
| -func TestFloorMemberWithOtherHATake(t *testing.T) { |
| +// The floor counts ha_handover, not ha_take: no box needs ha_take for the |
| +// floor, so a floor met with no ha_take anywhere drains. |
| +func TestFloorIgnoresHATake(t *testing.T) { |
| + h := newFloorHarness(t, false) |
| + h.f.haTake = nil |
| + row := h.drained(t, h.floor("replace", "")) |
| + if !sameValue(row["live"], []any{"adi", ref(fakeIID), ref(fakePeer)}) { |
| + t.Fatalf("live = %v", row["live"]) |
| + } |
| + // A fixed box that is not HA publishes ha_handover and no ha_take. |
| + h = newFloorHarness(t, false) |
| + h.f.fixed["tito"] = fixedEdges{haHandover: int64(1), age: time.Minute} |
| + h.drained(t, h.floor("replace", "")) |
| +} |
| + |
| +// Only the JSON integer 1 is the floor value (the script's `type(take) is |
| +// int and take == 1`, now read from ha_handover). 1.0 and 1e0 are floats |
| +// to json.loads, and True is a bool, so each is a DR-4 reason, never a |
| +// refusal; the edges_key row journals 1.0 and 1e0 as 1 (the journal's |
| +// float ruling) while the floor reads the raw token the decoder kept as a |
| +// json.Number. |
| +func TestFloorMemberWithOtherHAHandover(t *testing.T) { |
| for _, c := range []struct { |
| take any |
| raw string |
| @@ -268,7 +291,7 @@ func TestFloorMemberWithOtherHATake(t *testing.T) { |
| } { |
| t.Run(c.raw, func(t *testing.T) { |
| h := newFloorHarness(t, false) |
| - h.f.haTake[ref(fakeIID)] = c.take |
| + h.f.haHandover[ref(fakeIID)] = c.take |
| r := h.floor("replace", "") |
| if c.raw == "1" { |
| h.drained(t, r) |
| @@ -278,8 +301,8 @@ func TestFloorMemberWithOtherHATake(t *testing.T) { |
| if c.raw == "1.0" || c.raw == "1e0" { |
| for _, row := range r.e.j.Rows() { |
| res, _ := row["result"].(map[string]any) |
| - if row["kind"] == "response" && res["box"] == ref(fakeIID) && res["ha_take"] != int64(1) { |
| - t.Fatalf("journaled ha_take = %#v, want 1", res["ha_take"]) |
| + if row["kind"] == "response" && res["box"] == ref(fakeIID) && res["ha_handover"] != int64(1) { |
| + t.Fatalf("journaled ha_handover = %#v, want 1", res["ha_handover"]) |
| } |
| } |
| } |
| @@ -287,45 +310,121 @@ func TestFloorMemberWithOtherHATake(t *testing.T) { |
| } |
| } |
| -func TestFloorFixedForwarderWithoutHATake(t *testing.T) { |
| +func TestFloorFixedForwarderWithoutHAHandover(t *testing.T) { |
| h := newFloorHarness(t, false) |
| h.f.fixed["adi"] = fixedEdges{age: 5 * time.Second} |
| h.refused(t, h.floor("replace", ""), Text("floor_box", "box", "adi")) |
| + // ha_take does not stand in for it. |
| + h = newFloorHarness(t, false) |
| + h.f.fixed["adi"] = fixedEdges{haTake: int64(1), age: 5 * time.Second} |
| + h.refused(t, h.floor("replace", ""), Text("floor_box", "box", "adi")) |
| } |
| -// test_stale_box_is_not_live: an edges file outside DrainAckPeers' |
| -// liveness (older than 15 minutes, more than 60 s ahead, or with no |
| -// readable generation) is not a live box, so its ha_take does not count. |
| -func TestFloorStaleEdgesFileIgnored(t *testing.T) { |
| - for name, age := range map[string]time.Duration{"old": 16 * time.Minute, "ahead": -61 * time.Second} { |
| +// The floor counts every edges file present in the listing, whatever its |
| +// age (held floor capability ruling, 2026-11-10): a box that publishes |
| +// only on change may be hours quiet and still forward. An old file that |
| +// says ha_handover: 1 is counted and met; one without it, of any age, is |
| +// a DR-4 reason naming the box. A file ahead of the clock, or with no |
| +// readable generation, is counted the same way. |
| +func TestFloorCountsEveryEdgesFileWhateverItsAge(t *testing.T) { |
| + ages := map[string]time.Duration{"old": 6 * time.Hour, "week": 7 * 24 * time.Hour, |
| + "just-past": 16 * time.Minute, "ahead": -2 * time.Hour, "fresh": time.Second} |
| + for name, age := range ages { |
| + t.Run(name, func(t *testing.T) { |
| + h := newFloorHarness(t, false) |
| + h.f.fixed[name] = fixedEdges{haHandover: int64(1), age: age} |
| + row := h.drained(t, h.floor("replace", "")) |
| + if !containsValue(row["live"], name) { |
| + t.Fatalf("%s is not counted: %v", name, row["live"]) |
| + } |
| + h = newFloorHarness(t, false) |
| + h.f.fixed[name] = fixedEdges{haTake: int64(1), age: age} |
| + r := h.floor("replace", "") |
| + h.refused(t, r, Text("floor_box", "box", name)) |
| + if !containsValue(r.row(t, "floor")["live"], name) { |
| + t.Fatalf("%s is not counted: %v", name, r.row(t, "floor")["live"]) |
| + } |
| + }) |
| + } |
| + // No readable generation: counted by its capability, not an error. |
| + for _, handover := range []any{int64(1), nil} { |
| h := newFloorHarness(t, false) |
| - h.f.fixed[name] = fixedEdges{age: age} |
| - row := h.drained(t, h.floor("replace", "")) |
| - if containsValue(row["live"], name) { |
| - t.Fatalf("%s is live: %v", name, row["live"]) |
| + h.f.fixed["nogen"] = fixedEdges{haHandover: handover} |
| + h.f.wrap = func(op string, args map[string]any, r any, err error) (any, error) { |
| + if op == "edges" && args["box_ref"] == "nogen" { |
| + r.(map[string]any)["generation"] = "yesterday" |
| + } |
| + return r, err |
| + } |
| + r := h.floor("replace", "") |
| + if handover == nil { |
| + h.refused(t, r, Text("floor_box", "box", "nogen")) |
| + } else { |
| + h.drained(t, r) |
| + } |
| + if !containsValue(r.row(t, "floor")["live"], "nogen") { |
| + t.Fatalf("nogen is not counted: %v", r.row(t, "floor")["live"]) |
| } |
| } |
| - // The bounds themselves are live. |
| +} |
| + |
| +// A declared fixed box with no edges file is DR-4, naming it (Astra r1 |
| +// F1.2): a fixed box whose first PUT fails can serve and forward with no |
| +// file, so the listing alone cannot prove every forwarder was counted. |
| +func TestFloorDeclaredFixedBoxWithoutAFile(t *testing.T) { |
| h := newFloorHarness(t, false) |
| - h.f.fixed["edge-old"] = fixedEdges{haTake: int64(1), age: 15 * time.Minute} |
| - h.f.fixed["edge-ahead"] = fixedEdges{haTake: int64(1), age: -60 * time.Second} |
| - row := h.drained(t, h.floor("replace", "")) |
| - if !containsValue(row["live"], "edge-old") || !containsValue(row["live"], "edge-ahead") { |
| - t.Fatalf("live = %v", row["live"]) |
| + h.c.FixedBoxes = []string{"adi", "tito"} |
| + r := h.floor("replace", "") |
| + h.refused(t, r, Text("floor_fixed_missing", "box", "tito")) |
| + if containsValue(r.row(t, "floor")["live"], "tito") { |
| + t.Fatalf("tito counted: %v", r.row(t, "floor")["live"]) |
| } |
| - // No readable generation: skipped, not an error. |
| + // adi's first PUT failed: its file was never written. |
| h = newFloorHarness(t, false) |
| - h.f.fixed["nogen"] = fixedEdges{} |
| - h.f.wrap = func(op string, args map[string]any, r any, err error) (any, error) { |
| - if op == "edges" && args["box_ref"] == "nogen" { |
| - r.(map[string]any)["generation"] = "yesterday" |
| - } |
| - return r, err |
| - } |
| - row = h.drained(t, h.floor("replace", "")) |
| - if containsValue(row["live"], "nogen") { |
| - t.Fatalf("live = %v", row["live"]) |
| + delete(h.f.fixed, "adi") |
| + h.refused(t, h.floor("replace", ""), Text("floor_fixed_missing", "box", "adi")) |
| + // A file present for a box not declared still counts by its capability. |
| + h = newFloorHarness(t, false) |
| + h.f.fixed["other"] = fixedEdges{age: time.Minute} |
| + h.refused(t, h.floor("replace", ""), Text("floor_box", "box", "other")) |
| +} |
| + |
| +// The fixed-box declaration must be explicit: a non-empty fixed_boxes, or |
| +// no_fixed_boxes true, never both and never neither. Anything else is a |
| +// floor error, never read as "no fixed boxes". |
| +func TestFloorFixedBoxesDeclaration(t *testing.T) { |
| + yes, no := true, false |
| + for _, c := range []struct { |
| + name string |
| + boxes []string |
| + none *bool |
| + err string // "" drains |
| + }{ |
| + {"list", []string{"adi"}, nil, ""}, |
| + {"list, none false", []string{"adi"}, &no, ""}, |
| + {"none true, list absent", nil, &yes, ""}, |
| + {"none true, list empty", []string{}, &yes, ""}, |
| + {"both", []string{"adi"}, &yes, "floor_fixed_both"}, |
| + {"neither", nil, nil, "floor_fixed_boxes"}, |
| + {"list empty", []string{}, nil, "floor_fixed_boxes"}, |
| + {"none false, list absent", nil, &no, "floor_fixed_boxes"}, |
| + {"none false, list empty", []string{}, &no, "floor_fixed_boxes"}, |
| + } { |
| + t.Run(c.name, func(t *testing.T) { |
| + h := newFloorHarness(t, false) |
| + h.c.FixedBoxes, h.c.NoFixedBoxes = c.boxes, c.none |
| + if c.err == "" { |
| + h.drained(t, h.floor("replace", "")) |
| + return |
| + } |
| + h.floorError(t, h.floor("replace", ""), Text(c.err)) |
| + }) |
| } |
| + // no_fixed_boxes true does not excuse a present file: adi still counts. |
| + h := newFloorHarness(t, false) |
| + h.c.FixedBoxes, h.c.NoFixedBoxes = nil, &yes |
| + h.f.fixed["adi"] = fixedEdges{age: time.Minute} |
| + h.refused(t, h.floor("replace", ""), Text("floor_box", "box", "adi")) |
| } |
| func TestFloorOldPinnedTemplate(t *testing.T) { |
diff --git a/internal/grouproll/testdata/parity-ledger.tsv b/internal/grouproll/testdata/parity-ledger.tsv| index d81b1f149..b62999077 100644 |
| --- a/internal/grouproll/testdata/parity-ledger.tsv |
| +++ b/internal/grouproll/testdata/parity-ledger.tsv |
| @@ -199,10 +199,10 @@ held CancelDrainTests.test_cancel_lifts_fence_after_failed_drain ported TestCanc |
| held CancelDrainTests.test_refused_cancel_keeps_fence ported TestCancelDrainRefusedKeepsFence |
| held CancelDrainTests.test_cancel_proven_by_status ported TestCancelDrainProvenByStatus |
| held CancelDrainTests.test_cancel_only_for_a_failed_drain_of_this_member ported TestCancelDrainOnlyForAFailedDrainOfThisMember |
| -held FloorTests.test_member_without_ha_take ported TestFloorMemberWithoutHATake TestDepartFloorRefused |
| -held FloorTests.test_member_with_other_ha_take ported TestFloorMemberWithOtherHATake TestDepartFloorRefused |
| -held FloorTests.test_fixed_forwarder_without_ha_take ported TestFloorFixedForwarderWithoutHATake TestDepartFloorRefused |
| -held FloorTests.test_stale_box_is_not_live ported TestFloorStaleEdgesFileIgnored TestDepartStaleBoxIsNotLive |
| +held FloorTests.test_member_without_ha_take ported TestFloorMemberWithoutHAHandover TestFloorIgnoresHATake TestDepartFloorRefused ruling: ha_handover, not ha_take, is the floor's capability (held floor capability, agent manager 8a3d302, 2026-11-10) |
| +held FloorTests.test_member_with_other_ha_take ported TestFloorMemberWithOtherHAHandover TestDepartFloorRefused ruling: ha_handover, not ha_take, is the floor's capability (held floor capability, agent manager 8a3d302, 2026-11-10) |
| +held FloorTests.test_fixed_forwarder_without_ha_take ported TestFloorFixedForwarderWithoutHAHandover TestDepartFloorRefused ruling: ha_handover, not ha_take, is the floor's capability (held floor capability, agent manager 8a3d302, 2026-11-10) |
| +held FloorTests.test_stale_box_is_not_live does-not-apply ruling: held floor capability (agent manager 8a3d302, 2026-11-10): the floor counts every present edges file whatever its age, so no file is skipped as stale (TestFloorCountsEveryEdgesFileWhateverItsAge, TestDepartCountsOldEdgesFiles) |
| held FloorTests.test_old_pinned_template ported TestFloorOldPinnedTemplate TestDepartFloorRefused |
| held FloorTests.test_uncomparable_pinned_template_is_an_error ported TestFloorUncomparablePinnedTemplateIsAnError TestDepartFloorErrorRefusesWithoutDR4 |
| held FloorTests.test_no_floor_config ported TestFloorNoFloorConfig TestDepartFloorRefused |
diff --git a/internal/grouproll/testdata/remotecommand/main.go b/internal/grouproll/testdata/remotecommand/main.go| index d4ac40531..1cffdc46f 100644 |
| --- a/internal/grouproll/testdata/remotecommand/main.go |
| +++ b/internal/grouproll/testdata/remotecommand/main.go |
| @@ -23,6 +23,9 @@ func main() { |
| Transaction string `json:"transaction"` |
| Permit map[string]any `json:"permit"` |
| Nonce string `json:"nonce"` |
| + // Peers is drain's acknowledgement list; absent stays nil (the |
| + // builder refuses a drain without one). |
| + Peers []string `json:"peers"` |
| } |
| dec := json.NewDecoder(os.Stdin) |
| dec.UseNumber() |
| @@ -35,7 +38,7 @@ func main() { |
| fmt.Fprintln(os.Stderr, err) |
| os.Exit(2) |
| } |
| - args := grouproll.BoxArgs{SHA256: req.SHA256, Transaction: req.Transaction} |
| + args := grouproll.BoxArgs{SHA256: req.SHA256, Transaction: req.Transaction, Peers: req.Peers} |
| if req.Permit != nil { |
| args.Permit = permit.(map[string]any) |
| } |
diff --git a/internal/grouproll/text.go b/internal/grouproll/text.go| index d8c21e565..c9a1b8e54 100644 |
| --- a/internal/grouproll/text.go |
| +++ b/internal/grouproll/text.go |
| @@ -91,7 +91,13 @@ var text = map[string]string{ |
| "cancel_refused": "cancel-drain needs this member's transaction after a failed drain: closed, or stopped while its drain was still moving hosts", |
| "cancel_failed": "drain --cancel did not finish. The fence stays: {detail}", |
| "cancelled": "The drain was cancelled and the start fence removed.", |
| - "floor_box": "Live box {box} does not publish ha_take: 1", |
| + "floor_box": "Box {box} does not publish ha_handover: 1", |
| + "floor_fixed_missing": "Fixed box {box} is in fixed_boxes but has no edges file", |
| + "floor_fixed_boxes": "The config must list the deployment's fixed boxes in fixed_boxes, or set no_fixed_boxes to true if it has none", |
| + "floor_legacy": "This transaction's floor was recorded by an older tool that did not count every edges file, so it cannot be resumed into a drain. Do not resume it: end it with abandon, return, cancel-drain or close-lost, whichever applies", |
| + "floor_population": "This transaction's floor row has no valid list of the boxes it counted, so the drain cannot name them. Do not resume it: end it with abandon, return, cancel-drain or close-lost, whichever applies", |
| + "drain_peers_many": "The floor counted {count} other boxes, more than the {max} one drain request can name", |
| + "floor_fixed_both": "The config lists fixed_boxes and also sets no_fixed_boxes to true. Keep only one", |
| "floor_unreadable": "The edges file {key} cannot be read", |
| "floor_template": "The pinned launch template boots release {release}, below ha_floor", |
| "floor_version": "The roll's release {release} is below ha_floor", |
diff --git a/internal/grouproll/text_test.go b/internal/grouproll/text_test.go| index 91f722e39..e82abd1c3 100644 |
| --- a/internal/grouproll/text_test.go |
| +++ b/internal/grouproll/text_test.go |
| @@ -12,8 +12,11 @@ var placeholderPattern = regexp.MustCompile(`\{([a-z_]+)\}`) |
| // for every placeholder it names. A key whose text names a placeholder |
| // Text cannot fill, or leaves a brace behind, fails here. |
| func TestTextRendersEveryKey(t *testing.T) { |
| - if len(text) != 139 { |
| - t.Fatalf("text has %d keys, want the 139 approved", len(text)) |
| + // 139 approved, plus floor_fixed_missing, floor_fixed_boxes, |
| + // floor_fixed_both, drain_peers_many, floor_legacy and floor_population |
| + // (held floor capability, 2026-11-10), not yet copy-reviewed. |
| + if len(text) != 145 { |
| + t.Fatalf("text has %d keys, want the 139 approved plus 6", len(text)) |
| } |
| for key, raw := range text { |
| var args []string |
diff --git a/internal/host/edgesfile.go b/internal/host/edgesfile.go| index 3fedae8b9..5bf859bc1 100644 |
| --- a/internal/host/edgesfile.go |
| +++ b/internal/host/edgesfile.go |
| @@ -396,6 +396,14 @@ type edgesFile struct { |
| // ignores it. Absent is an older build or a box that is not HA, which a |
| // draining box never asks. |
| HATake int `json:"ha_take,omitempty"` |
| + // HAHandover is 1 on every box this build writes, HA or not, set by the |
| + // pass itself and never from config: the binary understands the held |
| + // requests headers (X-Carlos-Handover, the replay mark) and the drain |
| + // acknowledgement it may be asked for (region HA §25.4-§25.9). The |
| + // group roll's floor (internal/grouproll Engine.Floor) counts every |
| + // edges file by it. It says nothing about takes: ha_take alone does. |
| + // Additive (omitempty): absent is an older build. |
| + HAHandover int `json:"ha_handover,omitempty"` |
| // SecretsKeyFP is the fingerprint of this box's CARLOS_SECRETS_KEY's |
| // public half (appconfig.KeyFingerprint), NEVER the key. Additive and |
| @@ -1049,6 +1057,7 @@ func edgesFileWriteClaims(ctx context.Context, s release.Store, reg *registry.Re |
| f.Capabilities = append(slices.Clone(f.Capabilities), edgesfile.NamesCapability) |
| } |
| f.BurstNotices = true |
| + f.HAHandover = 1 |
| if slices.Contains(f.Capabilities, capRegionHA1) { |
| f.HATake = 1 |
| } |
diff --git a/internal/host/edgesfile_test.go b/internal/host/edgesfile_test.go| index b441259e5..3985157e0 100644 |
| --- a/internal/host/edgesfile_test.go |
| +++ b/internal/host/edgesfile_test.go |
| @@ -327,7 +327,7 @@ func TestEdgesFileRawWireBodyMatchesSchema(t *testing.T) { |
| t.Fatalf("generation %q is not RFC3339: %v", probe.Generation, err) |
| } |
| - want := `{"v":1,"box":"quiet-harbour","eip":"203.0.113.10","hibernation_configured":false,"serves_shared_pool":false,"accepts_inbound":false,"named_pools":[],"burst_notices":true,"capabilities":["names-2"],"moves_protocol":0,"seeds_protocol":0,"addrs":null,"generation":"` + |
| + want := `{"v":1,"box":"quiet-harbour","eip":"203.0.113.10","hibernation_configured":false,"serves_shared_pool":false,"accepts_inbound":false,"named_pools":[],"burst_notices":true,"ha_handover":1,"capabilities":["names-2"],"moves_protocol":0,"seeds_protocol":0,"addrs":null,"generation":"` + |
| probe.Generation + `","hosts":{"app.example.com":{"role":"home","platform":false}}}` |
| if string(got) != want { |
| t.Fatalf("raw wire body =\n%s\nwant\n%s", got, want) |
| @@ -370,7 +370,7 @@ func TestEdgesFileRawWireBodyRegionField(t *testing.T) { |
| t.Fatal(err) |
| } |
| gen := genOf(t, got) |
| - want := `{"v":1,"box":"quiet-harbour","eip":"203.0.113.10","hibernation_configured":false,"serves_shared_pool":false,"accepts_inbound":false,"named_pools":[],"burst_notices":true,"capabilities":["names-2"],"moves_protocol":0,"seeds_protocol":0,"addrs":null,"generation":"` + |
| + want := `{"v":1,"box":"quiet-harbour","eip":"203.0.113.10","hibernation_configured":false,"serves_shared_pool":false,"accepts_inbound":false,"named_pools":[],"burst_notices":true,"ha_handover":1,"capabilities":["names-2"],"moves_protocol":0,"seeds_protocol":0,"addrs":null,"generation":"` + |
| gen + `","hosts":{"app.example.com":{"role":"home","platform":false}}}` |
| if string(got) != want { |
| t.Fatalf("raw wire body (region unset) =\n%s\nwant\n%s", got, want) |
| @@ -389,7 +389,7 @@ func TestEdgesFileRawWireBodyRegionField(t *testing.T) { |
| t.Fatal(err) |
| } |
| gen := genOf(t, got) |
| - want := `{"v":1,"box":"quiet-harbour","eip":"203.0.113.10","region":"eu-west-1","hibernation_configured":false,"serves_shared_pool":false,"accepts_inbound":false,"named_pools":[],"burst_notices":true,"capabilities":["names-2"],"moves_protocol":0,"seeds_protocol":0,"addrs":null,"generation":"` + |
| + want := `{"v":1,"box":"quiet-harbour","eip":"203.0.113.10","region":"eu-west-1","hibernation_configured":false,"serves_shared_pool":false,"accepts_inbound":false,"named_pools":[],"burst_notices":true,"ha_handover":1,"capabilities":["names-2"],"moves_protocol":0,"seeds_protocol":0,"addrs":null,"generation":"` + |
| gen + `","hosts":{"app.example.com":{"role":"home","platform":false}}}` |
| if string(got) != want { |
| t.Fatalf("raw wire body (region set) =\n%s\nwant\n%s", got, want) |
| @@ -943,7 +943,7 @@ func TestEdgesFileRawWireBodyPlacementField(t *testing.T) { |
| if err := json.Unmarshal(got, &probe); err != nil { |
| t.Fatal(err) |
| } |
| - want := `{"v":1,"box":"quiet-harbour","eip":"203.0.113.10","region":"eu-west-2","placement":"uk","hibernation_configured":false,"serves_shared_pool":false,"accepts_inbound":false,"named_pools":[],"burst_notices":true,"capabilities":["names-2"],"moves_protocol":0,"seeds_protocol":0,"addrs":null,"generation":"` + |
| + want := `{"v":1,"box":"quiet-harbour","eip":"203.0.113.10","region":"eu-west-2","placement":"uk","hibernation_configured":false,"serves_shared_pool":false,"accepts_inbound":false,"named_pools":[],"burst_notices":true,"ha_handover":1,"capabilities":["names-2"],"moves_protocol":0,"seeds_protocol":0,"addrs":null,"generation":"` + |
| probe.Generation + `","hosts":{"app.example.com":{"role":"home","platform":false}}}` |
| if string(got) != want { |
| t.Fatalf("raw wire body (placement set) =\n%s\nwant\n%s", got, want) |
| @@ -1467,7 +1467,9 @@ func TestEdgesFileAdvertisesBurstNotices(t *testing.T) { |
| // An HA box says ha_take: 1 (region HA §25.7): its edge answers take |
| // requests itself, and a draining box sends takes only to a file that says |
| -// so. Every other box's file is unchanged: no ha_take key at all. |
| +// so. Every other box's file has no ha_take key at all. Every box, HA or |
| +// not, says ha_handover: 1 (§25.9): the binary understands held requests, |
| +// which is what the group roll's floor counts. |
| func TestEdgesFileAdvertisesHATake(t *testing.T) { |
| for name, tc := range map[string]struct { |
| caps []string |
| @@ -1496,6 +1498,10 @@ func TestEdgesFileAdvertisesHATake(t *testing.T) { |
| if tc.want == "" && ok || tc.want != "" && string(got) != tc.want { |
| t.Fatalf("ha_take = %q (present %v) in %s, want %q", got, ok, body, tc.want) |
| } |
| + // ha_handover is the binary's, whatever the box's capabilities. |
| + if got := string(raw["ha_handover"]); got != "1" { |
| + t.Fatalf("ha_handover = %q in %s, want 1", got, body) |
| + } |
| }) |
| } |
| } |
| @@ -1820,7 +1826,7 @@ func TestEdgesFileAddrsEmptyAndUnreadable(t *testing.T) { |
| } |
| return strings.Replace(string(body), probe.Generation, "GEN", 1) |
| } |
| - const head = `{"v":1,"box":"%s","eip":"203.0.113.10","hibernation_configured":false,"serves_shared_pool":false,"accepts_inbound":false,"named_pools":[],"burst_notices":true,"capabilities":["names-2"],"moves_protocol":0,"seeds_protocol":0,` |
| + const head = `{"v":1,"box":"%s","eip":"203.0.113.10","hibernation_configured":false,"serves_shared_pool":false,"accepts_inbound":false,"named_pools":[],"burst_notices":true,"ha_handover":1,"capabilities":["names-2"],"moves_protocol":0,"seeds_protocol":0,` |
| const tail = `,"generation":"GEN","hosts":{"app.example.com":{"role":"home","platform":false}}}` |
| r := &addrsReader{} |
diff --git a/internal/host/egress_nopolicy_linux_test.go b/internal/host/egress_nopolicy_linux_test.go| index aa896778f..48288321c 100644 |
| --- a/internal/host/egress_nopolicy_linux_test.go |
| +++ b/internal/host/egress_nopolicy_linux_test.go |
| @@ -385,9 +385,9 @@ func TestEgressNoPolicyBoxPublishesAsMain(t *testing.T) { |
| mainBody := fmt.Sprintf(mainNoPolicyEdges, probeGen.Generation) |
| const addrsField = `"addrs":["10.0.1.5","fe80::1"],` |
| wantBody := strings.Replace(mainBody, `"generation":`, addrsField+`"generation":`, 1) |
| - wantBody = strings.Replace(wantBody, `"moves_protocol":`, `"named_pools":[],"burst_notices":true,"capabilities":["names-2"],"moves_protocol":`, 1) |
| + wantBody = strings.Replace(wantBody, `"moves_protocol":`, `"named_pools":[],"burst_notices":true,"ha_handover":1,"capabilities":["names-2"],"moves_protocol":`, 1) |
| if string(body) != wantBody { |
| - t.Fatalf("the edges file is not main's plus addrs and burst_notices:\n%s\nwant:\n%s", body, wantBody) |
| + t.Fatalf("the edges file is not main's plus addrs, burst_notices and ha_handover:\n%s\nwant:\n%s", body, wantBody) |
| } |
| }) |
| } |
diff --git a/internal/host/group_maintenance_drain.go b/internal/host/group_maintenance_drain.go| index 36079b092..8f8e15d1c 100644 |
| --- a/internal/host/group_maintenance_drain.go |
| +++ b/internal/host/group_maintenance_drain.go |
| @@ -118,7 +118,7 @@ func (cmd *groupMaintenanceCommand) runDrain(ctx context.Context, out io.Writer) |
| func (cmd *groupMaintenanceCommand) moveUnderway(ctx context.Context, agent drainCaller) bool { |
| sctx, cancel := context.WithTimeout(ctx, 10*time.Second) |
| defer cancel() |
| - r, err := agent(sctx, "status", "") |
| + r, err := agent(sctx, "status", "", nil) |
| if err != nil || r.err() != nil || r.Status == nil { |
| return false |
| } |
| @@ -128,7 +128,7 @@ func (cmd *groupMaintenanceCommand) moveUnderway(ctx context.Context, agent drai |
| // drainStep asks the agent for one step and returns its report. |
| func (cmd *groupMaintenanceCommand) drainStep(ctx context.Context, agent drainCaller, step string) (*drainReport, error) { |
| - r, err := agent(ctx, step, cmd.txn) |
| + r, err := agent(ctx, step, cmd.txn, cmd.peers) |
| if err != nil { |
| return nil, err |
| } |
| @@ -158,7 +158,7 @@ func (cmd *groupMaintenanceCommand) runDrainCancel(ctx context.Context) error { |
| } |
| ctx, cancel := context.WithTimeout(ctx, 2*time.Minute) |
| defer cancel() |
| - r, callErr := cmd.agent()(ctx, "cancel", cmd.txn) |
| + r, callErr := cmd.agent()(ctx, "cancel", cmd.txn, nil) |
| if callErr == nil { |
| callErr = r.err() |
| } |
| @@ -193,7 +193,7 @@ func (cmd *groupMaintenanceCommand) handoverStatus(ctx context.Context) (mainten |
| ds := maintenanceDrainStatus{State: "unknown"} |
| sctx, cancel := context.WithTimeout(ctx, 5*time.Second) |
| defer cancel() |
| - r, err := cmd.agent()(sctx, "status", "") |
| + r, err := cmd.agent()(sctx, "status", "", nil) |
| if err == nil { |
| err = r.err() |
| } |
diff --git a/internal/host/group_maintenance_verbs.go b/internal/host/group_maintenance_verbs.go| index 1c8e2ef5a..173785bd0 100644 |
| --- a/internal/host/group_maintenance_verbs.go |
| +++ b/internal/host/group_maintenance_verbs.go |
| @@ -11,6 +11,7 @@ import ( |
| "net/http" |
| "os" |
| "path/filepath" |
| + "strings" |
| "time" |
| "github.com/carlosframework/platform/internal/hostenv" |
| @@ -35,11 +36,13 @@ Root only, on a group member. Use through the attended Session Manager operator. |
| Local only. A consumed rollback permit cannot be replayed. |
| permit Read at most 4096 bytes of permit JSON from stdin and install it. |
| revoke Remove the permit. Keep all consumed-action records. |
| - drain <transaction> |
| + drain --peers=<box,...> <transaction> |
| Drain this member for a planned handover: withdraw it and wait for every |
| - live box to acknowledge, install the start fence for the transaction, |
| - then move every awake host away and drain the connections. Print the |
| - agent's JSON report. Exit 0 only when the report's result is ok. |
| + listed box, and any other box with an edges file, to acknowledge, install |
| + the start fence for the transaction, then move every awake host away and |
| + drain the connections. --peers lists every other box the operator's |
| + floor counted (empty when it counted none). Print the agent's JSON |
| + report. Exit 0 only when the report's result is ok. |
| drain --cancel <transaction> |
| End the drain of the transaction and remove its start fence. |
| fence-clear <transaction> |
| @@ -73,6 +76,10 @@ func RunGroupMaintenance(args []string, in io.Reader, out, stderr io.Writer) int |
| fmt.Fprint(stderr, groupMaintenanceHelp) |
| return 2 |
| } |
| + var peers []string |
| + if verb == "drain" && len(args) == 3 { |
| + peers, _ = parseDrainPeersFlag(args[1]) |
| + } |
| digest, txn := value, "" |
| if drainVerb(verb) { |
| digest, txn = "", value |
| @@ -80,7 +87,7 @@ func RunGroupMaintenance(args []string, in io.Reader, out, stderr io.Writer) int |
| cmd := groupMaintenanceCommand{ |
| a: &systemApplier{etcDir: "/etc", optDir: release.OptDir(), dataDir: dataDir(), ops: productionSysOps()}, |
| euid: os.Geteuid, root: "/", edge: maintenanceEdgeProcess, |
| - client: maintenanceHealthClient(nil), sha256: digest, txn: txn, |
| + client: maintenanceHealthClient(nil), sha256: digest, txn: txn, peers: peers, |
| startedAt: func(start string) (string, error) { return maintenanceProcessStartedAt("/proc", start) }, |
| configure: configureMaintenanceApplier, |
| } |
| @@ -104,6 +111,9 @@ type groupMaintenanceCommand struct { |
| configure func(*systemApplier, map[string]string) error |
| // txn is the drain verbs' transaction. |
| txn string |
| + // peers is drain's --peers list, nil when the caller passed none (the |
| + // agent then refuses the drain). |
| + peers []string |
| // fence and drainCall are the start fence and the agent call; zero |
| // means production's (groupStartFence, execDrainCall: a child as the |
| // agent's user, hadrain_call.go). |
| @@ -448,7 +458,14 @@ func maintenanceArguments(args []string) (string, string, error) { |
| txn := func(s string) bool { return groupTransactionID.MatchString(s) && s[0] != '-' } |
| switch { |
| case len(args) == 2 && args[0] == "drain" && txn(args[1]): |
| + // No --peers: an older verb. Accepted here so the agent's refusal |
| + // is reported; the drain refuses before any move. |
| return "drain", args[1], nil |
| + case len(args) == 3 && args[0] == "drain" && strings.HasPrefix(args[1], drainPeersFlag) && txn(args[2]): |
| + if _, ok := parseDrainPeersFlag(args[1]); !ok { |
| + return "", "", errGroupMaintenance |
| + } |
| + return "drain", args[2], nil |
| case len(args) == 3 && args[0] == "drain" && args[1] == "--cancel" && txn(args[2]): |
| return "drain-cancel", args[2], nil |
| case len(args) == 2 && args[0] == "fence-clear" && txn(args[1]): |
diff --git a/internal/host/group_names_test.go b/internal/host/group_names_test.go| index e321b405c..a879b782b 100644 |
| --- a/internal/host/group_names_test.go |
| +++ b/internal/host/group_names_test.go |
| @@ -462,7 +462,7 @@ var groupNameProducerInventory = map[string]string{ |
| "claimunit_binding.go:claimUnitShape.route": "f38fd6e10aba680354ee908c255fd34e731fe2d1a22fffd41ac449e8b763dd2c", |
| "claimunit_policy.go:claimUnitShapeCheck": "45f16830e5ed834995ca573a710f1e390a504b7eb78c3c0465ac70e7f306e50c", |
| "claimunit_policy.go:rootClaimRestartShape": "1d0370516c32482b1784f4bd4ab0deb042c31120d81f4dc8c417f52b24ef76ac", |
| - "edgesfile.go:edgesFileWriteClaims": "577e7cec14583485e02efe50f53160cd626322b2ff494fc0c86fbfbd1cfac24a", // #724: dns_pointing mark on custom names only; no name or class derivation |
| + "edgesfile.go:edgesFileWriteClaims": "f19e0a6547b891ad689fb58b11d842ba9b7214f6df766bc46e9da0a4cce4d9d7", // held floor capability: constant ha_handover=1 on every pass; no name or class derivation |
| "movesheldenv.go:composeHeldEnv": "17ad3714758d1c07a71375734c125496855a16ca800eb814bde58283d3a5318b", |
| "movesheldrelease_root.go:heldReleaseRoute": "10bf824edc963319a38a47b91877b865977b1dc4a27c6e7680c46704289a7df7", |
| "movesstage.go:heldReleasePublished": "edad51c04a01657b77a9fc469404db5fde51cff1f2c61e243d6a717fb6224e85", |
diff --git a/internal/host/hadrain.go b/internal/host/hadrain.go| index 4a3234cd4..701404fd0 100644 |
| --- a/internal/host/hadrain.go |
| +++ b/internal/host/hadrain.go |
| @@ -98,7 +98,7 @@ type drainActivator interface { |
| // drainEdge is the edge's half (internal/edge hadrain.go, hatake.go, |
| // hadrainconns.go). |
| type drainEdge interface { |
| - DrainAckPeers(now time.Time) []string |
| + DrainAckPeers() []string |
| AskDrainSeen(ctx context.Context, peer, txn, phase string, id uint64) (bool, error) |
| PeerTakes(ref string) bool |
| PeerDraining(ref string) bool |
| @@ -202,7 +202,10 @@ type drainDriver struct { |
| } |
| type drainRun struct { |
| - step string |
| + step string |
| + // peers is the step's acknowledgement population as the verb passed |
| + // it (§25.4 step 1). |
| + peers []string |
| cancel context.CancelFunc |
| done chan struct{} |
| } |
| @@ -212,6 +215,7 @@ var ( |
| errDrainNoFence = errors.New("the start fence for this transaction is not installed") |
| errDrainStep = errors.New("withdraw must succeed before move") |
| errDrainUnknown = errors.New("unknown drain step") |
| + errDrainNoPeers = errors.New("the drain request names no acknowledgement peers; the operator's tool is older than this agent") |
| errDrainCancel = errors.New("the drain is being cancelled") |
| ) |
| @@ -222,13 +226,20 @@ func newDrainDriver(act drainActivator, e drainEdge, marks drainMarks, fence fun |
| // start runs step for txn, or joins the same step already running, and |
| // returns its completion and report. A finished move that succeeded is |
| // answered again as it was. |
| -func (d *drainDriver) start(txn, step string) (<-chan struct{}, error) { |
| +func (d *drainDriver) start(txn, step string, peers []string) (<-chan struct{}, error) { |
| if !groupTransactionID.MatchString(txn) { |
| return nil, errGroupMaintenance |
| } |
| if step != "withdraw" && step != "move" { |
| return nil, errDrainUnknown |
| } |
| + // The verb's list is the acknowledgement population, read once from |
| + // its listing of control/edges/ (held floor capability ruling, |
| + // 2026-11-10). Without it nothing runs: no move is made on this box's |
| + // own fold alone. |
| + if !validDrainPeers(peers) { |
| + return nil, errDrainNoPeers |
| + } |
| d.mu.Lock() |
| defer d.mu.Unlock() |
| if d.cancelling { |
| @@ -272,7 +283,7 @@ func (d *drainDriver) start(txn, step string) (<-chan struct{}, error) { |
| } |
| d.txn = txn |
| ctx, cancel := context.WithDeadline(context.Background(), d.deadline) |
| - r := &drainRun{step: step, cancel: cancel, done: make(chan struct{})} |
| + r := &drainRun{step: step, peers: append([]string{}, peers...), cancel: cancel, done: make(chan struct{})} |
| rep := &drainReport{V: 1, Transaction: txn, Incarnation: agentIncarnation, Step: step, Result: "running", StartedAt: now, |
| Reasons: []string{}, Acked: []string{}, Moved: []drainMoved{}, Released: []drainLeft{}, Unclean: []string{}, Left: []drainLeft{}} |
| d.run, d.report = r, rep |
| @@ -281,9 +292,9 @@ func (d *drainDriver) start(txn, step string) (<-chan struct{}, error) { |
| defer cancel() |
| var reasons []string |
| if step == "withdraw" { |
| - reasons = d.withdraw(ctx, txn, rep) |
| + reasons = d.withdraw(ctx, txn, rep, r.peers) |
| } else { |
| - reasons = d.move(ctx, txn, rep) |
| + reasons = d.move(ctx, txn, rep, r.peers) |
| } |
| if ctx.Err() == context.DeadlineExceeded { |
| reasons = append(reasons, "the drain deadline passed") |
| @@ -399,17 +410,23 @@ func (d *drainDriver) note(f func()) { |
| } |
| // withdraw is step 1: the drain state published and acknowledged. |
| -func (d *drainDriver) withdraw(ctx context.Context, txn string, rep *drainReport) []string { |
| +func (d *drainDriver) withdraw(ctx context.Context, txn string, rep *drainReport, listed []string) []string { |
| if err := d.marks.begin(txn); err != nil { |
| return []string{err.Error()} |
| } |
| - return d.publishAndAck(ctx, txn, edge.DrainPhaseDraining, rep) |
| + return d.publishAndAck(ctx, txn, edge.DrainPhaseDraining, rep, listed) |
| } |
| // publishAndAck waits for the wanted drain state to be published, then |
| -// asks every live box until each has seen it: every 5 s, failing after 2 |
| -// minutes. |
| -func (d *drainDriver) publishAndAck(ctx context.Context, txn, phase string, rep *drainReport) []string { |
| +// asks every box on listed, the verb's population (§25.4 step 1), until |
| +// each has given a signed answer that it has seen it: every 5 s, failing |
| +// after 2 minutes, naming each box that did not. The edge's fold may only |
| +// add boxes, never remove one: a box in the fold that the list lacks (one |
| +// that published after the verb's listing) is asked too, re-read each |
| +// round. The fold's completeness is never evidence (held floor capability |
| +// ruling, 2026-11-10: one population, read once, by the party that |
| +// decides). |
| +func (d *drainDriver) publishAndAck(ctx context.Context, txn, phase string, rep *drainReport, listed []string) []string { |
| pctx, cancel := context.WithTimeout(ctx, drainPublishTimeout) |
| mark, err := d.marks.waitPublished(pctx) |
| cancel() |
| @@ -418,7 +435,13 @@ func (d *drainDriver) publishAndAck(ctx context.Context, txn, phase string, rep |
| } |
| actx, acancel := context.WithTimeout(ctx, drainAckBound) |
| defer acancel() |
| - peers := d.edge.DrainAckPeers(d.now()) |
| + tick := time.NewTicker(drainAckEvery) |
| + defer tick.Stop() |
| + peers := append([]string{}, listed...) |
| + known := make(map[string]bool, len(peers)) |
| + for _, p := range peers { |
| + known[p] = true |
| + } |
| // Only this goroutine reads or writes seen and why; the askers send |
| // their answers back on a channel. |
| seen := map[string]bool{} |
| @@ -428,9 +451,13 @@ func (d *drainDriver) publishAndAck(ctx context.Context, txn, phase string, rep |
| ok bool |
| err error |
| } |
| - tick := time.NewTicker(drainAckEvery) |
| - defer tick.Stop() |
| for { |
| + for _, p := range d.edge.DrainAckPeers() { |
| + if !known[p] { |
| + known[p] = true |
| + peers = append(peers, p) |
| + } |
| + } |
| var pending []string |
| for _, p := range peers { |
| if !seen[p] { |
| @@ -438,6 +465,7 @@ func (d *drainDriver) publishAndAck(ctx context.Context, txn, phase string, rep |
| } |
| } |
| if len(pending) == 0 { |
| + sort.Strings(peers) |
| d.note(func() { rep.Acked = append([]string(nil), peers...) }) |
| return nil |
| } |
| @@ -490,8 +518,8 @@ func allSeen(peers []string, seen map[string]bool) bool { |
| // move is steps 2 to 5, then the transaction's release audit and the |
| // hold statistics, both read after the connection barrier has joined |
| // every request (so every held request's outcome is counted). |
| -func (d *drainDriver) move(ctx context.Context, txn string, rep *drainReport) []string { |
| - reasons := d.moveSteps(ctx, txn, rep) |
| +func (d *drainDriver) move(ctx context.Context, txn string, rep *drainReport, listed []string) []string { |
| + reasons := d.moveSteps(ctx, txn, rep, listed) |
| reasons = append(reasons, d.auditReleases(rep)...) |
| d.note(func() { |
| st := d.act.DrainHoldStatsNow() |
| @@ -545,7 +573,7 @@ func (d *drainDriver) auditReleases(rep *drainReport) []string { |
| } |
| // moveSteps is steps 2 to 5. |
| -func (d *drainDriver) moveSteps(ctx context.Context, txn string, rep *drainReport) []string { |
| +func (d *drainDriver) moveSteps(ctx context.Context, txn string, rep *drainReport, listed []string) []string { |
| fence := func() bool { |
| f := d.fence() |
| return f.Present && f.Err == nil && f.Transaction == txn |
| @@ -607,7 +635,7 @@ func (d *drainDriver) moveSteps(ctx context.Context, txn string, rep *drainRepor |
| if err := d.marks.setDrained(); err != nil { |
| return []string{err.Error()} |
| } |
| - if r := d.publishAndAck(ctx, txn, edge.DrainPhaseDrained, rep); len(r) > 0 { |
| + if r := d.publishAndAck(ctx, txn, edge.DrainPhaseDrained, rep, listed); len(r) > 0 { |
| return r |
| } |
| d.act.EndDrainMoves() |
diff --git a/internal/host/hadrain_call.go b/internal/host/hadrain_call.go| index 940d072bc..e3778298a 100644 |
| --- a/internal/host/hadrain_call.go |
| +++ b/internal/host/hadrain_call.go |
| @@ -32,8 +32,61 @@ import ( |
| "encoding/json" |
| "errors" |
| "io" |
| + "regexp" |
| + "strings" |
| ) |
| +// maxDrainPeers bounds the boxes one drain request names (the verb's |
| +// grouproll.MaxDrainPeers). |
| +const maxDrainPeers = 256 |
| + |
| +// drainPeerRef is a box reference as an edges key names it. |
| +var drainPeerRef = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$`) |
| + |
| +// validDrainPeers is whether peers is a drain request's acknowledgement |
| +// population (region HA §25.4 step 1): present (never nil), at most |
| +// maxDrainPeers references in the edges-key grammar, no duplicates. An |
| +// empty list is valid: the verb's floor counted no other box. |
| +func validDrainPeers(peers []string) bool { |
| + if peers == nil || len(peers) > maxDrainPeers { |
| + return false |
| + } |
| + seen := make(map[string]bool, len(peers)) |
| + for _, p := range peers { |
| + if !drainPeerRef.MatchString(p) || seen[p] { |
| + return false |
| + } |
| + seen[p] = true |
| + } |
| + return true |
| +} |
| + |
| +// drainPeersFlag is the --peers=<a,b,...> argument the verb passes to drain |
| +// and root passes to the child; "--peers=" is the empty list. |
| +const drainPeersFlag = "--peers=" |
| + |
| +// parseDrainPeersFlag reads a --peers= argument; ok is false for anything |
| +// that is not one, or whose list is not valid. |
| +func parseDrainPeersFlag(arg string) ([]string, bool) { |
| + list, ok := strings.CutPrefix(arg, drainPeersFlag) |
| + if !ok { |
| + return nil, false |
| + } |
| + peers := []string{} |
| + if list != "" { |
| + peers = strings.Split(list, ",") |
| + } |
| + if !validDrainPeers(peers) { |
| + return nil, false |
| + } |
| + return peers, true |
| +} |
| + |
| +// drainPeersArg is peers as a --peers= argument. |
| +func drainPeersArg(peers []string) string { |
| + return drainPeersFlag + strings.Join(peers, ",") |
| +} |
| + |
| // drainCallCommand is the child's private entry point, before CLI dispatch. |
| const drainCallCommand = "__drain-call" |
| @@ -65,10 +118,12 @@ func (r drainCallResult) err() error { |
| } |
| // drainCaller makes one call of the agent's drain socket: op is withdraw, |
| -// move, cancel or status. A transport failure of the caller itself (the |
| +// move, cancel or status. peers is withdraw's and move's acknowledgement |
| +// population as the verb passed it, nil when it passed none (the agent |
| +// then refuses the step). A transport failure of the caller itself (the |
| // child did not run or answered nothing usable) is the error; the agent's |
| // answer, a refusal included, is the result. |
| -type drainCaller func(ctx context.Context, op, txn string) (drainCallResult, error) |
| +type drainCaller func(ctx context.Context, op, txn string, peers []string) (drainCallResult, error) |
| // drainCallOp is whether op is a call the child makes. |
| func drainCallOp(op string) bool { |
| @@ -78,12 +133,12 @@ func drainCallOp(op string) bool { |
| // socketDrainCall is the call itself over c: the child's body, and the |
| // in-process caller tests use. |
| func socketDrainCall(c *drainClient) drainCaller { |
| - return func(ctx context.Context, op, txn string) (drainCallResult, error) { |
| + return func(ctx context.Context, op, txn string, peers []string) (drainCallResult, error) { |
| r := drainCallResult{V: 1} |
| var err error |
| switch op { |
| case "withdraw", "move": |
| - r.Report, err = c.step(ctx, op, txn) |
| + r.Report, err = c.step(ctx, op, txn, peers) |
| case "cancel": |
| err = c.cancel(ctx, txn) |
| case "status": |
| @@ -103,34 +158,44 @@ func socketDrainCall(c *drainClient) drainCaller { |
| } |
| // drainCallArgs reads the child's arguments: an op and a transaction ("-" |
| -// for status). |
| -func drainCallArgs(args []string) (op, txn string, err error) { |
| - if len(args) != 2 || !drainCallOp(args[0]) { |
| - return "", "", errGroupMaintenance |
| +// for status), then for withdraw and move a --peers= list when root was |
| +// given one (peers nil when not). |
| +func drainCallArgs(args []string) (op, txn string, peers []string, err error) { |
| + if (len(args) != 2 && len(args) != 3) || !drainCallOp(args[0]) { |
| + return "", "", nil, errGroupMaintenance |
| } |
| op, txn = args[0], args[1] |
| + if len(args) == 3 { |
| + var ok bool |
| + if op != "withdraw" && op != "move" { |
| + return "", "", nil, errGroupMaintenance |
| + } |
| + if peers, ok = parseDrainPeersFlag(args[2]); !ok { |
| + return "", "", nil, errGroupMaintenance |
| + } |
| + } |
| if op == "status" { |
| if txn != "-" { |
| - return "", "", errGroupMaintenance |
| + return "", "", nil, errGroupMaintenance |
| } |
| - return op, "", nil |
| + return op, "", nil, nil |
| } |
| if !groupTransactionID.MatchString(txn) || txn[0] == '-' { |
| - return "", "", errGroupMaintenance |
| + return "", "", nil, errGroupMaintenance |
| } |
| - return op, txn, nil |
| + return op, txn, peers, nil |
| } |
| // runDrainCallBody is the child after its privileges are dropped: one call |
| // over the socket at path, its answer printed as one JSON line. |
| func runDrainCallBody(ctx context.Context, args []string, path string, out io.Writer) error { |
| - op, txn, err := drainCallArgs(args) |
| + op, txn, peers, err := drainCallArgs(args) |
| if err != nil { |
| return err |
| } |
| ctx, cancel := context.WithTimeout(ctx, haDrainCallBound) |
| defer cancel() |
| - r, err := socketDrainCall(newDrainClient(path))(ctx, op, txn) |
| + r, err := socketDrainCall(newDrainClient(path))(ctx, op, txn, peers) |
| if err != nil { |
| return err |
| } |
| @@ -138,11 +203,15 @@ func runDrainCallBody(ctx context.Context, args []string, path string, out io.Wr |
| } |
| // drainCallChildArgs is the child's argument list after the command: the |
| -// transaction is "-" for status. |
| -func drainCallChildArgs(op, txn string) []string { |
| +// transaction is "-" for status; withdraw and move add --peers= when root |
| +// was given a list. |
| +func drainCallChildArgs(op, txn string, peers []string) []string { |
| if op == "status" { |
| txn = "-" |
| } |
| + if peers != nil && (op == "withdraw" || op == "move") { |
| + return []string{op, txn, drainPeersArg(peers)} |
| + } |
| return []string{op, txn} |
| } |
diff --git a/internal/host/hadrain_call_linux.go b/internal/host/hadrain_call_linux.go| index 1f7a06fc8..dc7ab832c 100644 |
| --- a/internal/host/hadrain_call_linux.go |
| +++ b/internal/host/hadrain_call_linux.go |
| @@ -14,11 +14,11 @@ import ( |
| // execDrainCall is the production drainCaller: one child, run as the |
| // agent's user, per call (hadrain_call.go). |
| -func execDrainCall(ctx context.Context, op, txn string) (drainCallResult, error) { |
| - if !drainCallOp(op) { |
| +func execDrainCall(ctx context.Context, op, txn string, peers []string) (drainCallResult, error) { |
| + if !drainCallOp(op) || (peers != nil && !validDrainPeers(peers)) { |
| return drainCallResult{}, errGroupMaintenance |
| } |
| - cmd, err := drainCallExec(op, txn) |
| + cmd, err := drainCallExec(op, txn, peers) |
| if err != nil { |
| return drainCallResult{}, err |
| } |
| @@ -28,11 +28,11 @@ func execDrainCall(ctx context.Context, op, txn string) (drainCallResult, error) |
| // drainCallExec is the child's command: the pinned executable (fd 3, as |
| // the registry child), the private command, op and transaction, an empty |
| // environment, "/" as its directory, and no stdin. |
| -func drainCallExec(op, txn string) (*exec.Cmd, error) { |
| +func drainCallExec(op, txn string, peers []string) (*exec.Cmd, error) { |
| if registryExecutableError != nil { |
| return nil, registryExecutableError |
| } |
| - cmd := exec.Command("/proc/self/fd/3", append([]string{drainCallCommand}, drainCallChildArgs(op, txn)...)...) |
| + cmd := exec.Command("/proc/self/fd/3", append([]string{drainCallCommand}, drainCallChildArgs(op, txn, peers)...)...) |
| cmd.ExtraFiles = []*os.File{registryExecutable} |
| cmd.Env = []string{} |
| cmd.Dir = "/" |
diff --git a/internal/host/hadrain_call_linux_test.go b/internal/host/hadrain_call_linux_test.go| index 928984dd8..ffe615e4e 100644 |
| --- a/internal/host/hadrain_call_linux_test.go |
| +++ b/internal/host/hadrain_call_linux_test.go |
| @@ -43,20 +43,29 @@ func init() { |
| // transaction; an empty environment, "/" and no stdin. It runs through the |
| // registry child's start (no new privileges) and drops to carlos itself. |
| func TestDrainCallCommand(t *testing.T) { |
| - cmd, err := drainCallExec("move", "t1") |
| + cmd, err := drainCallExec("move", "t1", []string{"adi", "g-0123456789abcdef0123"}) |
| must(t, err) |
| - if cmd.Path != "/proc/self/fd/3" || strings.Join(cmd.Args, " ") != "/proc/self/fd/3 __drain-call move t1" { |
| + if cmd.Path != "/proc/self/fd/3" || strings.Join(cmd.Args, " ") != "/proc/self/fd/3 __drain-call move t1 --peers=adi,g-0123456789abcdef0123" { |
| t.Fatalf("command %q %q", cmd.Path, cmd.Args) |
| } |
| + if cmd, _ = drainCallExec("withdraw", "t1", nil); strings.Join(cmd.Args[1:], " ") != "__drain-call withdraw t1" { |
| + t.Fatalf("no list: %q", cmd.Args) |
| + } |
| + if cmd, _ = drainCallExec("withdraw", "t1", []string{}); strings.Join(cmd.Args[1:], " ") != "__drain-call withdraw t1 --peers=" { |
| + t.Fatalf("empty list: %q", cmd.Args) |
| + } |
| if cmd.Env == nil || len(cmd.Env) != 0 || cmd.Dir != "/" || cmd.Stdin != nil || len(cmd.ExtraFiles) != 1 || cmd.ExtraFiles[0] != registryExecutable { |
| t.Fatalf("env %q dir %q stdin %v extra %v", cmd.Env, cmd.Dir, cmd.Stdin, cmd.ExtraFiles) |
| } |
| - if cmd, _ = drainCallExec("status", ""); strings.Join(cmd.Args[1:], " ") != "__drain-call status -" { |
| + if cmd, _ = drainCallExec("status", "", nil); strings.Join(cmd.Args[1:], " ") != "__drain-call status -" { |
| t.Fatalf("status args %q", cmd.Args) |
| } |
| - if _, err := execDrainCall(context.Background(), "stop", "t1"); err == nil { |
| + if _, err := execDrainCall(context.Background(), "stop", "t1", nil); err == nil { |
| t.Fatal("an unknown op ran a child") |
| } |
| + if _, err := execDrainCall(context.Background(), "withdraw", "t1", []string{"a", "a"}); err == nil { |
| + t.Fatal("a duplicate peer ran a child") |
| + } |
| } |
| func TestDrainCallArgs(t *testing.T) { |
| @@ -65,6 +74,13 @@ func TestDrainCallArgs(t *testing.T) { |
| op, txn string |
| bad bool |
| }{ |
| + {[]string{"withdraw", "t1", "--peers=adi,g-0123456789abcdef0123"}, "withdraw", "t1", false}, |
| + {[]string{"move", "t1", "--peers="}, "move", "t1", false}, |
| + {[]string{"withdraw", "t1", "--peers=adi,adi"}, "", "", true}, |
| + {[]string{"withdraw", "t1", "--peers=a b"}, "", "", true}, |
| + {[]string{"withdraw", "t1", "--peers=,"}, "", "", true}, |
| + {[]string{"cancel", "t1", "--peers="}, "", "", true}, |
| + {[]string{"status", "-", "--peers="}, "", "", true}, |
| {[]string{"withdraw", "t1"}, "withdraw", "t1", false}, |
| {[]string{"move", "t1"}, "move", "t1", false}, |
| {[]string{"cancel", "t1"}, "cancel", "t1", false}, |
| @@ -76,7 +92,7 @@ func TestDrainCallArgs(t *testing.T) { |
| {[]string{"move"}, "", "", true}, |
| {[]string{"move", "t1", "x"}, "", "", true}, |
| } { |
| - op, txn, err := drainCallArgs(tc.args) |
| + op, txn, _, err := drainCallArgs(tc.args) |
| if (err != nil) != tc.bad || op != tc.op || txn != tc.txn { |
| t.Fatalf("%q: %q %q %v", tc.args, op, txn, err) |
| } |
| @@ -114,15 +130,15 @@ func TestDrainCallChildEndToEnd(t *testing.T) { |
| cmd, l := verbDrain(t, d) |
| d.fence = l.read |
| path := socketPathOf(t, cmd) |
| - child := func(ctx context.Context, op, txn string) (drainCallResult, error) { |
| - c, err := drainCallExec(op, txn) |
| + child := func(ctx context.Context, op, txn string, peers []string) (drainCallResult, error) { |
| + c, err := drainCallExec(op, txn, peers) |
| if err != nil { |
| return drainCallResult{}, err |
| } |
| c.Env = []string{"HADRAIN_CALL_TEST_SOCKET=" + path} |
| return runDrainCallChild(ctx, c) |
| } |
| - r, err := child(context.Background(), "status", "") |
| + r, err := child(context.Background(), "status", "", nil) |
| if err != nil || r.err() != nil || r.Status == nil || r.Status.Incarnation != agentIncarnation { |
| t.Fatalf("status through the child: %+v %v", r, err) |
| } |
| @@ -135,7 +151,7 @@ func TestDrainCallChildEndToEnd(t *testing.T) { |
| t.Fatal("the agent's own start gate is open after the withdrawal") |
| } |
| // A refusal comes back as the agent's answer, not a caller failure. |
| - if r, err = child(context.Background(), "cancel", "t2"); err != nil || !strings.Contains(r.Error, errDrainOtherTxn.Error()) || r.AgentDown { |
| + if r, err = child(context.Background(), "cancel", "t2", nil); err != nil || !strings.Contains(r.Error, errDrainOtherTxn.Error()) || r.AgentDown { |
| t.Fatalf("refused cancel: %+v %v", r, err) |
| } |
| if _, err = runDrainVerb(t, cmd, "drain-cancel", "t1"); err != nil || l.read().Present || marks.startsClosed() { |
| @@ -143,13 +159,13 @@ func TestDrainCallChildEndToEnd(t *testing.T) { |
| } |
| // No agent: agent_down. |
| other := filepath.Join(filepath.Dir(path), "none.sock") |
| - c, _ := drainCallExec("status", "") |
| + c, _ := drainCallExec("status", "", nil) |
| c.Env = []string{"HADRAIN_CALL_TEST_SOCKET=" + other} |
| if r, err = runDrainCallChild(context.Background(), c); err != nil || !r.AgentDown { |
| t.Fatalf("no agent: %+v %v", r, err) |
| } |
| // A child that fails or is killed is a caller error, not an answer. |
| - c, _ = drainCallExec("status", "") |
| + c, _ = drainCallExec("status", "", nil) |
| c.Env = []string{"HADRAIN_CALL_TEST_SOCKET=" + path} |
| c.Args = []string{c.Args[0], drainCallCommand, "status", "t1"} |
| if _, err = runDrainCallChild(context.Background(), c); err == nil { |
| @@ -157,7 +173,7 @@ func TestDrainCallChildEndToEnd(t *testing.T) { |
| } |
| ctx, cancel := context.WithCancel(context.Background()) |
| cancel() |
| - c, _ = drainCallExec("status", "") |
| + c, _ = drainCallExec("status", "", nil) |
| c.Env = []string{"HADRAIN_CALL_TEST_SOCKET=" + path} |
| if _, err = runDrainCallChild(ctx, c); err == nil { |
| t.Fatal("a cancelled call answered") |
| @@ -170,7 +186,7 @@ func TestDrainCallChildRefusesWithoutDrop(t *testing.T) { |
| if os.Geteuid() == 0 { |
| t.Skip("as root the child would drop to carlos") |
| } |
| - c, err := drainCallExec("status", "") |
| + c, err := drainCallExec("status", "", nil) |
| must(t, err) |
| out := &cappedBuffer{max: 4096} |
| errOut := &cappedBuffer{max: 4096} |
diff --git a/internal/host/hadrain_call_other.go b/internal/host/hadrain_call_other.go| index 3845266f9..23ef928c0 100644 |
| --- a/internal/host/hadrain_call_other.go |
| +++ b/internal/host/hadrain_call_other.go |
| @@ -10,7 +10,7 @@ import ( |
| ) |
| // execDrainCall: the drain verbs are Linux group members' only. |
| -func execDrainCall(context.Context, string, string) (drainCallResult, error) { |
| +func execDrainCall(context.Context, string, string, []string) (drainCallResult, error) { |
| return drainCallResult{}, errSystemUnsupported |
| } |
diff --git a/internal/host/hadrain_socket.go b/internal/host/hadrain_socket.go| index a57803042..1b378d53f 100644 |
| --- a/internal/host/hadrain_socket.go |
| +++ b/internal/host/hadrain_socket.go |
| @@ -8,8 +8,12 @@ package host |
| // (hadrain_call.go). Instances never see it: their namespaces replace |
| // /run/carlos with an empty tmpfs. |
| // |
| -// POST /v1/drain/withdraw {"transaction":T} step 1; answers the report |
| -// POST /v1/drain/move {"transaction":T} steps 2-5; answers the report |
| +// POST /v1/drain/withdraw {"transaction":T,"peers":[...]} step 1; answers the report |
| +// POST /v1/drain/move {"transaction":T,"peers":[...]} steps 2-5; answers the report |
| +// |
| +// peers is the verb's acknowledgement population (§25.4 step 1): the boxes |
| +// its floor counted, the member excluded. A step without it is refused |
| +// before anything runs. |
| // POST /v1/drain/cancel {"transaction":T} drain --cancel |
| // GET /v1/drain/status incarnation and drain state |
| // |
| @@ -31,14 +35,17 @@ import ( |
| const ( |
| haDrainSocketDir = "/run/carlos/.ha-drain" |
| haDrainSocketPath = haDrainSocketDir + "/drain.sock" |
| - haDrainBodyMax = 4096 |
| + // haDrainBodyMax bounds a request: a transaction and up to |
| + // maxDrainPeers references of at most 128 bytes each. |
| + haDrainBodyMax = 64 << 10 |
| // haDrainCallBound is the verb's backstop on one step: the agent ends |
| // every step by the drain deadline itself. |
| haDrainCallBound = 3 * time.Hour |
| ) |
| type drainAsk struct { |
| - Transaction string `json:"transaction"` |
| + Transaction string `json:"transaction"` |
| + Peers *[]string `json:"peers,omitempty"` |
| } |
| type drainError struct { |
| @@ -78,7 +85,8 @@ func (d *drainDriver) handler() http.Handler { |
| var ask drainAsk |
| dec := json.NewDecoder(bytes.NewReader(b)) |
| dec.DisallowUnknownFields() |
| - if err != nil || len(b) > haDrainBodyMax || dec.Decode(&ask) != nil || !groupTransactionID.MatchString(ask.Transaction) { |
| + if err != nil || len(b) > haDrainBodyMax || dec.Decode(&ask) != nil || !groupTransactionID.MatchString(ask.Transaction) || |
| + (ask.Peers != nil && (step == "cancel" || !validDrainPeers(*ask.Peers))) { |
| w.WriteHeader(http.StatusBadRequest) |
| _ = json.NewEncoder(w).Encode(drainError{Error: errGroupMaintenance.Error()}) |
| return |
| @@ -94,7 +102,11 @@ func (d *drainDriver) handler() http.Handler { |
| _ = json.NewEncoder(w).Encode(struct{}{}) |
| return |
| } |
| - done, err := d.start(ask.Transaction, step) |
| + var peers []string |
| + if ask.Peers != nil { |
| + peers = *ask.Peers |
| + } |
| + done, err := d.start(ask.Transaction, step, peers) |
| if err != nil { |
| w.WriteHeader(http.StatusConflict) |
| _ = json.NewEncoder(w).Encode(drainError{Error: err.Error()}) |
| @@ -167,9 +179,13 @@ func (c *drainClient) call(ctx context.Context, method, path string, body any, o |
| return nil |
| } |
| -func (c *drainClient) step(ctx context.Context, step, txn string) (*drainReport, error) { |
| +func (c *drainClient) step(ctx context.Context, step, txn string, peers []string) (*drainReport, error) { |
| var rep drainReport |
| - if err := c.call(ctx, http.MethodPost, "/v1/drain/"+step, drainAsk{Transaction: txn}, &rep); err != nil { |
| + ask := drainAsk{Transaction: txn} |
| + if peers != nil { |
| + ask.Peers = &peers |
| + } |
| + if err := c.call(ctx, http.MethodPost, "/v1/drain/"+step, ask, &rep); err != nil { |
| return nil, err |
| } |
| return &rep, nil |
diff --git a/internal/host/hadrain_test.go b/internal/host/hadrain_test.go| index f1f19bc7e..2a624eb52 100644 |
| --- a/internal/host/hadrain_test.go |
| +++ b/internal/host/hadrain_test.go |
| @@ -274,7 +274,7 @@ type fakeDrainEdge struct { |
| heldShut []string |
| } |
| -func (f *fakeDrainEdge) DrainAckPeers(time.Time) []string { |
| +func (f *fakeDrainEdge) DrainAckPeers() []string { |
| f.mu.Lock() |
| defer f.mu.Unlock() |
| return append([]string(nil), f.peers...) |
| @@ -456,7 +456,7 @@ func shorten(v *time.Duration, d time.Duration) func() { |
| } |
| func (d *drainDriver) startWithdrawForTest(txn string) error { |
| - done, err := d.start(txn, "withdraw") |
| + done, err := d.start(txn, "withdraw", []string{}) |
| if err != nil { |
| return err |
| } |
| @@ -467,7 +467,13 @@ func (d *drainDriver) startWithdrawForTest(txn string) error { |
| // runDrain runs both steps as the verb does, the fence installed between. |
| func runDrain(t *testing.T, d *drainDriver, txn string) *drainReport { |
| t.Helper() |
| - done, err := d.start(txn, "withdraw") |
| + return runDrainListed(t, d, txn, []string{}) |
| +} |
| + |
| +// runDrainListed is runDrain with the verb's population. |
| +func runDrainListed(t *testing.T, d *drainDriver, txn string, listed []string) *drainReport { |
| + t.Helper() |
| + done, err := d.start(txn, "withdraw", listed) |
| if err != nil { |
| t.Fatal(err) |
| } |
| @@ -475,7 +481,7 @@ func runDrain(t *testing.T, d *drainDriver, txn string) *drainReport { |
| if r := d.snapshot(); r.Result != "ok" { |
| return r |
| } |
| - done, err = d.start(txn, "move") |
| + done, err = d.start(txn, "move", listed) |
| if err != nil { |
| t.Fatal(err) |
| } |
| @@ -555,7 +561,7 @@ func TestDrainDriverWholeSequence(t *testing.T) { |
| t.Fatal("a successful drain cleared the drain state") |
| } |
| // The move step is answered again as it was. |
| - done, err := d.start("t1", "move") |
| + done, err := d.start("t1", "move", []string{}) |
| if err != nil { |
| t.Fatal(err) |
| } |
| @@ -612,7 +618,7 @@ func TestDrainWaitsForQuiescence(t *testing.T) { |
| if err := d.startWithdrawForTest("t1"); err != nil { |
| t.Fatal(err) |
| } |
| - done, err := d.start("t1", "move") |
| + done, err := d.start("t1", "move", []string{}) |
| if err != nil { |
| t.Fatal(err) |
| } |
| @@ -725,7 +731,7 @@ func TestDrainReleaseLogCatchesEveryUncleanStop(t *testing.T) { |
| if err := d.startWithdrawForTest("t1"); err != nil { |
| t.Fatal(err) |
| } |
| - done, err := d.start("t1", "move") |
| + done, err := d.start("t1", "move", []string{}) |
| if err != nil { |
| t.Fatal(err) |
| } |
| @@ -886,7 +892,7 @@ func TestDrainMissingAcknowledgement(t *testing.T) { |
| if ed.askCount("c draining") < 3 || ed.askCount("b draining") != 1 { |
| t.Fatalf("asks: c %d (want re-asked), b %d (want once)", ed.askCount("c draining"), ed.askCount("b draining")) |
| } |
| - if _, err := d.start("t1", "move"); !errors.Is(err, errDrainStep) { |
| + if _, err := d.start("t1", "move", []string{}); !errors.Is(err, errDrainStep) { |
| t.Fatalf("move after a failed withdraw: %v", err) |
| } |
| // A drained acknowledgement missing fails the move step too, with |
| @@ -902,6 +908,109 @@ func TestDrainMissingAcknowledgement(t *testing.T) { |
| } |
| } |
| +// The drain fails before any move when a filed box cannot answer: a box |
| +// rolled back to an older binary (its capable file left in place) and a |
| +// dead box's leftover file are named; a quiet box that answers is not. |
| +func TestDrainFailsNamingFiledBoxesThatCannotAnswer(t *testing.T) { |
| + defer shorten(&drainAckBound, 120*time.Millisecond)() |
| + defer shorten(&drainAckEvery, 20*time.Millisecond)() |
| + act, ed, marks := healthyDrain() |
| + ed.peers = []string{"gone", "olden", "quiet"} |
| + ed.ack = func(peer string) (bool, error) { |
| + switch peer { |
| + case "olden": |
| + return false, errors.New("ha-drain: olden answered 404") |
| + case "gone": |
| + return false, errors.New("ha-drain: ask gone (127.0.0.14:443): connection refused") |
| + } |
| + return true, nil |
| + } |
| + rep := runDrain(t, newDrainDriver(act, ed, marks, fenceOf("t1")), "t1") |
| + why := strings.Join(rep.Reasons, ";") |
| + if rep.Result != "failed" || rep.Step != "withdraw" || !strings.Contains(why, "olden (ha-drain: olden answered 404)") || |
| + !strings.Contains(why, "gone (") || strings.Contains(why, "quiet") { |
| + t.Fatalf("report %+v", rep) |
| + } |
| + if len(rep.Moved) != 0 || act.endedMoves() != 0 { |
| + t.Fatalf("moved before the acknowledgement: %+v", rep.Moved) |
| + } |
| +} |
| + |
| +// Astra r2 F2.1: the verb's list is the population, whatever the fold |
| +// says. olden is on the list and not in the fold (a failed LIST, every GET |
| +// failing, or no poll since it published, as the edge witnesses show), so |
| +// it is asked, cannot answer, and the drain fails naming it before any |
| +// move. The fold's own boxes are asked too: a box the list omits but the |
| +// fold has is not dropped. |
| +func TestDrainAsksTheVerbsListWhateverTheFoldSays(t *testing.T) { |
| + defer shorten(&drainAckBound, 120*time.Millisecond)() |
| + defer shorten(&drainAckEvery, 20*time.Millisecond)() |
| + act, ed, marks := healthyDrain() |
| + ed.peers = []string{} // the stale fold holds no other box |
| + ed.ack = func(peer string) (bool, error) { |
| + if peer == "olden" { |
| + return false, errors.New("ha-drain: no edges file for olden (fold read: list failed)") |
| + } |
| + return true, nil |
| + } |
| + rep := runDrainListed(t, newDrainDriver(act, ed, marks, fenceOf("t1")), "t1", []string{"olden"}) |
| + if rep.Result != "failed" || rep.Step != "withdraw" || !strings.Contains(strings.Join(rep.Reasons, ";"), "olden (") { |
| + t.Fatalf("report %+v", rep) |
| + } |
| + if ed.askCount("olden draining") == 0 || len(rep.Moved) != 0 || act.endedMoves() != 0 { |
| + t.Fatalf("olden asked %d times, moved %+v", ed.askCount("olden draining"), rep.Moved) |
| + } |
| + // The list omits b and c, which the fold has: both are asked, and both |
| + // phases ask the listed box too. |
| + act, ed, marks = healthyDrain() |
| + rep = runDrainListed(t, newDrainDriver(act, ed, marks, fenceOf("t1")), "t1", []string{"adi"}) |
| + if rep.Result != "ok" || !slices.Equal(rep.Acked, []string{"adi", "b", "c"}) { |
| + t.Fatalf("report %+v", rep) |
| + } |
| + for _, k := range []string{"adi draining", "b draining", "c draining", "adi drained", "b drained", "c drained"} { |
| + if ed.askCount(k) == 0 { |
| + t.Fatalf("%s was not asked", k) |
| + } |
| + } |
| +} |
| + |
| +// Recovery within the bound: olden cannot be asked for two rounds (its file |
| +// not yet readable), then answers; the drain goes on. |
| +func TestDrainListedBoxRecoversWithinTheBound(t *testing.T) { |
| + defer shorten(&drainAckBound, 2*time.Second)() |
| + defer shorten(&drainAckEvery, 20*time.Millisecond)() |
| + act, ed, marks := healthyDrain() |
| + ed.peers = []string{} |
| + var n atomic.Int32 |
| + ed.ack = func(peer string) (bool, error) { |
| + if peer == "olden" && n.Add(1) <= 2 { |
| + return false, errors.New("ha-drain: no edges file for olden") |
| + } |
| + return true, nil |
| + } |
| + rep := runDrainListed(t, newDrainDriver(act, ed, marks, fenceOf("t1")), "t1", []string{"olden"}) |
| + if rep.Result != "ok" || !slices.Equal(rep.Acked, []string{"olden"}) { |
| + t.Fatalf("report %+v", rep) |
| + } |
| +} |
| + |
| +// No list from the verb (an older tool): nothing runs, no move, no state. |
| +func TestDrainWithoutTheVerbsListRefuses(t *testing.T) { |
| + act, ed, marks := healthyDrain() |
| + d := newDrainDriver(act, ed, marks, fenceOf("t1")) |
| + for _, step := range []string{"withdraw", "move"} { |
| + if _, err := d.start("t1", step, nil); !errors.Is(err, errDrainNoPeers) { |
| + t.Fatalf("%s without a list: %v", step, err) |
| + } |
| + } |
| + if _, err := d.start("t1", "withdraw", []string{"a", "a"}); !errors.Is(err, errDrainNoPeers) { |
| + t.Fatalf("a duplicate: %v", err) |
| + } |
| + if begun, _, _ := marks.counts(); len(ed.rec.events()) != 0 || begun != 0 { |
| + t.Fatalf("a refused drain did something: %v", ed.rec.events()) |
| + } |
| +} |
| + |
| // Many peers answering at once (the acknowledgement map is the |
| // coordinator's alone): run under -race. |
| func TestDrainAcknowledgementsConcurrently(t *testing.T) { |
| @@ -956,13 +1065,13 @@ func TestDrainMoveNeedsTheFence(t *testing.T) { |
| if err := d.startWithdrawForTest("t1"); err != nil { |
| t.Fatal(err) |
| } |
| - if _, err := d.start("t1", "move"); !errors.Is(err, errDrainNoFence) { |
| + if _, err := d.start("t1", "move", []string{}); !errors.Is(err, errDrainNoFence) { |
| t.Fatalf("no fence: %v", err) |
| } |
| mu.Lock() |
| f = fenceState{Present: true, Transaction: "other"} |
| mu.Unlock() |
| - if _, err := d.start("t1", "move"); !errors.Is(err, errDrainNoFence) { |
| + if _, err := d.start("t1", "move", []string{}); !errors.Is(err, errDrainNoFence) { |
| t.Fatalf("another fence: %v", err) |
| } |
| mu.Lock() |
| @@ -970,7 +1079,7 @@ func TestDrainMoveNeedsTheFence(t *testing.T) { |
| mu.Unlock() |
| // The fence goes during the moves: the report fails. |
| act.onBeginMove = func(string) { mu.Lock(); f = fenceState{}; mu.Unlock() } |
| - done, err := d.start("t1", "move") |
| + done, err := d.start("t1", "move", []string{}) |
| if err != nil { |
| t.Fatal(err) |
| } |
| @@ -988,7 +1097,7 @@ func TestDrainOneTransaction(t *testing.T) { |
| if err := d.startWithdrawForTest("t1"); err != nil { |
| t.Fatal(err) |
| } |
| - if _, err := d.start("t2", "withdraw"); !errors.Is(err, errDrainOtherTxn) { |
| + if _, err := d.start("t2", "withdraw", []string{}); !errors.Is(err, errDrainOtherTxn) { |
| t.Fatalf("t2: %v", err) |
| } |
| if err := d.cancel(context.Background(), "t2"); !errors.Is(err, errDrainOtherTxn) { |
| @@ -997,7 +1106,7 @@ func TestDrainOneTransaction(t *testing.T) { |
| d.mu.Lock() |
| d.cancelling = true |
| d.mu.Unlock() |
| - if _, err := d.start("t1", "withdraw"); !errors.Is(err, errDrainCancel) { |
| + if _, err := d.start("t1", "withdraw", []string{}); !errors.Is(err, errDrainCancel) { |
| t.Fatalf("start during a cancel: %v", err) |
| } |
| d.mu.Lock() |
| @@ -1056,7 +1165,7 @@ func TestDrainAgentRestartVoidsTheReport(t *testing.T) { |
| if s.Incarnation == rep.Incarnation || s.Transaction != "" || s.Result != "none" || restarted.snapshot() != nil { |
| t.Fatalf("after a restart: %+v (report incarnation %s)", s, rep.Incarnation) |
| } |
| - if _, err := restarted.start("t1", "move"); !errors.Is(err, errDrainStep) { |
| + if _, err := restarted.start("t1", "move", []string{}); !errors.Is(err, errDrainStep) { |
| t.Fatalf("move on a restarted agent: %v", err) |
| } |
| } |
diff --git a/internal/host/hadrainfence_linux_test.go b/internal/host/hadrainfence_linux_test.go| index db71a364f..02f4e58f3 100644 |
| --- a/internal/host/hadrainfence_linux_test.go |
| +++ b/internal/host/hadrainfence_linux_test.go |
| @@ -269,6 +269,9 @@ func verbDrain(t *testing.T, d *drainDriver) (*groupMaintenanceCommand, fenceLoc |
| drainSocketPaths.Store(cmd, path) |
| t.Cleanup(func() { drainSocketPaths.Delete(cmd) }) |
| cmd.txn = "" |
| + // The verb always names its population; these fixtures' boxes come |
| + // from the fake fold. |
| + cmd.peers = []string{} |
| return cmd, l |
| } |
| @@ -405,6 +408,33 @@ func TestDrainVerbFailures(t *testing.T) { |
| } |
| } |
| +// A drain verb run with no --peers (an older operator tool) refuses before |
| +// anything moves: the agent answers errDrainNoPeers, and no fence is |
| +// installed. A malformed list never reaches the agent's driver. |
| +func TestDrainVerbWithoutPeersRefuses(t *testing.T) { |
| + act, ed, marks := healthyDrain() |
| + d := newDrainDriver(act, ed, marks, nil) |
| + cmd, l := verbDrain(t, d) |
| + d.fence = l.read |
| + cmd.peers = nil |
| + _, err := runDrainVerb(t, cmd, "drain", "t1") |
| + if err == nil || !strings.Contains(err.Error(), errDrainNoPeers.Error()) || l.read().Present { |
| + t.Fatalf("no list: %v fence %+v", err, l.read()) |
| + } |
| + if begun, _, _ := marks.counts(); begun != 0 || act.endedMoves() != 0 { |
| + t.Fatalf("a refused drain began: %d", begun) |
| + } |
| + // The socket refuses a malformed list outright. |
| + path := socketPathOf(t, cmd) |
| + bad := []string{"a", "a"} |
| + r, err := socketDrainCall(newDrainClient(path))(context.Background(), "withdraw", "t1", bad) |
| + if err != nil || r.err() == nil || begunOf(marks) != 0 { |
| + t.Fatalf("a duplicate list: %+v %v", r, err) |
| + } |
| +} |
| + |
| +func begunOf(m *fakeMarks) int { b, _, _ := m.counts(); return b } |
| + |
| func TestDrainVerbArguments(t *testing.T) { |
| for _, tc := range []struct { |
| args []string |
| @@ -412,6 +442,11 @@ func TestDrainVerbArguments(t *testing.T) { |
| shouldFail bool |
| }{ |
| {[]string{"drain", "t1"}, "drain", "t1", false}, |
| + {[]string{"drain", "--peers=adi,g-0123456789abcdef0123", "t1"}, "drain", "t1", false}, |
| + {[]string{"drain", "--peers=", "t1"}, "drain", "t1", false}, |
| + {[]string{"drain", "--peers=adi,adi", "t1"}, "", "", true}, |
| + {[]string{"drain", "--peers=a;b", "t1"}, "", "", true}, |
| + {[]string{"drain", "--peers=adi"}, "", "", true}, |
| {[]string{"drain", "--cancel", "t1"}, "drain-cancel", "t1", false}, |
| {[]string{"fence-clear", "t1"}, "fence-clear", "t1", false}, |
| {[]string{"drain"}, "", "", true}, |
diff --git a/internal/host/testdata/edges-p2b-golden.json b/internal/host/testdata/edges-p2b-golden.json| index 20d9c3248..dbfbb96a7 100644 |
| --- a/internal/host/testdata/edges-p2b-golden.json |
| +++ b/internal/host/testdata/edges-p2b-golden.json |
| @@ -1 +1 @@ |
| -{"box_role":"serve","admitted":true,"drained":false,"v":1,"box":"leo","eip":"203.0.113.10","region":"eu-west-1","data_bucket":"test-data","data_bucket_region":"eu-west-1","hibernation_configured":true,"serves_shared_pool":false,"accepts_inbound":true,"named_pools":["cohort1","hapair"],"burst_notices":true,"ha_take":1,"secrets_key_fp":"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","box_id":"leo","capabilities":["region-ha-1","names-2"],"headroom":{"mem_free_mib":512,"disk_free_mib":2048,"awake":0,"mem_total_mib":1024,"disk_total_mib":4096},"moves_protocol":0,"seeds_protocol":0,"addrs":null,"generation":"2026-11-04T12:00:00Z","hosts":{"app.example.com":{"role":"home","platform":false}}} |
| \ No newline at end of file |
| +{"box_role":"serve","admitted":true,"drained":false,"v":1,"box":"leo","eip":"203.0.113.10","region":"eu-west-1","data_bucket":"test-data","data_bucket_region":"eu-west-1","hibernation_configured":true,"serves_shared_pool":false,"accepts_inbound":true,"named_pools":["cohort1","hapair"],"burst_notices":true,"ha_take":1,"ha_handover":1,"secrets_key_fp":"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","box_id":"leo","capabilities":["region-ha-1","names-2"],"headroom":{"mem_free_mib":512,"disk_free_mib":2048,"awake":0,"mem_total_mib":1024,"disk_total_mib":4096},"moves_protocol":0,"seeds_protocol":0,"addrs":null,"generation":"2026-11-04T12:00:00Z","hosts":{"app.example.com":{"role":"home","platform":false}}} |
| \ No newline at end of file |
diff --git a/internal/provision/testdata/plan14-root-reads-chain.tsv b/internal/provision/testdata/plan14-root-reads-chain.tsv| index 18c8161d9..32b36c4fa 100644 |
| --- a/internal/provision/testdata/plan14-root-reads-chain.tsv |
| +++ b/internal/provision/testdata/plan14-root-reads-chain.tsv |
| @@ -156,3 +156,4 @@ plan14-root-reads-deploy-happy-path.tsv a9ae6b238b6b2e177be1f9c7ae06ea0f24477e4e |
| plan14-root-reads-held-move-speed.tsv 837f27a6b7b6ed272f8c68aca07650fa32cf3ec92ce28bf9d812a4282eeb0b58 |
| plan14-root-reads-litestream-quiet-802.tsv 6d3ea7fccce1a7f4bc507b6eb8d368ed0b62f83022504aa04c7684c72c93aa9a |
| plan14-root-reads-group-roll-dr4-lock-refusal.tsv 6d3ea7fccce1a7f4bc507b6eb8d368ed0b62f83022504aa04c7684c72c93aa9a |
| +plan14-root-reads-held-floor-capability.tsv b60c83f8ba4311222174284420b5327e92002882b4a1c6f291e74e69234c6f59 |
diff --git a/internal/provision/testdata/plan14-root-reads-held-floor-capability.tsv b/internal/provision/testdata/plan14-root-reads-held-floor-capability.tsv| new file mode 100644 |
| index 000000000..1c8e6c033 |
| --- /dev/null |
| +++ b/internal/provision/testdata/plan14-root-reads-held-floor-capability.tsv |
| @@ -0,0 +1,20 @@ |
| +# Census overlay held-floor-capability, written by census-propose (#369). census-ruling-held-floor-capability, approved on #280 before the merge; the approval card is docs/superpowers/notes/census-proposal-held-floor-capability.md. |
| +# 6 body, 0 sites, 4 envelope: each changed unit re-frozen at its existing disposition with its claim appended. |
| +# 1 new dispositions: 0 reads re-frozen at their disposition with the claim, 1 new units frozen accepted-legacy, 0 quiet units retired while they read nothing, 0 other. |
| +@legacy bc4b8ee15c32b3bbcf3d4d4bc53415821d5c0c751b089840e6b940e6fe66bf6e infra/modules/region-group-operator-document/tool-pattern.txt external legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p3b2-ops;basis=new: Branch T grammar admitting only region-group-roll.py remote_command forms (status/prepare/permit/revoke/apply/rollback);rev3=census-ruling-region-ha-held-build;basis=region HA held-requests Task 6 fix 1: Branch T admits exactly the tool forms status, revoke, prepare --sha256 SHA, permit && status, apply and rollback (900 s), plus the planned-handover forms "timeout --signal=TERM --kill-after=30s 3600s ... group-maintenance drain TX", "timeout --signal=TERM --kill-after=30s 300s ... group-maintenance drain --cancel TX && ... status", "... group-maintenance fence-clear TX && ... status" and "timeout --signal=TERM --kill-after=10s 120s /usr/bin/systemctl stop carlos-edge.service; /usr/bin/systemctl show --property=MainPID --property=ActiveState carlos-edge.service", where TX is [A-Za-z0-9_][A-Za-z0-9_-]{0,79}; nothing else;rev3=census-ruling-held-floor-capability;basis=held floor capability (Astra r2 F2.1): the drain alternative of the operator document's allowedPattern becomes `group-maintenance drain --peers=[A-Za-z0-9._,-]* <transaction>`: the verb's acknowledgement list, shell-safe characters only (no space, quote, semicolon or dollar), validated again by root's maintenanceArguments. Every other alternative is unchanged. Needs the document redeployed before a verb on this build can drain. file:external@0 b922ea7dad60357ec66e3b572a0033db6c21e9ed348e15f469ce21214fee1ea9 |
| +@legacy 6a8aa49b5c230210f04c48d0c252fff803557d6dce3e1e7e345087a7492e97fa internal/edge/hadrain.go Edge.serveHAControl legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-held-build;basis=new: answers a signed drain ask. Reads the request body (io.ReadAll under MaxBytesReader 4 KiB and a 2 s read deadline), verifies its own mesh-key MAC, requires a phase (draining or drained) and a nonzero publication id, and may refresh the edges fold (the existing refreshHosts: LIST plus GET of control/edges/ in the deployment bucket); reads no local file; answers JSON seen true or false, or a bare 404. Fix round 1: the ask names phase and publication id instead of a generation. held-requests Task 4: accepts POST /.carlos/ha-take beside /.carlos/ha-drain, with the same bounded body read; the signature is verified over the request's own path (one of the two reserved constants), then a take goes to serveHATake (strict JSON with transaction, asker, host, lifetime and a positive marker generation, else a bare 404); no read added here;rev3=census-ruling-held-floor-capability;basis=held floor capability (region HA §25.4 step 1, agent manager 8a3d302, 2026-11-10): a drain ask must also carry a nonce of 32 lower-case hex digits (else a bare 404, like any other malformed ask), and the JSON answer gains sig, an HMAC-SHA256 under the same mesh key (signingKey of the mirrored pair) over a distinct domain, this box, the asker, the transaction, the phase, the publication id, the nonce and the seen value. Computed in memory from the already verified ask; no read added, no file, record or store access added; the take path is unchanged. file:ReadAll@703 5085c6761663c54fbb90687e3ac2f1f1314c82e25352325e08dbed91f532523e |
| +@legacy fa5fc7a9bef579861e3338b4f71c9483866bda98d412b703a9acbb948c11cdf1 internal/host/hadrain.go drainDriver.moveSteps legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-held-build;basis=new (split from move): drain steps 2-5 over the activator and edge APIs; reads route Host from the activator's in-memory DrainHosts; releases and moves under one 4-way semaphore; no store or file read of its own;rev3=census-ruling-held-floor-capability;basis=held floor capability (Astra r2 F2.1): takes the verb's acknowledgement list (listed) and passes it to the drained-phase publishAndAck, which asks every listed box plus any the fold adds; nothing else changes. No read added; in-memory only. registry:Host@987,whole:Route@989 510582ac2a15ae55282bf2866b45a874d6ee8a147fa40ca3727d4cd95594bc0b |
| +@legacy eb8fbcf4118b191a68a62b86c8be452726800ebb361d27a44b194661e8f138a6 internal/host/hadrain_call_linux.go drainCallExec legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-held-build;basis=new (branch review r1, Astra B1.3): builds the __drain-call child command: the pinned executable /proc/self/fd/3 (registryExecutable, as the registry child), fixed arguments (op from a fixed set, the validated transaction), empty environment, Dir "/", no stdin; the child drops to the agent user before it dials the agent socket; root reads only its bounded stdout (drainCallMax);rev3=census-ruling-held-floor-capability;basis=held floor capability (Astra r2 F2.1): root's drain-call child command gains a third argument for withdraw and move, --peers=<refs joined by commas>, when root was given a list; execDrainCall refuses a list that is not valid (validDrainPeers: at most 256 references in the edges-key grammar [A-Za-z0-9][A-Za-z0-9._-]{0,127}, no duplicates) before any child starts. Same pinned executable, empty environment, "/" directory, no stdin; the child still drops to the agent user before reading anything. No read added. file:Command@158 d1f15ed19e3837e3da1b3a703c437b7f097db7eb22bcea09f7236b3c703e2267 |
| +@legacy 849593102156dd3d4e0a54f841df3f7ce640649fe534b18bb32c8dffb3e88bbc internal/host/hadrain_socket.go drainDriver.handler legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-held-build;basis=new: agent drain socket handler: reads the request body bounded to 4 KiB, strict JSON with one transaction field; served only to a peer SO_PEERCRED reports as root; not a file read;rev3=census-ruling-held-floor-capability;basis=held floor capability (Astra r2 F2.1): the agent's drain socket accepts an optional peers array on withdraw and move (strict JSON, unknown fields still refused; a peers field on cancel, or an invalid list, is a 400), the body bound rises from 4 KiB to 64 KiB for up to 256 references, and the list goes to drainDriver.start, which refuses a step without a valid list (errDrainNoPeers) before anything runs. Peer-credential check unchanged; no file or store read added. file:ReadAll@722 7224fbfc2069ff2b7216c9c14a33f7886b4a79cb0a687bdd3ea1d144f6c2e01d |
| +@legacy e3fece4d48f4bceb8a18c12bec66d693a72dec53d0d35d04bebee1dda9d703d2 internal/edge/hadrain.go Edge.AskDrainSeen legacy accepted-legacy accepted-legacy;rev3=census-ruling-held-floor-capability;basis=held floor capability (region HA §25.4 step 1, agent manager 8a3d302, 2026-11-10): the ask gains a nonce, 16 bytes from crypto/rand in lower-case hex, inside the already signed body; the answer must carry sig, an HMAC-SHA256 under either mirrored mesh key over a distinct domain, the peer, this box, the transaction, the phase, the id, that nonce and the seen value, verified in constant time; an unsigned, wrongly signed or other-ask answer is an error (not acknowledged), never seen. Astra r2 F2.1: when the peer (from the verb's list) has no edges file in this edge's fold, it runs the existing refreshHostsNow once (the receivers' own fold read on an ask: a LIST and GETs of control/edges/ in the deployment bucket, as the agent user, bounded by haDrainRefreshTimeout) and retries controlTarget; still absent, the ask fails naming the peer. No new read kind, path or record; a drain only fails more often, never proceeds on less. file:Read@1398 7f634d395f69292d2fbb6012a65f2cec0e04ae053943052c4ff17e1249f2bd1b |
| +infra/modules/region-group-operator-document/tool-pattern.txt external legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p3b2-ops;basis=new: Branch T grammar admitting only region-group-roll.py remote_command forms (status/prepare/permit/revoke/apply/rollback);rev3=census-ruling-region-ha-held-build;basis=region HA held-requests Task 6 fix 1: Branch T admits exactly the tool forms status, revoke, prepare --sha256 SHA, permit && status, apply and rollback (900 s), plus the planned-handover forms "timeout --signal=TERM --kill-after=30s 3600s ... group-maintenance drain TX", "timeout --signal=TERM --kill-after=30s 300s ... group-maintenance drain --cancel TX && ... status", "... group-maintenance fence-clear TX && ... status" and "timeout --signal=TERM --kill-after=10s 120s /usr/bin/systemctl stop carlos-edge.service; /usr/bin/systemctl show --property=MainPID --property=ActiveState carlos-edge.service", where TX is [A-Za-z0-9_][A-Za-z0-9_-]{0,79}; nothing else;rev3=census-ruling-held-floor-capability;basis=held floor capability (Astra r2 F2.1): the drain alternative of the operator document's allowedPattern becomes `group-maintenance drain --peers=[A-Za-z0-9._,-]* <transaction>`: the verb's acknowledgement list, shell-safe characters only (no space, quote, semicolon or dollar), validated again by root's maintenanceArguments. Every other alternative is unchanged. Needs the document redeployed before a verb on this build can drain. file:external@0 b922ea7dad60357ec66e3b572a0033db6c21e9ed348e15f469ce21214fee1ea9 |
| +internal/edge/hadrain.go Edge.serveHAControl legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-held-build;basis=new: answers a signed drain ask. Reads the request body (io.ReadAll under MaxBytesReader 4 KiB and a 2 s read deadline), verifies its own mesh-key MAC, requires a phase (draining or drained) and a nonzero publication id, and may refresh the edges fold (the existing refreshHosts: LIST plus GET of control/edges/ in the deployment bucket); reads no local file; answers JSON seen true or false, or a bare 404. Fix round 1: the ask names phase and publication id instead of a generation. held-requests Task 4: accepts POST /.carlos/ha-take beside /.carlos/ha-drain, with the same bounded body read; the signature is verified over the request's own path (one of the two reserved constants), then a take goes to serveHATake (strict JSON with transaction, asker, host, lifetime and a positive marker generation, else a bare 404); no read added here;rev3=census-ruling-held-floor-capability;basis=held floor capability (region HA §25.4 step 1, agent manager 8a3d302, 2026-11-10): a drain ask must also carry a nonce of 32 lower-case hex digits (else a bare 404, like any other malformed ask), and the JSON answer gains sig, an HMAC-SHA256 under the same mesh key (signingKey of the mirrored pair) over a distinct domain, this box, the asker, the transaction, the phase, the publication id, the nonce and the seen value. Computed in memory from the already verified ask; no read added, no file, record or store access added; the take path is unchanged. file:ReadAll@703 5085c6761663c54fbb90687e3ac2f1f1314c82e25352325e08dbed91f532523e |
| +internal/host/edgesfile.go edgesFileWriteClaims authority F,J1 rev3=census-ruling-self-serve-moves-1;basis=root-route;kept=F;scope=protected-decision-only; the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): region-ha-2a's body, which with the box's lifetimes switch on also publishes each served row's lifetime pair (registry:Incarnation and registry:ServingSeq, two new sites on the rows it already lists) and an alias's or served catch-all's primary's pair, and names that primary as target_host whatever the switch; a report the edge orders unstamped entries by, not a decision; no record, /data, release or claim read added; F,J1 authority retained; self-serve moves 1 Task 8;rev3=census-ruling-instance-egress-sizes-328-329;basis=#328 plan 2 Task 8: takes a localAddrs reader (instancectl.LocalAddresses in production, which reads /proc/net/fib_trie and /proc/net/if_inet6 in the agent) and publishes its non-loopback entries as the edges file's addrs before the write gate (boxAddrs, no read of its own), so an address change writes once. The same 44 sites, offsets moved; no record, /data, release or claim read added; a report the console's egress grant check reads, not a root decision; F,J1 authority retained.;rev3=census-ruling-edge-asset-cache-3;basis=starts with assets = assets.active(), so a policy whose box has not opened its asset store publishes no assets blocks and reads no manifests, and copies the decision's Primary (the route host the block was decided for, drift D4) into the published assets block; read sites unchanged (44); no read added. Merged onto main's #328 body, which takes the localAddrs reader: the assets.active() line sits after that signature and the loop passes pub and instancectl.LocalAddresses;rev3=census-ruling-region-ha-p1a;basis=the agent as carlos: the claims argument (*edgesClaims) becomes addrs (AddressSource) and the applyEdgesClaims(ctx, claims, routes, hosts) call is deleted with edgesclaims.go, which is the one whole:Route site removed: no host claim is read and every served row publishes as with region HA off; the box-address publication is the same code reading addrs.BoxAddresses() instead of claims.addrs; a report the edge reads, not a root decision; no read added; merge of origin/main d7ae1d76: main's edge asset cache plan 3 body is kept (census-ruling-edge-asset-cache-3): the first line is assets = assets.active(), so a policy whose store has not opened publishes no assets blocks and reads no manifests, and edgesFileLoop passes pub (assets.active() for that tick) in the assets argument; main's claims *edgesClaims argument is this branch's addrs AddressSource, and no edgesClaims, applyEdgesClaims or hostclaim reference remains;rev3=census-ruling-alias-wake-338;basis=#338 follow-up: skips publishing a platform alias edge.PlatformAliasFold refuses (and so anything attached to it); reads the same route listing;rev3=census-ruling-fleet-public-routes;basis=fleet public routes (spec 2026-10-29 rev 4, §4.2 writer rule): Task 6 and its fix rounds: publishes by FleetArmVerdict (via fleetRefusedFor): withheld rows left out; a forward host's path rows left out of its owner; no assets for forward rows; the alias loop replays Reload's alias fold from the served rows so a chained alias carries its root primary's owner; certRefused and parentRefused leave out a refused claim's wildcard parent (+registry:Alias x5, +registry:Host x4, +whole:Route, +whole:RouteAlias x2, +whole:RoutePath x7, +whole:WildcardDomain). Rows already read in the pass; keeps authority F,J1; publishes less, never more.;rev3=census-ruling-probe-burst-limit;basis=sets the constant BurstNotices=true on the box's own edges file (this build's edge answers probe-burst notices, so peers may send them); not from config or any read; the same 65 sites; a report other edges read, not a root decision; F,J1 authority retained; no new root read or write kind;rev3=census-ruling-region-ha-p3a;basis=Publish one injected role snapshot with box_role/admitted/drained; retain legacy route and alias rows during booting, cutting namespace withdrawal under the 2026-11-04 ruling; acknowledge the exact published tuple only after PUT; existing registry reads unchanged.;rev3=census-ruling-region-ha-p2b;basis=region HA P2b-1 T0 (Q1 ruling): before building the comparison copy and the body, a nil NamedPools on the identity becomes []string{} so the additive named_pools field is always an explicit array; the list itself is computed once at arm by edgesFileEligibility from the same provisionTickConfig(os.Getenv) parse as serves_shared_pool (CARLOS_POOLS through provision.ParseBoxPools, filtered to nonempty provision.ValidPool names, sorted, unique). A report the console reads for create admission, not a root decision; no record, /data, release or claim read added; read sites unchanged (65); F,J1 authority retained. One-off cost: the first pass after the upgrade writes once per box (seeded gate null vs []).;rev3=census-ruling-region-ha-p3b;basis=Require cached GroupReadersReady before first group publication and append additive names-2 capability even for supplied identities. Agent writes the same edges object/index with existing registry reads; known readers come from root boot configuration, snapshot from existing fold, no added GET/LIST or root authority.;rev3=census-ruling-region-ha-g2-fixes;basis=Omit non-forward, non-platform-alias rows outside local served pools from home publication; added Host/Pool field reads and local configuration use, existing registry/store operations retained.;rev3=census-ruling-edge-page-cache-1;basis=prunes the manifest cache through the new atomic pointer (assets.manifests.Load().prune(...), nil-safe); nothing else changes; read sites unchanged (67); no read added;rev3=census-ruling-region-ha-held-build;basis=writes also when DrainPublishRequired, and reports the written drain state, its ha_drain mark (transaction and publication id) and generation to DrainSource (in-memory); the file gains ha_drained and ha_drain beside the existing draining; no read added. held-requests Task 4: sets the constant ha_take=1 on the box's own file when its in-memory capabilities include region-ha-1 (this build's edge answers take requests); not from config or any read; a report other edges read, not a root decision; no read added;rev3=census-ruling-warm-set-published-724;basis=#724: the agent as carlos: reads PLATFORM_APPS_DOMAIN from the environment once per pass (the variable domainsLoop already reads) and sets an additive dns_pointing mark on each published custom name through dnsPointingMark: true on a published alias (registry:Alias, already published only when its dns_status is pointing), and on a route with a hostname outside the apps domain whether its registry:DNSStatus is pointing (registry:Host, registry:DNSStatus on rows the pass already lists). No mark under the apps domain, on a wildcard row, or with no apps domain set. A report the issuer cert warm reads to leave a not-yet-pointing custom name out of its set, not a root decision; it publishes the same names as before. No record, /data, release or claim read added; no new registry query; F,J1 authority retained. One-off cost: the first pass after the upgrade writes once on a box homing a custom name.;rev3=census-ruling-held-floor-capability;basis=held floor capability (region HA §25.9, agent manager 8a3d302, 2026-11-10): sets the constant ha_handover=1 on the box's own edges file on every pass, whatever its capabilities (this build understands the held-requests headers and the drain acknowledgement); the group roll floor reads it. Not from config or any read; ha_take unchanged; a report other tools read, not a root decision; no read added; F,J1 authority retained. One-off cost: the first pass after the upgrade writes once per box. registry:Account@16743,registry:Alias@10183,registry:Alias@10340,registry:Alias@10410,registry:Alias@10442,registry:Alias@11186,registry:Alias@11396,registry:Alias@14216,registry:Alias@14266,registry:Alias@9544,registry:Alias@9563,registry:Alias@9662,registry:Alias@9716,registry:Alias@9751,registry:Alias@9813,registry:App@16755,registry:DNSStatus@10349,registry:DNSStatus@5731,registry:DNSStatus@9858,registry:Host@14119,registry:Host@14139,registry:Host@14404,registry:Host@14484,registry:Host@14519,registry:Host@14568,registry:Host@15030,registry:Host@15065,registry:Host@16173,registry:Host@4188,registry:Host@4279,registry:Host@4325,registry:Host@4384,registry:Host@5723,registry:Host@5970,registry:Host@6940,registry:Host@9589,registry:Host@9637,registry:Incarnation@5930,registry:Platform@5238,registry:Pool@4239,registry:Provisioned@5252,registry:Replica@5276,registry:ServingSeq@5945,registry:Status@2957,whole:Route@1026,whole:Route@18213,whole:Route@1841,whole:Route@19038,whole:Route@19213,whole:Route@2327,whole:Route@7025,whole:Route@750,whole:RouteAlias@14170,whole:RouteAlias@18235,whole:RouteAlias@19228,whole:RouteAlias@9427,whole:RouteAlias@9509,whole:RouteAlias@9701,whole:RoutePath@18228,whole:RoutePath@19221,whole:RoutePath@6809,whole:RoutePath@6841,whole:RoutePath@6888,whole:RoutePath@6916,whole:RoutePath@6954,whole:RoutePath@6974,whole:RoutePath@6986,whole:RoutePath@7040,whole:WildcardDomain@14097,whole:WildcardDomain@14473 3f2f6d92db4a60e2931eb80fc0f0d94fba9a75172a36aa03dcda890f2134f681 |
| +internal/host/hadrain.go drainDriver.moveSteps legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-held-build;basis=new (split from move): drain steps 2-5 over the activator and edge APIs; reads route Host from the activator's in-memory DrainHosts; releases and moves under one 4-way semaphore; no store or file read of its own;rev3=census-ruling-held-floor-capability;basis=held floor capability (Astra r2 F2.1): takes the verb's acknowledgement list (listed) and passes it to the drained-phase publishAndAck, which asks every listed box plus any the fold adds; nothing else changes. No read added; in-memory only. registry:Host@987,whole:Route@989 510582ac2a15ae55282bf2866b45a874d6ee8a147fa40ca3727d4cd95594bc0b |
| +internal/host/hadrain_call_linux.go drainCallExec legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-held-build;basis=new (branch review r1, Astra B1.3): builds the __drain-call child command: the pinned executable /proc/self/fd/3 (registryExecutable, as the registry child), fixed arguments (op from a fixed set, the validated transaction), empty environment, Dir "/", no stdin; the child drops to the agent user before it dials the agent socket; root reads only its bounded stdout (drainCallMax);rev3=census-ruling-held-floor-capability;basis=held floor capability (Astra r2 F2.1): root's drain-call child command gains a third argument for withdraw and move, --peers=<refs joined by commas>, when root was given a list; execDrainCall refuses a list that is not valid (validDrainPeers: at most 256 references in the edges-key grammar [A-Za-z0-9][A-Za-z0-9._-]{0,127}, no duplicates) before any child starts. Same pinned executable, empty environment, "/" directory, no stdin; the child still drops to the agent user before reading anything. No read added. file:Command@158 d1f15ed19e3837e3da1b3a703c437b7f097db7eb22bcea09f7236b3c703e2267 |
| +internal/host/hadrain_socket.go drainDriver.handler legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-held-build;basis=new: agent drain socket handler: reads the request body bounded to 4 KiB, strict JSON with one transaction field; served only to a peer SO_PEERCRED reports as root; not a file read;rev3=census-ruling-held-floor-capability;basis=held floor capability (Astra r2 F2.1): the agent's drain socket accepts an optional peers array on withdraw and move (strict JSON, unknown fields still refused; a peers field on cancel, or an invalid list, is a 400), the body bound rises from 4 KiB to 64 KiB for up to 256 references, and the list goes to drainDriver.start, which refuses a step without a valid list (errDrainNoPeers) before anything runs. Peer-credential check unchanged; no file or store read added. file:ReadAll@722 7224fbfc2069ff2b7216c9c14a33f7886b4a79cb0a687bdd3ea1d144f6c2e01d |
| +internal/edge/hadrain.go Edge.AskDrainSeen legacy accepted-legacy accepted-legacy;rev3=census-ruling-held-floor-capability;basis=held floor capability (region HA §25.4 step 1, agent manager 8a3d302, 2026-11-10): the ask gains a nonce, 16 bytes from crypto/rand in lower-case hex, inside the already signed body; the answer must carry sig, an HMAC-SHA256 under either mirrored mesh key over a distinct domain, the peer, this box, the transaction, the phase, the id, that nonce and the seen value, verified in constant time; an unsigned, wrongly signed or other-ask answer is an error (not acknowledged), never seen. Astra r2 F2.1: when the peer (from the verb's list) has no edges file in this edge's fold, it runs the existing refreshHostsNow once (the receivers' own fold read on an ask: a LIST and GETs of control/edges/ in the deployment bucket, as the agent user, bounded by haDrainRefreshTimeout) and retries controlTarget; still absent, the ask fails naming the peer. No new read kind, path or record; a drain only fails more often, never proceeds on less. file:Read@1398 7f634d395f69292d2fbb6012a65f2cec0e04ae053943052c4ff17e1249f2bd1b |
| +@coverage infra/modules/region-group-operator-document bc02dd037f5f04854964d89efcfdb72a5b10221303e346c61e62e7f85a2f0494 |
| +@coverage internal/edge 9c3f3a915e490691be4eb79789067ed1e160f5009990f70b94189c6e04ed7fb4 |
| +@coverage internal/grouproll 9a567994d5e6197e84024b628e9556e09a021a04a1644a5d6e1f97912c1f93b4 |
| +@coverage internal/host 00baab19b9ed34b246421999024d672cadad9dfbd4a760e7a596b1de6fd00686 |
diff --git a/scripts/region-group-roll.py b/scripts/region-group-roll.py| index fbeef8f24..76a8627d7 100755 |
| --- a/scripts/region-group-roll.py |
| +++ b/scripts/region-group-roll.py |
| @@ -6,6 +6,7 @@ |
| # replacement can later pass without its own readiness and ha_take check; |
| # (2) after the terminate check, a desired or minimum below N is raised again, |
| # so an outside capacity reduction after the restore launches capacity. |
| +# Its floor is also stale: the Go verb counts every edges file by ha_handover, no age test. |
| """Attended, serialized maintenance of one Auto Scaling group member. |
| Run as root on the shared operator host. All operators must use the same |
diff --git a/scripts/region_group_document_test.py b/scripts/region_group_document_test.py| index 8cf4ea76e..b8349558d 100644 |
| --- a/scripts/region_group_document_test.py |
| +++ b/scripts/region_group_document_test.py |
| @@ -61,6 +61,27 @@ def tearDownModule(): |
| _go_builder.stop() |
| +PEERS = "--peers=adi,g-0123456789abcdef0,box.b_1" |
| + |
| + |
| +def with_peers(command, peers=None): |
| + """The group verb's drain: the plain drain command with its acknowledgement list.""" |
| + flag = PEERS if peers is None else "--peers=" + peers |
| + out = command.replace("group-maintenance drain ", "group-maintenance drain " + flag + " ", 1) |
| + assert out != command |
| + return out |
| + |
| + |
| +def drain_command(transaction, peers=None): |
| + """A drain with its acknowledgement list, from whichever builder is under test. |
| + The Go builder takes the list itself; the script has none, so it is added.""" |
| + if GO_REMOTE_COMMAND: |
| + listed = PEERS[len("--peers="):] if peers is None else peers |
| + return go_remote_command(dict(verb="drain", transaction=transaction, |
| + peers=listed.split(",") if listed else []), NONCE) |
| + return with_peers(frames.roll.AWS.remote_command(dict(verb="drain", transaction=transaction), NONCE), peers) |
| + |
| + |
| class DocumentPatternTests(unittest.TestCase): |
| def setUp(self): |
| self.tool = pattern() |
| @@ -86,30 +107,52 @@ class DocumentPatternTests(unittest.TestCase): |
| self.assertAccepted(command, harness=True) |
| def test_planned_handover_forms(self): |
| - # Region HA section 25: drain, fence-clear and the edge stop the roll |
| - # tool sends for replace, remove and the drained roll. |
| + # Region HA section 25: drain, fence-clear and the edge stop the group |
| + # verb sends for replace, remove and the drained roll. The drain now |
| + # carries the verb's acknowledgement list (--peers=, held-floor-capability); |
| + # the superseded script's plain "drain <txn>" is refused by the document, |
| + # as a member on this release would refuse it without a list. |
| for transaction in ("a", "t6_held-1", "A_9-" * 20): |
| for verb in ("drain", "drain-cancel", "fence-clear"): |
| - command = frames.roll.AWS.remote_command(dict(verb=verb, transaction=transaction), NONCE) |
| with self.subTest(verb=verb, transaction=transaction): |
| + if verb == "drain": |
| + if GO_REMOTE_COMMAND: |
| + # The Go builder refuses a drain without its list. |
| + with self.assertRaises(frames.roll.Refusal): |
| + frames.roll.AWS.remote_command(dict(verb=verb, transaction=transaction), NONCE) |
| + else: |
| + plain = frames.roll.AWS.remote_command(dict(verb=verb, transaction=transaction), NONCE) |
| + self.assertRefused(plain) |
| + self.assertRefused(plain, harness=True) |
| + command = drain_command(transaction) |
| + else: |
| + command = frames.roll.AWS.remote_command(dict(verb=verb, transaction=transaction), NONCE) |
| self.assertAccepted(command) |
| self.assertAccepted(command, harness=True) |
| self.assertAccepted(frames.roll.AWS.remote_command({"verb": "edge-stop"}, NONCE)) |
| - drain = frames.roll.AWS.remote_command(dict(verb="drain", transaction="t6"), NONCE) |
| + drain = drain_command("t6") |
| + self.assertAccepted(drain_command("t6", "")) |
| + D = PEERS + " t6" |
| clear = frames.roll.AWS.remote_command(dict(verb="fence-clear", transaction="t6"), NONCE) |
| cancel = frames.roll.AWS.remote_command(dict(verb="drain-cancel", transaction="t6"), NONCE) |
| stop = frames.roll.AWS.remote_command({"verb": "edge-stop"}, NONCE) |
| bad = { |
| - "leading dash": drain.replace("drain t6", "drain -t6"), |
| + "leading dash": drain.replace(D, PEERS + " -t6"), |
| "cancel without bound": drain.replace( |
| - "/usr/bin/timeout --signal=TERM --kill-after=30s 3600s /opt/carlos/carlos system group-maintenance drain t6", |
| + "/usr/bin/timeout --signal=TERM --kill-after=30s 3600s /opt/carlos/carlos system group-maintenance drain " + D, |
| "/opt/carlos/carlos system group-maintenance drain --cancel t6 && " + STATUS), |
| - "cancel under the drain bound": drain.replace("drain t6", "drain --cancel t6 && " + STATUS), |
| + "cancel under the drain bound": drain.replace(D, "--cancel t6 && " + STATUS), |
| "cancel without status": cancel.replace(" && " + STATUS, ""), |
| "cancel dash": cancel.replace("--cancel t6", "--cancel -t6"), |
| "cancel two transactions": cancel.replace("--cancel t6", "--cancel t6 t7"), |
| - "two transactions": drain.replace("drain t6", "drain t6 t7"), |
| - "long transaction": drain.replace("drain t6", "drain " + "a" * 81), |
| + "two transactions": drain.replace(D, D + " t7"), |
| + "long transaction": drain.replace(D, PEERS + " " + "a" * 81), |
| + "peers with a space": drain.replace(PEERS, "--peers=adi box-b"), |
| + "peers with a quote": drain.replace(PEERS, "--peers=adi'b"), |
| + "peers with a dollar": drain.replace(PEERS, "--peers=adi$(id)"), |
| + "peers with a semicolon": drain.replace(PEERS, "--peers=adi;id"), |
| + "peers flag after the transaction": drain.replace(D, "t6 " + PEERS), |
| + "no peers flag": drain.replace(PEERS + " ", ""), |
| "drain without timeout": drain.replace("/usr/bin/timeout --signal=TERM --kill-after=30s 3600s ", ""), |
| "drain longer bound": drain.replace("3600s", "3601s"), |
| "fence-clear without status": clear.replace(" && " + STATUS, ""), |
| @@ -121,7 +164,7 @@ class DocumentPatternTests(unittest.TestCase): |
| "other property": stop.replace("--property=ActiveState", "--property=Environment"), |
| } |
| for addition in ("; id", " && id", " | sh"): |
| - bad["drain " + repr(addition)] = drain.replace("drain t6", "drain t6" + addition) |
| + bad["drain " + repr(addition)] = drain.replace(D, D + addition) |
| bad["stop " + repr(addition)] = stop.replace("carlos-edge.service)", "carlos-edge.service" + addition + ")") |
| for label, command in bad.items(): |
| with self.subTest(case=label): |
| @@ -296,7 +339,11 @@ class DocumentPatternTests(unittest.TestCase): |
| elif char == "[": |
| end = source.index("]", index) |
| self.assertIn(source[index:end + 1], ( |
| - "[0-9a-f]", "[A-Za-z0-9+/=]", "[A-Za-z0-9_-]", "[A-Za-z0-9_]", "[1-9]", "[1-5]", "[0-9]")) |
| + "[0-9a-f]", "[A-Za-z0-9+/=]", "[A-Za-z0-9_-]", "[A-Za-z0-9_]", "[1-9]", "[1-5]", "[0-9]", |
| + # The drain's acknowledgement list (held-floor-capability): |
| + # ASCII ranges and literal . _ , with - last; no space, |
| + # quote, semicolon or dollar, so it stays one argument. |
| + "[A-Za-z0-9._,-]")) |
| index = end |
| elif char == "{": |
| end = source.index("}", index) |
diff --git a/testdata/clireg-golden.jsonl b/testdata/clireg-golden.jsonl| index 6872ee194..d65b9318c 100644 |
| --- a/testdata/clireg-golden.jsonl |
| +++ b/testdata/clireg-golden.jsonl |
| @@ -824,8 +824,8 @@ |
| {"case":"system group | bare","argv":["system","group"],"exit":2,"stdout":"","stderr":"usage: carlos system <verb> [flags]\n carlos system router <verb> [flags]\n carlos system demos <status|serving on|serving off|takedown|takedown-status>\n carlos system managed-fleets <show|set --file f.json>\n carlos system antivirus <status|enable|disable|rotate-webhook-key> [flags]\n carlos system pdf status\n carlos system geoip <publish|status|off> [flags]\n carlos system seeds-floor publish --min-release <release>\n carlos system legacy-routes assign --name <name> --to <account>/<app>\n carlos system lifetimes cutover [--no-wait]\n carlos system hosts-used status\n carlos system named-units install <file>\n carlos system box role <box> <default|legacy|platform>\n carlos system box publish-record\n carlos system group role <region> <default|legacy>\n carlos system host-env <write|seed> --deployment <name> --region <code> [flags]\n\nThe platform's own binary (ops account owners and CARLOS_SYSTEM_OPERATORS):\n\n update promote a platform release to a channel; every box on it rolls itself\n status every box: platform, channel, running build, channel target, last apply outcome\n rollback point a channel back at the release before this one\n cancel-activation\n release a channel's activation reservation that was never\n published, so promote and rollback work again\n apply (root oneshot behind carlos-system-update.service; not for operators)\n layout migrate|revert|status: move every instance into its own directory\n and namespace, or back; see carlos system layout help\n seeds-floor publish --min-release <release>\n the first release whose boxes can place a seed, such as v0.27.0\n legacy-routes assign --name <name> --to <account>/<app>\n say which account and app the routes an operator filed by hand belong to\n lifetimes cutover [--no-wait]\n switch a console without host claims onto instance lifetimes,\n once, after the old console has stopped. Waits until they are on\n hosts-used status\n the hostname history: its mode, how many hostnames it has\n recorded, its closed fleets and its floor\n box role <box> <default|legacy|platform>\n whether new instances may be placed on a box. A legacy or\n platform box keeps the instances it has and takes no new ones\n group role <region> <default|legacy>\n the same for every box a region's group has enrolled, and for\n every box it enrolls later\n box publish-record\n run on a box as the agent user, with systemd-run -p User=carlos:\n publish its AWS-signed identity record to the deployment\n bucket, once. It never replaces or deletes a record\n\nA box a region's group launches (region HA):\n\n host-env write build host.env from the deployment's parameters (root)\n host-env seed copy a box's host.env into the deployment's parameters\n install-channel install the release this box's channel names (root)\n\nDeployment-wide settings (CARLOS_STORE_OPERATORS):\n\n pdf status\n\n antivirus status is object scanning wired, switched on, and answering?\n Reports wiring and policy separately, because they fail\n separately.\n antivirus enable turn object scanning on for this deployment. Refused if\n no engine is wired: a record claiming enabled with\n nothing behind it would report health where no scan can\n run.\n antivirus disable turn it off. Takes effect on the next tick — no restart,\n which is the point of the switch living in a record\n rather than in the unit file.\n antivirus rotate-webhook-key\n deliver the current master-derived callback secret to\n every scanning-enabled app, one bounded batch at a\n time. Skips apps already on that key, restarts the\n rest, and is safe to run again.\n\nPlatform GeoIP (ops account owners and CARLOS_SYSTEM_OPERATORS):\n\n geoip publish <file.mmdb> publish a MaxMind-format database (DB-IP Lite or\n GeoLite2) to every edge. -force skips the shrink check\n geoip status the published database, and whether every box\n strips forged headers and has it\n geoip off stop: edges drop the database and send no geo headers\n\nEnabling antivirus scans nothing by itself: a member still requests scanning\nfor their app, and an operator still grants it per store.\n\nThe platform is not an app: the console is updated with carlos deploy --app console.\n"} |
| {"case":"system group | help","argv":["system","group","help"],"exit":2,"stdout":"","stderr":"usage: carlos system <verb> [flags]\n carlos system router <verb> [flags]\n carlos system demos <status|serving on|serving off|takedown|takedown-status>\n carlos system managed-fleets <show|set --file f.json>\n carlos system antivirus <status|enable|disable|rotate-webhook-key> [flags]\n carlos system pdf status\n carlos system geoip <publish|status|off> [flags]\n carlos system seeds-floor publish --min-release <release>\n carlos system legacy-routes assign --name <name> --to <account>/<app>\n carlos system lifetimes cutover [--no-wait]\n carlos system hosts-used status\n carlos system named-units install <file>\n carlos system box role <box> <default|legacy|platform>\n carlos system box publish-record\n carlos system group role <region> <default|legacy>\n carlos system host-env <write|seed> --deployment <name> --region <code> [flags]\n\nThe platform's own binary (ops account owners and CARLOS_SYSTEM_OPERATORS):\n\n update promote a platform release to a channel; every box on it rolls itself\n status every box: platform, channel, running build, channel target, last apply outcome\n rollback point a channel back at the release before this one\n cancel-activation\n release a channel's activation reservation that was never\n published, so promote and rollback work again\n apply (root oneshot behind carlos-system-update.service; not for operators)\n layout migrate|revert|status: move every instance into its own directory\n and namespace, or back; see carlos system layout help\n seeds-floor publish --min-release <release>\n the first release whose boxes can place a seed, such as v0.27.0\n legacy-routes assign --name <name> --to <account>/<app>\n say which account and app the routes an operator filed by hand belong to\n lifetimes cutover [--no-wait]\n switch a console without host claims onto instance lifetimes,\n once, after the old console has stopped. Waits until they are on\n hosts-used status\n the hostname history: its mode, how many hostnames it has\n recorded, its closed fleets and its floor\n box role <box> <default|legacy|platform>\n whether new instances may be placed on a box. A legacy or\n platform box keeps the instances it has and takes no new ones\n group role <region> <default|legacy>\n the same for every box a region's group has enrolled, and for\n every box it enrolls later\n box publish-record\n run on a box as the agent user, with systemd-run -p User=carlos:\n publish its AWS-signed identity record to the deployment\n bucket, once. It never replaces or deletes a record\n\nA box a region's group launches (region HA):\n\n host-env write build host.env from the deployment's parameters (root)\n host-env seed copy a box's host.env into the deployment's parameters\n install-channel install the release this box's channel names (root)\n\nDeployment-wide settings (CARLOS_STORE_OPERATORS):\n\n pdf status\n\n antivirus status is object scanning wired, switched on, and answering?\n Reports wiring and policy separately, because they fail\n separately.\n antivirus enable turn object scanning on for this deployment. Refused if\n no engine is wired: a record claiming enabled with\n nothing behind it would report health where no scan can\n run.\n antivirus disable turn it off. Takes effect on the next tick — no restart,\n which is the point of the switch living in a record\n rather than in the unit file.\n antivirus rotate-webhook-key\n deliver the current master-derived callback secret to\n every scanning-enabled app, one bounded batch at a\n time. Skips apps already on that key, restarts the\n rest, and is safe to run again.\n\nPlatform GeoIP (ops account owners and CARLOS_SYSTEM_OPERATORS):\n\n geoip publish <file.mmdb> publish a MaxMind-format database (DB-IP Lite or\n GeoLite2) to every edge. -force skips the shrink check\n geoip status the published database, and whether every box\n strips forged headers and has it\n geoip off stop: edges drop the database and send no geo headers\n\nEnabling antivirus scans nothing by itself: a member still requests scanning\nfor their app, and an operator still grants it per store.\n\nThe platform is not an app: the console is updated with carlos deploy --app console.\n"} |
| {"case":"system group | zz-unknown","argv":["system","group","zz-unknown"],"exit":2,"stdout":"","stderr":"usage: carlos system <verb> [flags]\n carlos system router <verb> [flags]\n carlos system demos <status|serving on|serving off|takedown|takedown-status>\n carlos system managed-fleets <show|set --file f.json>\n carlos system antivirus <status|enable|disable|rotate-webhook-key> [flags]\n carlos system pdf status\n carlos system geoip <publish|status|off> [flags]\n carlos system seeds-floor publish --min-release <release>\n carlos system legacy-routes assign --name <name> --to <account>/<app>\n carlos system lifetimes cutover [--no-wait]\n carlos system hosts-used status\n carlos system named-units install <file>\n carlos system box role <box> <default|legacy|platform>\n carlos system box publish-record\n carlos system group role <region> <default|legacy>\n carlos system host-env <write|seed> --deployment <name> --region <code> [flags]\n\nThe platform's own binary (ops account owners and CARLOS_SYSTEM_OPERATORS):\n\n update promote a platform release to a channel; every box on it rolls itself\n status every box: platform, channel, running build, channel target, last apply outcome\n rollback point a channel back at the release before this one\n cancel-activation\n release a channel's activation reservation that was never\n published, so promote and rollback work again\n apply (root oneshot behind carlos-system-update.service; not for operators)\n layout migrate|revert|status: move every instance into its own directory\n and namespace, or back; see carlos system layout help\n seeds-floor publish --min-release <release>\n the first release whose boxes can place a seed, such as v0.27.0\n legacy-routes assign --name <name> --to <account>/<app>\n say which account and app the routes an operator filed by hand belong to\n lifetimes cutover [--no-wait]\n switch a console without host claims onto instance lifetimes,\n once, after the old console has stopped. Waits until they are on\n hosts-used status\n the hostname history: its mode, how many hostnames it has\n recorded, its closed fleets and its floor\n box role <box> <default|legacy|platform>\n whether new instances may be placed on a box. A legacy or\n platform box keeps the instances it has and takes no new ones\n group role <region> <default|legacy>\n the same for every box a region's group has enrolled, and for\n every box it enrolls later\n box publish-record\n run on a box as the agent user, with systemd-run -p User=carlos:\n publish its AWS-signed identity record to the deployment\n bucket, once. It never replaces or deletes a record\n\nA box a region's group launches (region HA):\n\n host-env write build host.env from the deployment's parameters (root)\n host-env seed copy a box's host.env into the deployment's parameters\n install-channel install the release this box's channel names (root)\n\nDeployment-wide settings (CARLOS_STORE_OPERATORS):\n\n pdf status\n\n antivirus status is object scanning wired, switched on, and answering?\n Reports wiring and policy separately, because they fail\n separately.\n antivirus enable turn object scanning on for this deployment. Refused if\n no engine is wired: a record claiming enabled with\n nothing behind it would report health where no scan can\n run.\n antivirus disable turn it off. Takes effect on the next tick — no restart,\n which is the point of the switch living in a record\n rather than in the unit file.\n antivirus rotate-webhook-key\n deliver the current master-derived callback secret to\n every scanning-enabled app, one bounded batch at a\n time. Skips apps already on that key, restarts the\n rest, and is safe to run again.\n\nPlatform GeoIP (ops account owners and CARLOS_SYSTEM_OPERATORS):\n\n geoip publish <file.mmdb> publish a MaxMind-format database (DB-IP Lite or\n GeoLite2) to every edge. -force skips the shrink check\n geoip status the published database, and whether every box\n strips forged headers and has it\n geoip off stop: edges drop the database and send no geo headers\n\nEnabling antivirus scans nothing by itself: a member still requests scanning\nfor their app, and an operator still grants it per store.\n\nThe platform is not an app: the console is updated with carlos deploy --app console.\n"} |
| -{"case":"system group-maintenance | --zz-unknown-flag","argv":["system","group-maintenance","--zz-unknown-flag"],"exit":2,"stdout":"","stderr":"Usage: carlos system group-maintenance {status|permit|revoke|prepare|apply|rollback|drain|fence-clear}\nRoot only, on a group member. Use through the attended Session Manager operator.\n prepare --sha256 <digest>\n Verify the configured signed pointer, cache its artifact and write a request.\n Check local restart configuration. No staging, repoint or restart.\n Makes cloud GETs only when attended and operator-invoked, never on a timer.\n The total prepare timeout is five minutes.\n previous_result reports the last outcome for this exact promotion.\n An applied, rolled-back or rollback-failed result leaves request_written false.\n apply Run the normal permit-gated apply using the checked local host.env.\n On a group member use carlos system group-maintenance apply, never bare\n carlos system apply.\n rollback Restore this member's previous artifact using an explicit rollback permit.\n Use the same transaction and old/new digests after revoking the apply permit.\n Local only. A consumed rollback permit cannot be replayed.\n permit Read at most 4096 bytes of permit JSON from stdin and install it.\n revoke Remove the permit. Keep all consumed-action records.\n drain <transaction>\n Drain this member for a planned handover: withdraw it and wait for every\n live box to acknowledge, install the start fence for the transaction,\n then move every awake host away and drain the connections. Print the\n agent's JSON report. Exit 0 only when the report's result is ok.\n drain --cancel <transaction>\n End the drain of the transaction and remove its start fence.\n fence-clear <transaction>\n Remove the start fence of the transaction. Another transaction's fence\n is refused.\n status Print one v1 JSON object, at most 8192 bytes. Make one local health GET.\nStatus includes edge.started_at in UTC at second precision, derived from kernel boot time and clock ticks.\nIt is a lower bound, up to two seconds early; compare with a generation at least two seconds later and check the edge identity has not changed.\nClock errors are in edge.started_at_error; edge.error describes the process.\naccepted means the guard's validators accept this permit now; it is not readiness: check the action and its consumed flag too.\nStatus is local evidence, not proof of fresh admission or role publication.\nPresent and accepted is still not authorization for the operator.\nThe cloud facts are the operator's.\nThe operator must also check the published edges object for this process.\nExit codes: 0 success or help, 1 refused or failed, 2 invalid arguments.\nErrors go to stderr, prefixed with \"group-maintenance:\". A held apply lock\nrefuses the command. Unknown status fields are null or state \"unknown\".\n"} |
| -{"case":"system group-maintenance | -h","argv":["system","group-maintenance","-h"],"exit":0,"stdout":"Usage: carlos system group-maintenance {status|permit|revoke|prepare|apply|rollback|drain|fence-clear}\nRoot only, on a group member. Use through the attended Session Manager operator.\n prepare --sha256 <digest>\n Verify the configured signed pointer, cache its artifact and write a request.\n Check local restart configuration. No staging, repoint or restart.\n Makes cloud GETs only when attended and operator-invoked, never on a timer.\n The total prepare timeout is five minutes.\n previous_result reports the last outcome for this exact promotion.\n An applied, rolled-back or rollback-failed result leaves request_written false.\n apply Run the normal permit-gated apply using the checked local host.env.\n On a group member use carlos system group-maintenance apply, never bare\n carlos system apply.\n rollback Restore this member's previous artifact using an explicit rollback permit.\n Use the same transaction and old/new digests after revoking the apply permit.\n Local only. A consumed rollback permit cannot be replayed.\n permit Read at most 4096 bytes of permit JSON from stdin and install it.\n revoke Remove the permit. Keep all consumed-action records.\n drain <transaction>\n Drain this member for a planned handover: withdraw it and wait for every\n live box to acknowledge, install the start fence for the transaction,\n then move every awake host away and drain the connections. Print the\n agent's JSON report. Exit 0 only when the report's result is ok.\n drain --cancel <transaction>\n End the drain of the transaction and remove its start fence.\n fence-clear <transaction>\n Remove the start fence of the transaction. Another transaction's fence\n is refused.\n status Print one v1 JSON object, at most 8192 bytes. Make one local health GET.\nStatus includes edge.started_at in UTC at second precision, derived from kernel boot time and clock ticks.\nIt is a lower bound, up to two seconds early; compare with a generation at least two seconds later and check the edge identity has not changed.\nClock errors are in edge.started_at_error; edge.error describes the process.\naccepted means the guard's validators accept this permit now; it is not readiness: check the action and its consumed flag too.\nStatus is local evidence, not proof of fresh admission or role publication.\nPresent and accepted is still not authorization for the operator.\nThe cloud facts are the operator's.\nThe operator must also check the published edges object for this process.\nExit codes: 0 success or help, 1 refused or failed, 2 invalid arguments.\nErrors go to stderr, prefixed with \"group-maintenance:\". A held apply lock\nrefuses the command. Unknown status fields are null or state \"unknown\".\n","stderr":""} |
| +{"case":"system group-maintenance | --zz-unknown-flag","argv":["system","group-maintenance","--zz-unknown-flag"],"exit":2,"stdout":"","stderr":"Usage: carlos system group-maintenance {status|permit|revoke|prepare|apply|rollback|drain|fence-clear}\nRoot only, on a group member. Use through the attended Session Manager operator.\n prepare --sha256 <digest>\n Verify the configured signed pointer, cache its artifact and write a request.\n Check local restart configuration. No staging, repoint or restart.\n Makes cloud GETs only when attended and operator-invoked, never on a timer.\n The total prepare timeout is five minutes.\n previous_result reports the last outcome for this exact promotion.\n An applied, rolled-back or rollback-failed result leaves request_written false.\n apply Run the normal permit-gated apply using the checked local host.env.\n On a group member use carlos system group-maintenance apply, never bare\n carlos system apply.\n rollback Restore this member's previous artifact using an explicit rollback permit.\n Use the same transaction and old/new digests after revoking the apply permit.\n Local only. A consumed rollback permit cannot be replayed.\n permit Read at most 4096 bytes of permit JSON from stdin and install it.\n revoke Remove the permit. Keep all consumed-action records.\n drain --peers=<box,...> <transaction>\n Drain this member for a planned handover: withdraw it and wait for every\n listed box, and any other box with an edges file, to acknowledge, install\n the start fence for the transaction, then move every awake host away and\n drain the connections. --peers lists every other box the operator's\n floor counted (empty when it counted none). Print the agent's JSON\n report. Exit 0 only when the report's result is ok.\n drain --cancel <transaction>\n End the drain of the transaction and remove its start fence.\n fence-clear <transaction>\n Remove the start fence of the transaction. Another transaction's fence\n is refused.\n status Print one v1 JSON object, at most 8192 bytes. Make one local health GET.\nStatus includes edge.started_at in UTC at second precision, derived from kernel boot time and clock ticks.\nIt is a lower bound, up to two seconds early; compare with a generation at least two seconds later and check the edge identity has not changed.\nClock errors are in edge.started_at_error; edge.error describes the process.\naccepted means the guard's validators accept this permit now; it is not readiness: check the action and its consumed flag too.\nStatus is local evidence, not proof of fresh admission or role publication.\nPresent and accepted is still not authorization for the operator.\nThe cloud facts are the operator's.\nThe operator must also check the published edges object for this process.\nExit codes: 0 success or help, 1 refused or failed, 2 invalid arguments.\nErrors go to stderr, prefixed with \"group-maintenance:\". A held apply lock\nrefuses the command. Unknown status fields are null or state \"unknown\".\n"} |
| +{"case":"system group-maintenance | -h","argv":["system","group-maintenance","-h"],"exit":0,"stdout":"Usage: carlos system group-maintenance {status|permit|revoke|prepare|apply|rollback|drain|fence-clear}\nRoot only, on a group member. Use through the attended Session Manager operator.\n prepare --sha256 <digest>\n Verify the configured signed pointer, cache its artifact and write a request.\n Check local restart configuration. No staging, repoint or restart.\n Makes cloud GETs only when attended and operator-invoked, never on a timer.\n The total prepare timeout is five minutes.\n previous_result reports the last outcome for this exact promotion.\n An applied, rolled-back or rollback-failed result leaves request_written false.\n apply Run the normal permit-gated apply using the checked local host.env.\n On a group member use carlos system group-maintenance apply, never bare\n carlos system apply.\n rollback Restore this member's previous artifact using an explicit rollback permit.\n Use the same transaction and old/new digests after revoking the apply permit.\n Local only. A consumed rollback permit cannot be replayed.\n permit Read at most 4096 bytes of permit JSON from stdin and install it.\n revoke Remove the permit. Keep all consumed-action records.\n drain --peers=<box,...> <transaction>\n Drain this member for a planned handover: withdraw it and wait for every\n listed box, and any other box with an edges file, to acknowledge, install\n the start fence for the transaction, then move every awake host away and\n drain the connections. --peers lists every other box the operator's\n floor counted (empty when it counted none). Print the agent's JSON\n report. Exit 0 only when the report's result is ok.\n drain --cancel <transaction>\n End the drain of the transaction and remove its start fence.\n fence-clear <transaction>\n Remove the start fence of the transaction. Another transaction's fence\n is refused.\n status Print one v1 JSON object, at most 8192 bytes. Make one local health GET.\nStatus includes edge.started_at in UTC at second precision, derived from kernel boot time and clock ticks.\nIt is a lower bound, up to two seconds early; compare with a generation at least two seconds later and check the edge identity has not changed.\nClock errors are in edge.started_at_error; edge.error describes the process.\naccepted means the guard's validators accept this permit now; it is not readiness: check the action and its consumed flag too.\nStatus is local evidence, not proof of fresh admission or role publication.\nPresent and accepted is still not authorization for the operator.\nThe cloud facts are the operator's.\nThe operator must also check the published edges object for this process.\nExit codes: 0 success or help, 1 refused or failed, 2 invalid arguments.\nErrors go to stderr, prefixed with \"group-maintenance:\". A held apply lock\nrefuses the command. Unknown status fields are null or state \"unknown\".\n","stderr":""} |
| {"case":"system guard-arm | --zz-unknown-flag","argv":["system","guard-arm","--zz-unknown-flag"],"exit":2,"stdout":"","stderr":"flag provided but not defined: -zz-unknown-flag\nUsage of system guard-arm:\n -console string\n \t\n -enrollment string\n \t\n -identity string\n \t\n -policy string\n \t\n"} |
| {"case":"system guard-arm | -h","argv":["system","guard-arm","-h"],"exit":0,"stdout":"","stderr":"Usage of system guard-arm:\n -console string\n \t\n -enrollment string\n \t\n -identity string\n \t\n -policy string\n \t\n"} |
| {"case":"system guard-exec zz | extra (release key set)","argv":["system","guard-exec","zz"],"env":{"CARLOS_RELEASE_PUBKEY":"ebVWLo/mVPlAeLES6KmLp5AfhTrmlb7X4OORC60ElmQ="},"exit":1,"stdout":"","stderr":"hostfloor: authenticated floor required\n"} |