docs: W6 ingress drain spec rev 4 (approved) and plan
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2 files changed,
+302
−0
docs/superpowers/plans/2026-11-10-fixed-edge-ingress-drain.md+81 −0docs/superpowers/specs/2026-11-10-fixed-edge-ingress-drain-design.md+221 −0
CI passed — run details
Intent
Attributed to this commit: 60.1 g CO₂e (4,793,639 tokens). This is an attribution, not a measurement — usage counted from this commit's own marker forward to the next one on w6-ingress-drain, never backward from it. A turn that produced more than one commit books all of its tokens to the last one, and a concurrent session on this branch can add to the same figure. Some of it was priced using the shared default rate, because no model-specific factor row exists yet for at least one model involved. The Carbon view has the repo total, which is never derived from this attribution.
diff --git a/docs/superpowers/plans/2026-11-10-fixed-edge-ingress-drain.md b/docs/superpowers/plans/2026-11-10-fixed-edge-ingress-drain.md| new file mode 100644 |
| index 000000000..75331a55e |
| --- /dev/null |
| +++ b/docs/superpowers/plans/2026-11-10-fixed-edge-ingress-drain.md |
| @@ -0,0 +1,81 @@ |
| +# W6 ingress drain: implementation plan |
| + |
| +Spec: `docs/superpowers/specs/2026-11-10-fixed-edge-ingress-drain-design.md` (rev 4). Not approved for build until Paul says so. Build with SDD: Opus implementers, Astra reviews each task, Astra and Fable review the branch (units, the socket, the verbs and IAM are on the security list). TDD throughout. Review rounds: at most three per review. |
| + |
| +Branch `w6-ingress-drain` from `origin/main`. One amadan task per plan task. Local tests: changed packages with `-run`; CI runs the full suite. |
| + |
| +## Task 1: the `ingress-drain` condition |
| + |
| +- `internal/lbhealth`: `CondIngressDrain = "ingress-drain"`; `State.SetIngressDrain(bool)`; `Failing` lists it last. The zero value does not fail it. |
| +- Tests: listed and ordered; nil state unchanged. |
| + |
| +## Task 2: the target-health adapter |
| + |
| +- `internal/ingresshealth` (new, provider-neutral interface): `Withdrawn(ctx, self) (Verdict, error)` over a list of target groups, returning per-group state and the count of other healthy targets. |
| +- AWS adapter: `DescribeTargetHealth` per target group with no target filter, through the SDK client and credentials the agent already uses for EC2 reads (`ec2:DescribeInstances`, region HA §12.2); this box's entries by instance id and registered port; the count of other `healthy` targets from the same response. Only `unhealthy` and `unhealthy.draining` count as withdrawn; everything else, `draining` and `unused` included, does not. `DescribeTargetGroupAttributes` once per drain: termination off and draining interval >= 180 s, or `unverified: target group retention`. |
| +- Config: `CARLOS_INGRESS_TARGET_GROUPS` (comma-separated ARNs; each must parse as an `elasticloadbalancing` target group ARN in the box's own account and region, or the drain is `not_armed` with the reason logged once at start). |
| +- Tests: state mapping; parse refusals; a fake client. |
| + |
| +## Task 3: the edge's drain calls |
| + |
| +- `internal/edge`: `Edge.BeginIngressDrain()` sets `connDrain.draining` (Connection: close) without the barrier and without touching keep-alives' ownership by §25; refuses if §25's drain is on. |
| +- `Edge.CloseIngress(ctx, wait)`: closes edge-held streams (`closeAllHeld`), then calls `Shutdown` on both servers with a `wait` context, then cancels and closes what is still running as `DrainConnections` does at its bound, and joins within `drainJoinBound`. Returns the counts. |
| +- `DrainConnections` refuses while an ingress drain is on (the guard). |
| +- The SIGTERM path (`edge.go:4976-4981`) is unchanged: `Shutdown` on an already-shut server returns at once. Confirm the serve goroutines' `ErrServerClosed` handling with a test. |
| +- Tests: spec §9 "Edge, step 1 and step 3" and "Guard", with real `http.Server`s on loopback, HTTP/1 and HTTP/2 (TLS) clients. |
| + |
| +## Task 4: the drain driver |
| + |
| +- `internal/host/ingressdrain.go`: spec §4.1 arming and §4.2 steps with a clock seam. Fixed: poll 2 s, settle 10 s (states must hold through it), cap 90 s, connection wait 30 s, exit 3 minutes after step 3. One drain per process; join. |
| +- The 3-minute exit: `log.Printf` then `os.Exit(1)` through a seam. |
| +- Tests (fake clock, fake edge, fake adapter): spec §9 "Arming" and "The drain state machine". |
| + |
| +## Task 5: the socket routes and serving it on fixed boxes |
| + |
| +- `internal/host/hadrain_socket.go`: `POST /v1/ingress/drain` (bounded 140 s; the drain continues on the agent if the caller goes away, and a repeat joins it) and `GET /v1/ingress/status`. |
| +- `internal/host/agent.go:1236-1243`: serve the socket when the ingress drain is armed too; mount the `/v1/drain/*` routes only on group members (404 otherwise). |
| +- Tests: routes; 404 for group routes on a fixed box; the peer rule unchanged (existing SO_PEERCRED tests). |
| + |
| +## Task 6: `carlos __ingress-drain` and the verbs |
| + |
| +- Private entry point beside `__drain-call`, before CLI dispatch. Run by the unit as the agent's user: dials the socket, prints the report, exits 0 in every case (no socket, refused, 404, timeout, error answer), each with one line saying why. |
| +- `systemapply.go`: `apply` and `rollback` ask for the drain through the existing drain-call child (pinned `/proc/self/exe`, privilege drop) after their refusals and preflight, before `quiesce` and the binary swap, and only when they will restart the edge. They print the report. A 404 or no socket is logged and the verb goes on. |
| +- Tests: each exit path of `__ingress-drain`; the verbs' order and the no-drain cases with `systemapply`'s fakes. |
| +- Transition test: a pre-W6 to W6 apply with a forced gate failure rolls back undrained and leaves the box serving (spec §5.3). |
| + |
| +## Task 7: units |
| + |
| +- New `internal/host/units/carlos-edge-drain.service` per spec §5.2; hardening copied from the edge, empty `CapabilityBoundingSet`, no `AmbientCapabilities`. |
| +- `carlos-edge.service`: `Upholds=carlos-edge-drain.service`. |
| +- Every tenant unit with `BindsTo=carlos-edge.service` (twelve today): `Before=carlos-edge-drain.service`. |
| +- `systemapply.go`: install and enable the unit with the others; start it after `daemon-reload`. Check that rollback's unit diff removes a unit present only in the newer set, as for other added units. |
| +- Check the systemd version on every AMI in use on dev and flagship (`Upholds=` needs 249); record it in the task report. |
| +- Check the SSM command timeout of every caller of `carlos system apply` and `rollback`, including `region-group-roll.py`'s and the Go group verb's apply steps: each must allow 150 s more than today. Raise any that do not. |
| +- Tests: the unit lint of spec §9; systemapply's install order. |
| + |
| +## Task 8: tofu |
| + |
| +- `infra/modules/region-host/ingress/main.tf`: the `target_health_state` block on `aws_lb_target_group.target` per spec §8. |
| +- `infra/modules/region-host`: a fixed-mode variable naming the target groups the box is attached to; when set, the box role gains `elasticloadbalancing:DescribeTargetHealth` and the host-env parameters gain `CARLOS_INGRESS_TARGET_GROUPS`. Confirm against the AWS service authorization reference whether the action takes a resource ARN; use it if so, else `*`. |
| +- `internal/hostenv`: add `CARLOS_INGRESS_TARGET_GROUPS` to the allowlist (`hostenv.go:74`, assembly at 223 and 419) with the ARN validation of Task 2; assembly and seed tests. |
| +- The role statement carries both read actions. |
| +- Card order (for 8a3d302's cards, recorded in the runbook): attributes and role first, checked with `describe-target-group-attributes`, then the host-env key. |
| +- Committed module tests for both (OpenTofu 1.13.9, as for the operator-policy test). |
| +- No live apply. Dev pinfra and flagship carloku-infrastructure applies are card steps for 8a3d302 after merge. |
| + |
| +## Task 9: root runner |
| + |
| +- `TestRootIngressDrainOrder` in the `TestRootHATerminateRelease` harness (`internal/host/haterminate_rootrunner_linux_test.go`), with a fake target-health adapter seam that turns `unhealthy` 10 s after the drain starts: spec §9 "Root runner" in full, including rollback from a W6 build to a pre-W6 build. |
| + |
| +## Task 10: docs |
| + |
| +- Region HA spec: pointers from §10 and §25.2 step 1 to this spec; §12.1's target group line gains the two attributes; §12.2 gains the fixed-box read right. |
| +- Runbook "Restarting a fixed box": planned stops drain on their own; expect 30 to 60 s; the journal line to read; what `unverified` means; the 3-minute exit. |
| + |
| +## Task 11: census |
| + |
| +- `make census-card`; claims for every new or changed root-binary package and unit (`internal/lbhealth`, `internal/ingresshealth`, `internal/edge`, `internal/host`, `internal/hostenv`, the new and changed units); `make census-propose NAME=w6-ingress-drain CLAIMS=<file>`; independent review of the overlay against the final diff by Astra and Fable; verdict recorded on #280 with the tip, per AGENTS.md "The census: the reviewer decides". |
| + |
| +## Witness (after a release Paul schedules) |
| + |
| +Spec §10, by 8a3d302's card. Not part of the build. |
diff --git a/docs/superpowers/specs/2026-11-10-fixed-edge-ingress-drain-design.md b/docs/superpowers/specs/2026-11-10-fixed-edge-ingress-drain-design.md| new file mode 100644 |
| index 000000000..3e491d73d |
| --- /dev/null |
| +++ b/docs/superpowers/specs/2026-11-10-fixed-edge-ingress-drain-design.md |
| @@ -0,0 +1,221 @@ |
| +# W6: drain a box out of the load balancer before its edge stops |
| + |
| +Design, 2026-11-10, **rev 4** (Astra rounds 1 to 3 applied, §12 to §14; round 2 repeated two families, so rev 3 narrowed the claim up front under stopping rule 2; round 3 READY AFTER FIXES, its two P2s applied in rev 4 with no fourth round). Agent manager 8a3d302 asked for it on 2026-11-10 with Paul's approval: a small spec, in parallel with G5. It gates calling region HA "done"; it does not gate G5. **APPROVED 2026-11-10**: Paul ("Let's finish this out"), relayed by agent manager 8a3d302 as yes to all four §11 decisions (target groups: unhealthy connection termination off, 180 s draining; fixed-box read-only DescribeTargetHealth and DescribeTargetGroupAttributes; health interval stays 10 s; planned stops 30-60 s slower). Build per the plan on branch `w6-ingress-drain`; infra applies go to 8a3d302 as targeted plans first. Review budget: at most three Astra rounds (AGENTS.md stopping rules). |
| + |
| +Line citations are to `origin/main` at c2083896. |
| + |
| +## 1. The finding |
| + |
| +Dev witness W6, 2026-11-09 20:42Z (`~/.cache/region-ha-held/REPORT.md`, "Dev witness window 1"). leo is a fixed box registered in the IE NLB's target groups. Restarting its edge under a probe at about 45 requests a second, aimed at an app hosted on the group members: |
| + |
| +- 26 of 1080 requests failed over 24 s. First 12 x connection refused while the edge was down, then 14 x 503 `Retry-After: 10` while tenant admission was closed after start. |
| +- The target group marked leo unhealthy only at 20:42:31, about 23 s after the stop, when the errors were over. It marked it healthy again at about 20:43:08. |
| +- No acknowledged write was lost and SSE had no gaps. The errors are ingress errors only. |
| + |
| +On the flagship, adi (a fixed HA box in the US target groups) shows 36 to 57 s of closed admission on every release. Its errors are bounded the same way: the NLB keeps sending it new flows until two failed health checks have landed. |
| + |
| +The cause is order. The load balancer learns that a box is going away only from failed health checks, and today the first failed check comes after the edge has already stopped. Group members do not have this gap on planned paths, because §25's transaction puts them in Standby (deregistered, 30 s deregistration delay) before anything stops. A fixed box cannot enter Standby: its target group attachment is a static `aws_lb_target_group_attachment` in the operator's tofu, and the box has no ELB rights (region HA spec §12.2). |
| + |
| +## 2. What changes, in one paragraph |
| + |
| +Before any planned stop of the edge on a **fixed** box that is a target of a region's NLB, the box makes its own health check fail while it keeps serving everything normally, reads the target groups until both report it no longer healthy, then stops its public listeners gracefully (Go's `Server.Shutdown`: GOAWAY on HTTP/2, idle connections closed, in-flight requests finished), and only then lets systemd stop the tenants and the edge. Two triggers run the same drain in the agent: the root verbs `carlos system apply` and `rollback` ask for it before they touch the binary, and a new oneshot unit, `carlos-edge-drain.service`, asks for it in its `ExecStop`, ordered so systemd finishes it before any tenant unit or the edge stops. After start the box already reports healthy only once tenant admission is open; that stays, and gains a test. The target groups stop resetting connections the moment a target turns unhealthy, so connections still open at that moment can finish. Group members are out of scope: their planned paths use §25's Standby transaction. |
| + |
| +## 3. Guarantee |
| + |
| +**The target is zero errors, and it is measured, not proven.** AWS documents neither a bound on how long NLB nodes take to apply a target's unhealthy state nor which node routes a given flow. So the design does what the box can check (it reads the target groups' own verdict, waits a settle on top, and keeps every connection it already has), and the dev witness measures the result (§10). The spec does not claim that no NLB node can send a new flow after the settle; a flow that arrives after step 3 meets a closed listener, exactly as at today's stop. |
| + |
| +Within that, **no errors are expected** for requests that reach the region through the NLB while a fixed box that is one of its targets is restarted or stopped on a planned path, when all of these hold: |
| +- the drain reports `withdrawn` (§4.2 step 2); |
| +- at least one other target in each target group is healthy throughout (otherwise the NLB fails open, §8, and the drain reports `unverified`); |
| +- the request's host is not held by the restarting box; |
| +- the box has started serving the request (read its headers and dispatched it) before step 3, and it completes within the connection wait (30 s). A connection the box accepted before step 3 whose request headers have not all arrived when step 3 starts is closed by Go's `Shutdown` without an answer (`net/http/server.go:2009`); this is refused up front, not handled. In practice it needs a client that opened a connection through the NLB before withdrawal and sent nothing for the settle and more. Longer requests (slow uploads or downloads) and long-lived streams (SSE, WebSockets) still open at the end of the wait are closed, as at today's shutdown; streams reconnect through the NLB to another box, as in §25.4 step 4. |
| + |
| +**Not covered, unchanged from today:** |
| +- Requests for hosts held by the restarting box. A fixed (non-HA) host is down for the restart, and from the end of step 2 rather than from the stop: once the listeners close, peers' hops to it are refused and answered with today's 503 `Retry-After: 10`. An HA host held by a fixed HA box (adi; leo when it serves a pool) is released with a clean marker at shutdown (§9.9), and peers answer 503 `Retry-After: 10` until they read it (§25.1 item 3). Moving those hosts first is §25's job, and §25 drains group members only (§6). |
| +- Unplanned stops (§7). |
| +- Group members (§4.1). |
| + |
| +## 4. The drain |
| + |
| +### 4.1 Who has one |
| + |
| +A box's drain is armed when all of these hold, and is otherwise `not_armed`, answered at once, with the stop exactly as today: |
| +- its load balancer health answer is armed (`CARLOS_REGION_HA` on, `internal/edge/lbhealth.go:21-31`); |
| +- it is a fixed box: tenant admission is the fixed kind (`internal/host/group_admission.go:55-70`, `group` false). A group member answers `group_member`. A member in service that failed its own health check would be replaced by the group's ELB health check (`infra/modules/region-host/group.tf:246-249`), so members drain only through §25; |
| +- `host.env` names the target groups it is registered in: `CARLOS_INGRESS_TARGET_GROUPS`, a comma-separated list of target group ARNs. The operator's tofu that attaches the box (the static `aws_lb_target_group_attachment`) writes it through the existing host-env parameters. A fixed box not attached to any NLB has no key and no drain. |
| + |
| +The core treats "is this box still a target that receives new flows" as an adapter, beside the termination oracle (region HA §12.5). The AWS adapter reads `elasticloadbalancing:DescribeTargetHealth`. Off AWS there is no adapter and no drain. |
| + |
| +### 4.2 Steps |
| + |
| +The agent runs these when asked (§5). One drain per agent process; a second request joins it and gets the same report. |
| + |
| +1. **Fail the health check, keep serving.** `lbhealth.State` gains one condition, `ingress-drain`, listed by `Failing` after the six it has (`internal/lbhealth/lbhealth.go:154-178`). The health answer becomes 503 `unavailable: ingress-drain`. Nothing else changes: tenant admission stays open, the edges file keeps the box's role and admission, placement and forwarding are unchanged, and peers keep forwarding to it as a holder. Every response now says `Connection: close` (the switch §25's connection drain uses, §4.3), so each HTTP/1 client connection carries at most one more request and the client's next connection goes through the NLB again. There is **no barrier**: a request that arrives during the drain is served normally. |
| +2. **Wait for the target groups.** Every 2 s the agent calls `DescribeTargetHealth` on each named target group with **no target filter**, so one response carries every target: it finds its own entries by instance id and the ports it is registered on (80 and 443), and counts the other targets reported `healthy`. Before the first poll it reads `DescribeTargetGroupAttributes` once per target group; if unhealthy connection termination is on, or the draining interval is below 180 s (§8), the verdict is `unverified: target group retention` and the drain goes on to the cap's behaviour below. If the box's state at the first poll is already anything but `healthy`, its age is unknown and the verdict is `unverified: not healthy at start`. |
| + |
| + It goes on when every target group reports the box `unhealthy` or `unhealthy.draining`, and at least one other target `healthy`, and then waits a **settle** of 10 s, polling on. The verdict is `withdrawn` only if the states held through the settle. `draining` and `unused` (deregistration) do not count: AWS notes that a deregistering target may still receive new connections while the change propagates, and the ingress drain never deregisters. The settle is a margin, not a documented bound (§3). |
| + |
| + The cap is 90 s from the request. If a read fails, or any target group still reports the box `healthy` or `initial` at the cap, the agent goes on anyway and records `unverified`, naming the target group, its last state or the read error. The drain cannot refuse the stop: a reboot or a `systemctl stop` is already under way, and stalling it longer helps nobody. Fail-open (§8) shows up here as the healthy-peer count: with none, the verdict is `unverified: no other healthy target`. |
| +3. **Close the public listeners gracefully.** The agent calls `Shutdown` on the edge's `:443` and `:80` servers with a 30 s context (the **connection wait**). Go's `Shutdown` stops accepting, closes idle connections, sends HTTP/2 GOAWAY to every HTTP/2 connection, and waits for the requests it has already dispatched on both protocols. A connection whose request headers are still incomplete is closed without an answer (§3). Before the wait it closes the edge-held SSE streams still open through it at an event boundary (`closeAllHeld`, which the edge already tracks). Other long-lived responses (proxied SSE, WebSockets) are not picked out early: they run until the 30 s bound, so a drain with one open takes the whole wait. At 30 s, whatever is still running is cancelled and its connection closed, as in `DrainConnections` (`internal/edge/hadrainconns.go:193-232`), and counted. The serve loops already treat `http.ErrServerClosed` as a normal exit (`internal/edge/edge.go:4956-4966`), and the shutdown at SIGTERM finds the servers already shut and returns at once. |
| +4. **Answer** with the report: the verdict (`withdrawn` or `unverified` and why), the target groups' states over time, the time each step ended, requests finished during the wait, and streams and connections closed. The caller logs it to the journal and returns. systemd then stops tenant units and the edge, which closes admission and shuts down as today (`internal/edge/shutdown.go:9-14`, §9.9). |
| + |
| +After step 3 the box serves nothing on its public ports. If the agent is still running 3 minutes after step 3 ended (someone stopped only the drain unit, or a verb failed after draining), it logs `ingress drain ended without a stop; exiting` and exits non-zero. systemd restarts it (`Restart=always`), and it comes back through admission and two passing health checks like any start. Before step 3 an abandoned caller changes nothing: the agent finishes the drain on its own, because the stop it was asked for is coming. |
| + |
| +### 4.3 Sharing the connection drain with §25 |
| + |
| +§25's `connDrain` (`internal/edge/hadrainconns.go:72-260`) owns `Connection: close`, keep-alives and the barrier, and runs on group members only. The ingress drain runs on fixed boxes only (§4.1), so the two never run on one box. The ingress drain uses `connDrain`'s `Connection: close` switch in step 1 and its stream closing and bound in step 3, never its barrier. The build adds a guard that refuses to start one while the other is on, so a future change to §4.1 cannot make them overlap silently. |
| + |
| +## 5. Triggers |
| + |
| +### 5.1 Why two |
| + |
| +The edge cannot do this at SIGTERM. Every instance template is bound to the edge and ordered after it (`internal/host/units/carlos-instance@.service:14-16` and eleven siblings), so systemd stops the tenants before the edge gets its signal (§25 r2 note, R1.1). The drain has to finish before systemd stops anything. |
| + |
| +- **The root verbs** cover rolls, including a rollback across the release that introduced W6 (§5.3). |
| +- **The drain unit** covers every other systemd stop of the edge: a manual `systemctl restart` or `stop`, and an OS reboot or poweroff. |
| + |
| +Both reach the same agent drain, so whichever comes first does the work and the second joins it. |
| + |
| +### 5.2 The drain unit |
| + |
| +``` |
| +[Unit] |
| +Description=carlos edge ingress drain (load balancer health, W6) |
| +BindsTo=carlos-edge.service |
| +After=carlos-edge.service |
| + |
| +[Service] |
| +Type=oneshot |
| +RemainAfterExit=yes |
| +ExecStart=/bin/true |
| +ExecStop=-/opt/carlos/carlos __ingress-drain |
| +TimeoutStopSec=150 |
| +User=carlos |
| +Group=carlos |
| +(the edge's hardening, with an empty capability bounding set) |
| +``` |
| + |
| +- **Started with the edge.** `carlos-edge.service` gains `Upholds=carlos-edge-drain.service` (systemd 249 or later), so the drain unit is active whenever the edge is: after a boot, a `systemctl restart` and an automatic restart alike. The plan checks the boxes' systemd version; the root-runner test (§9) decides between `Upholds=` and `Wants=`. |
| +- **Finished first.** Every tenant unit, that is every unit other than the drain unit that has `BindsTo=carlos-edge.service`, gains `Before=carlos-edge-drain.service`. systemd stops units in reverse order and starts a unit's stop only after the stop jobs ordered before it have finished, so in a stop of the edge the drain unit's `ExecStop` **completes** before any tenant unit's stop begins, and before the edge's own stop. A unit test fails if a tenant unit misses the line. |
| +- **Never blocks a stop.** The `-` prefix ignores the exit status, and `__ingress-drain` exits 0 in every case. If the agent's socket does not answer (the edge already crashed, or an older agent without the route), it exits at once. `TimeoutStopSec=150` covers the 90 s cap, the 10 s settle, the 30 s connection wait and slack. The edge's own `TimeoutStopSec=120` is separate and unchanged. |
| +- **How it reaches the agent.** It runs as the agent's user and dials the agent's existing drain socket, `/run/carlos/.ha-drain/drain.sock` (`internal/host/hadrain_socket.go:30-34`), which serves only that user (SO_PEERCRED, `hadrain_socket_linux.go:23-31`). New routes: `POST /v1/ingress/drain` (start or join, wait, answer the report; bounded at 140 s) and `GET /v1/ingress/status`. Today the socket is served on group members only (`internal/host/agent.go:1236-1243`); it is now served whenever the ingress drain is armed too, and the group-only `/v1/drain/*` routes answer 404 on a fixed box. Instances never see the socket: their namespaces replace `/run/carlos` (`hadrain_socket.go:8-9`). |
| + |
| +### 5.3 The root verbs, and rollback across W6 |
| + |
| +Rollback restores `carlos.prev` over `/opt/carlos/carlos` and then installs the older unit set, which lacks the drain unit, before it restarts the edge (`internal/host/systemapply.go:2063-2098`). By the time the drain unit stopped, its `ExecStop` would run the old binary, which has no `__ingress-drain`. So `apply` and `rollback` ask for the drain themselves, **before** they quiesce and swap anything, through the drain-call child they already use for group maintenance (`internal/host/hadrain_call.go`): root re-executes its own pinned `/proc/self/exe` (the binary running the verb, not the file on disk), which drops to the agent's user and dials the socket. The verb waits for the report and prints it. If the verb then fails before it restarts the edge, the agent's 3-minute exit (§4.2) restores service. |
| + |
| +A verb that will not restart the edge (a refusal, a no-op apply of the same release) asks for no drain. The verb asks only after its own refusals and preflight checks have passed. |
| + |
| +**Not drained: anything a pre-W6 binary runs.** That is the first roll onto W6, and also an automatic rollback or recovery that the pre-W6 verb process runs during that first roll if the new agent fails its gate (`internal/host/systemapply.go:675`, `:730`): the old process cannot ask, and the binary it restores has no helper. |
| + |
| +**The first roll onto W6** is not drained: the agent being stopped is the old one, with no `/v1/ingress/*` route, so the request gets a 404 and the verb goes on as today. A rollback from W6 to an older release is drained, because the running agent is W6's and the verb's own binary asks. The dev witness (§10) runs a restart after the release, a roll, and a rollback. |
| + |
| +`carlos system apply` installs and starts the drain unit with the others after `daemon-reload`. A rollback that removes it leaves nothing behind: the older release's agent has no drain to ask for. |
| + |
| +## 6. Interactions |
| + |
| +- **§25 held requests.** §25 drains group members only and puts them in Standby first; the ingress drain is off on members (§4.1). For a fixed HA box, the ingress drain is the counterpart of §25.2 step 1 ("out of the load balancer"). It does not move hosts. A later extension of §25 to fixed HA boxes would run the ingress drain's steps 1 and 2, then §25's steps 2 to 4, then step 3 here, then the stop. Not part of this spec. |
| +- **Placement and forwarding.** The ingress drain publishes nothing and withdraws nothing, so §24's reader table is untouched. Peers keep placing on the box and forwarding to it until step 3 closes the listeners; after that their hops are refused and they answer 503 `Retry-After: 10` for the box's hosts, which is today's answer for a stopped box, moved earlier by the connection wait (§3). |
| +- **The housekeeper lease on adi.** Unchanged. The housekeeper keeps renewing through the drain and stands down in the post-drain block at shutdown, releasing at once (`internal/host/housekeeper.go:255-283`). The drain adds up to 2 minutes before the stop, not to the gap between stand-down and the next acquire. Certificate work that needs the listeners (ACME HTTP-01 challenges) is answered from the mirror by any other box the NLB sends them to (`internal/edge/certsync.go:1811-1830`); the issuing box's own in-memory orders are a renewal it retries later, as at any restart. |
| +- **Hairpin.** Local callers on the box reach its own edge through the nftables redirect (§12.4). Until step 3 they are served; after it they are refused, as at today's stop. |
| +- **The admission gap after start.** adi's 36 to 57 s of closed admission per release stays, but clients no longer see it: the target groups marked the box unhealthy during the drain, keep it unhealthy through the restart (refused checks, then 503 while admission is closed), and need two passing checks after admission opens. The other targets carry the traffic, on the flagship US region the two group members, for about two to three minutes per release. |
| + |
| +## 7. Unplanned stops |
| + |
| +Unchanged, and stated so the guarantee is not read wider than it is. |
| + |
| +- **The agent crashes or is killed.** systemd restarts it after 1 s (`Restart=always`). The kernel resets its connections. Until the target groups have seen two failed checks, new flows get connection refused and then, once the new agent listens, 503 `Retry-After: 10` from closed admission. W6 measured 24 s of that. The drain unit is stopped because its edge stopped (`BindsTo=`), finds the socket dead and exits at once. |
| +- **The instance dies.** As today: the target groups mark it unhealthy after two failed checks; HA hosts follow §9. |
| +- **The edge is wedged but alive.** The health answer fails on its own conditions (`internal/lbhealth/lbhealth.go:154-178`). With the change in §8, connections already open to it are no longer reset at the unhealthy mark; they stay up to 180 s or until the box closes them. That is the cost of §8. |
| + |
| +## 8. Target group and IAM changes |
| + |
| +**Target groups.** In `infra/modules/region-host/ingress/main.tf:97-116`, both target groups: |
| + |
| +``` |
| +target_health_state { |
| + enable_unhealthy_connection_termination = false |
| + unhealthy_draining_interval = 180 |
| +} |
| +``` |
| + |
| +Why: the NLB default resets a target's connections the moment it turns unhealthy: "the load balancer sends a TCP RST for packets received on the client connections associated with the target" (AWS, target group health checks). A request in flight on such a connection at the unhealthy mark would fail, and the box cannot act at that exact moment. With termination off, the target is `unhealthy.draining` for the draining interval: it "supports existing connections and will not accept any new connections". The interval must outlast the whole drain, with no credit for time before the mark: the 90 s cap, the 10 s settle and the 30 s wait are 130 s, so 180 s leaves 50 s of margin. A box already not healthy when the drain starts gets `unverified` (§4.2 step 2), because its retention may already be running. The draining interval can be set only when termination is off. Both names are in the AWS provider 6.x schema. |
| + |
| +Cost: no money; target group attributes are free and health checks are not billed. Behaviour: for the wedged-but-alive case in §7, and for an in-service group member that turns unhealthy, clients with a connection already open to the sick box keep it up to 180 s instead of being reset at once. New connections go elsewhere at the mark either way. A dead process or instance resets or drops its connections itself. |
| + |
| +**Box role, fixed boxes only.** `elasticloadbalancing:DescribeTargetHealth` and `elasticloadbalancing:DescribeTargetGroupAttributes`, read-only. The operator policy already carries it (`infra/modules/region-host/group_operator.tf:68`). ELB's Describe actions do not take resource-level permissions, so the statement's resource is `*`; the plan confirms this against the service authorization reference and narrows it if the action does take a target group ARN. What it reveals: the health of targets in the account's load balancers, which the box can already infer from its own requests. Requests: one per target group every 2 s during a drain, at most about 90 per planned stop, free. No ELB write right, as §12.2 requires. |
| + |
| +**Kept as is:** |
| +- **Interval 10 s, thresholds 2 and 2.** Interval 5 s would halve the crash gap in §7 to roughly 12 s, but would also let a group member be marked unhealthy and replaced through the group's ELB health check after 10 s of failed checks instead of 20. Not changed without a measurement; a possible follow-up. |
| +- **Deregistration delay 30 s.** It applies to deregistering targets (Standby, §25), not unhealthy ones. |
| +- **Fail-open.** "If all targets fail health checks at the same time in all enabled Availability Zones, the load balancer fails open." Draining the last healthy target changes nothing for clients; the drain reports `unverified: no other healthy target` (§4.2 step 2). |
| + |
| +**Rollout.** The module changes ship in this repo. Applying them is an operator step per deployment: the dev pinfra stack and carloku-infrastructure for the flagship, each on its own card, which also add `CARLOS_INGRESS_TARGET_GROUPS` to the attached fixed boxes' host-env parameters. The target group change is in place; no target is re-registered. Order on each card: apply the target group attributes and the role first, check them with `aws elbv2 describe-target-group-attributes`, and only then add `CARLOS_INGRESS_TARGET_GROUPS`. Until the key is present a box's drain is `not_armed`. If the key arrives first anyway, the drain reads the attributes itself and reports `unverified: target group retention` (§4.2 step 2), never `withdrawn`. |
| + |
| +## 9. Tests |
| + |
| +- **lbhealth:** `ingress-drain` fails the answer and is listed in order; the zero value is unchanged. |
| +- **Arming:** not armed without region HA, without the key, or on a group member (`group_member`). |
| +- **The drain state machine** (`internal/host`, fake clock, fake edge, fake target health): `withdrawn` when both target groups report `unhealthy` or `unhealthy.draining` with a healthy peer, after the 10 s settle and not before, and not if a state flips back during it; `draining` and `unused` never count; `unverified: target group retention` when an attribute is wrong; `unverified: not healthy at start`; the healthy-peer count from an unfiltered read, with a healthy peer and with the last healthy target; `unverified` at the 90 s cap when one stays healthy; `unverified` on read errors, naming them; `unverified: no other healthy target`; join; the 3-minute exit after step 3; nothing changes when a caller goes away before step 3. |
| +- **Edge, step 1 and step 3:** a request during step 1 is served (200) with `Connection: close`; across step 3, an HTTP/1 request already in flight and an HTTP/2 stream already open both complete; an HTTP/2 client gets GOAWAY and its next request opens a new connection; a connection accepted before step 3 with partial headers is closed without an answer (the refusal in §3, pinned so a Go upgrade that changes it is noticed); a request still running at the 30 s bound is cancelled and counted; edge-held SSE streams are closed at the start of the wait, and a proxied SSE response or WebSocket runs until the bound and is then cut and counted; the serve loops exit without `log.Fatal`; the later SIGTERM shutdown returns at once. |
| +- **Guard:** the ingress drain refuses to start during a §25 connection drain, and the reverse. |
| +- **Healthy only once admitted:** a box restarted with admission closed answers 503 on `/.carlos/lb-health` until admission opens, with every lbhealth condition otherwise passing (pins `internal/edge/lbhealth.go:34-49`). |
| +- **Units:** every tenant unit in `internal/host/units` (`BindsTo=carlos-edge.service`, the drain unit excluded) has `Before=carlos-edge-drain.service`; the edge has `Upholds=carlos-edge-drain.service`; the drain unit's `ExecStop` has the `-` prefix and `TimeoutStopSec=150`. |
| +- **`__ingress-drain`:** exits 0 when the socket is absent, refuses, answers 404 (old agent) or times out; prints the report on success. |
| +- **The verbs:** `apply` and `rollback` ask for the drain after their preflight and before the quiesce and the binary swap; not on a refusal or a same-release no-op; a 404 is logged and the verb goes on. Fakes as in `systemapply`'s tests. |
| +- **Root runner, real systemd** (the `TestRootHATerminateRelease` harness, §9.9), with a fake target-health adapter that turns `unhealthy` 10 s after the drain starts: on a box with one awake tenant serving a request loop through the edge, `systemctl restart carlos-edge` shows, from journal timestamps, the drain's `ExecStop` **ending** before the tenant unit's first stop command and before the edge's SIGTERM, with the request loop at 0 failures until step 3; the drain unit active again after the restart; the same after an automatic restart following `systemctl kill -s KILL` of the agent, where the drain exits within 1 s; a reboot runs the drain first; `carlos system rollback` from a W6 build to a pre-W6 build drains before the swap; a pre-W6 to W6 apply with a forced gate failure rolls back undrained, as §5.3 states, and leaves the box serving. |
| +- **Tofu:** the ingress module's committed test plans the two `target_health_state` attributes on both target groups, and the fixed-box role carries the read statement only when the module is told the box is attached to target groups. |
| + |
| +## 10. Dev witness |
| + |
| +After a release Paul schedules, and after the dev target group, role and host-env changes are applied. The W6 probe (same rate, same app on the group members, through the NLB) runs throughout, plus a slow-request probe: a 10 s POST with a 1 MiB body every 5 s, and a 10 s download every 5 s. |
| + |
| +1. **Planned restart, the finish line.** `systemctl restart carlos-edge` on leo. Pass: **0 failed requests** on both probes, every acknowledged write stored, SSE reconnects with no gaps, drain verdict `withdrawn`. Record the drain report from the journal, and leo's target states from `aws elbv2 describe-target-health` polled every 2 s from docs-t1 (read-only, dev profile). |
| +2. **A roll and a rollback.** Two distinct builds that both carry W6, A (running) and B: `carlos system apply` of B onto leo, check the running build is B, then `rollback`, check it is A again. Same pass rule each. (An apply of the release already installed restarts nothing, `internal/host/systemapply.go:489`, and proves nothing.) |
| +3. **Unplanned, recorded only.** `systemctl kill -s KILL carlos-edge` on leo under the probe. Expect today's numbers (about 24 s of errors). Not a failure; it documents §7. |
| +4. **Flagship, observed only.** No flagship action is part of this spec. The first flagship release after the flagship changes are applied is watched on adi with the existing heartbeat helpers; zero errors on the US ingress is expected. |
| + |
| +## 11. Open questions for Paul |
| + |
| +1. **The target group change (§8):** turn off connection termination on unhealthy targets, with a 180 s draining interval. Cost: a wedged-but-alive box keeps its existing connections up to 180 s instead of having them reset. I recommend it; without it a request in flight at the unhealthy mark can still fail. |
| +2. **A read-only ELB right on fixed boxes (§8):** `DescribeTargetHealth` and `DescribeTargetGroupAttributes`, so the drain reads the target groups' verdict instead of guessing from time. I recommend it. |
| +3. **Health check interval:** keep 10 s. I recommend keeping it. |
| +4. **Planned stops get slower:** every planned edge stop on an attached fixed box takes roughly 30 to 60 s longer, up to 2 minutes at worst, including reboots, and the box's own hosts are unreachable for that extra time (§3). I recommend accepting it. |
| + |
| +## 12. Astra round 1 and where it went |
| + |
| +`~/.cache/w6-fixed-edge/ASTRA-R1.md`: NOT READY, 5 P1, 3 P2. |
| + |
| +| Finding | Disposition | Where | |
| +|---|---|---| |
| +| R1.1 P1 quiet does not prove withdrawal | Accepted: the box reads its target health (read-only IAM) and reports `withdrawn` or `unverified`; the guarantee needs `withdrawn`. The quiet signal is cut. | §3, §4.2 step 2, §8 | |
| +| R1.2 P1 HTTP/2 and late first requests escape the snapshot | Accepted: step 3 is Go's `Shutdown` on both servers, which is protocol-aware; the request-id snapshot is cut. | §4.2 step 3, §9 | |
| +| R1.3 P1 long ordinary requests | Accepted: the guarantee names the 30 s connection wait; slow-request probe added. | §3, §10 | |
| +| R1.4 P1 rollback runs the old helper | Accepted: `apply` and `rollback` drain through their own binary before the swap. | §5.3 | |
| +| R1.5 P1 members replaced by the ASG | Accepted: fixed boxes only; members answer `group_member`. | §4.1 | |
| +| R1.6 P2 Task 3 instruments the wrong path | Moot: the client-connection classification is cut with the quiet signal. | §4.2 | |
| +| R1.7 P2 ordering test checks the start, lint includes the drain unit | Accepted. | §5.2, §9 | |
| +| R1.8 P2 census missing from the plan | Accepted. | plan Task 11 | |
| + |
| +## 13. Astra round 2 and where it went |
| + |
| +`~/.cache/w6-fixed-edge/ASTRA-R2.md`: NOT READY, 3 P1, 4 P2. R2.1 and R2.2 repeat round 1's families (accepted-connection coverage, withdrawal evidence), so under stopping rule 2 rev 3 refuses up front and states the narrower claim instead of another mechanism. |
| + |
| +| Finding | Disposition | Where | |
| +|---|---|---| |
| +| R2.1 P1 `Shutdown` closes a connection with incomplete headers | Refused up front: coverage is requests dispatched before step 3; pinned by a test. | §3, §4.2 step 3, §9 | |
| +| R2.2 P1 `draining` plus 5 s is not proof | `draining`/`unused` excluded; only `unhealthy` states with a healthy peer, held through a 10 s settle. The zero is a measured target, not a proof. | §3, §4.2 step 2 | |
| +| R2.3 P1 retention arithmetic | Interval 180 s over the whole 130 s drain, no credit before the mark; a box not healthy at start is `unverified`. | §4.2 step 2, §8 | |
| +| R2.4 P2 filtered reads cannot count peers | Unfiltered reads; peers counted from the same response. | §4.2 step 2, §9 | |
| +| R2.5 P2 host-env allowlist | Plan Task 8 adds the key to `internal/hostenv`'s allowlist with validation and tests. | plan | |
| +| R2.6 P2 rollout before attributes | Card order fixed; the drain reads the attributes and reports `unverified` if they are wrong. | §4.2 step 2, §8 | |
| +| R2.7 P2 roll witness was a no-op | Two distinct builds; running build checked. | §10 | |
| + |
| +## 14. Astra round 3 (final) and where it went |
| + |
| +`~/.cache/w6-fixed-edge/ASTRA-R3.md`: READY AFTER FIXES, no P1, 2 P2. All round 1 and 2 findings closed for the narrowed claim except R1.4's remainder, which is R3.1. Applied in rev 4 without a fourth round. |
| + |
| +| Finding | Disposition | Where | |
| +|---|---|---| |
| +| R3.1 P2 automatic rollback by a pre-W6 process is undrained | Stated as an exclusion; transition test added. | §5.3, §9 | |
| +| R3.2 P2 selective early stream cancellation needs new tracking | Cut: only edge-held SSE streams close early (already tracked); other streams end at the 30 s bound. | §4.2 step 3, §9 | |