region HA P3b T3: review fixes for boot and fixed-box departures
Restart chrony and verify the Amazon source before synchronization; bind boot SSM queue selection to the rendered queue. Distinguish cancelled launch contexts, preserve fixed-mode marker handling and departure acknowledgments, and cover group ingress and departure controller gates directly. Validated covering Go tests, focused race tests, build, vet, Darwin/Windows cross-builds and 42 OpenTofu 1.13.1 mock tests. Task 3 review remains closed at round 1; integrated census approval stays with the controller.
Co-Authored-By: GPT-6 Astra (codex) <noreply@openai.com>
infra/modules/region-host/group-init.sh.tftpl+18 −1internal/edge/group_admission_external_test.go+64 −1internal/host/agent.go+1 −1internal/host/group_admission.go+5 −1internal/host/group_admission_fix_test.go+11 −1internal/host/group_boot.go+17 −2internal/host/group_boot_test.go+138 −0internal/host/group_departure_test.go+146 −0internal/host/group_receipt.go+15 −2internal/host/group_receipt_test.go+50 −0
Intent
<task-notification> <task-id>b1f8wbll3</task-id> <tool-use-id>toolu_01WXptoxbBp3KM1Z4wyJ6QCq</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/05c816f1-0a2d-43e3-9285-de8352549786/tasks/b1f8wbll3.output</output-file> <status>completed</status> <summary>Background command "D=/home/paulca/amadan.net/carlos/platform/.claude/worktrees/region-ha-p3b-build/.superpowers/sdd/2026-11-04-region-ha-p3b-group; $D/wait-astra.sh t1f1 $D/task-1-report.md" completed (exit code 0)</summary> </task-notification>
<task-notification> <task-id>a9350e8356db7612d</task-id> <tool-use-id>toolu_01N7za9jQvcNfjuK8wSB1Nba</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/05c816f1-0a2d-43e3-9285-de8352549786/tasks/a9350e8356db7612d.output</output-file> <status>completed</status> <summary>Agent "Re-review Task 1 fix round 1" finished</summary> <note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note> <result>Round 2 passes: all seven findings in scope are fixed, and the fix diff (4573a815..9dfeecab) introduces no new P1 or P2. I ran one focused overlay test, wrote the scratch file under `$TMPDIR` and removed it afterwards. I re-ran no suites and changed nothing in the worktree. The full review is at `/home/paulca/amadan.net/carlos/platform/.claude/worktrees/region-ha-p3b-build/.superpowers/sdd/2026-11-04-region-ha-p3b-group/task-1-review-r2.md`. **Findings in scope** - **P1-1: ADDRESSED.** `internal/host/systemleg.go:331-343` now checks group evidence before fold quality. A box that has never seen a group permits updates even when the fold is nil, stale or incomplete. Two in-memory latches stay set once a group is seen: - the fold's latch in `internal/edge/homemap.go:514-523, 561-563, 582-584, 612`, which is set from a group-shaped key before the read, so it survives a corrupt or missing first file; - the update leg's own latch. The witnesses cover every case the dispatch listed: `systemleg_test.go:396` and `edge/group_readers_test.go:98`. - **P2-1: ADDRESSED.** The local claim now carries its stamp and lifetime (`edge.go:2012`). When no claim has admission fields, a box serves its own exact alias (`nameauthority.go:113-122`). On legacy data no request can reach the unguarded Held branch, because address-less rows become certificate-class (`homemap.go:883-890`). - **P2-2: ADDRESSED.** On legacy data, signed-hop, door and failed-backhaul requests fall through to the local answer as before (`edge.go:2021, 2035-2038`). The stale comment is replaced, and four witnesses cover the cases (`group_names_test.go:20`). - **P2-3: ADDRESSED.** A closed catch-all now holds its children: a child with no other claimant gets 503 with Retry-After 10 and no holder header. An eligible catch-all, local or peer, still wins (`nameauthority.go:77-102`). Witness: `group_names_test.go:109`. - **P2-4: ADDRESSED.** The census now fingerprints each producer function instead of whole files (`internal/host/group_names_test.go:279-337`). Residual P3-a below. - **P3-2: ADDRESSED.** `IsGroupReference` (`snapshot.go:395`) matches exactly `g-` plus 20 lowercase hex digits, so `g-web` no longer counts. - **P3-4: ADDRESSED.** The fallback that built claims from hand-made snapshots is gone (`homemap.go:1122-1130`). **New breakage in the fix diff (P1/P2):** none. **P3s (none block):** - **P3-a** (same family as R1 P2-4, census maintainability): two hashed producer functions are still very large: `*Edge.Reload` is about 571 lines and `edgesFileWriteClaims` about 461. My overlay test showed that adding only a comment inside a producer changes its hash, because of the blank line the stripped comment leaves. - **P3-b** (same family as R1 P1-1, T1 update path): the latch lives only in memory, so after a restart a box on a group fleet permits an old target until its first fold. This is within the controller's ruling, so Task 8's preflight must be in place before group mode is switched on. - **P3-c** (same family as R1 P2-1, H4/A1): an unrelated admission-aware peer catch-all `*.parent` switches off the "serve your own alias" rule for `x.parent`. This is group mode only, and both boxes pick the same owner, so requests do not bounce between them. - **P3-d** (same family as R1 P2-1, H4/A1): the local box's admission status is read from its own published file, not from its live state. A group box keeps the legacy alias rule until its first edges write reaches the fold. - **P3-e** (T1 / reader gate): `noteGroupPublisher` marks the reader fold incomplete during every refresh, not only the first one. On a group fleet this only delays checks that already retry. Verdict: **PASS**. 7/7 in scope addressed; new P1 0, new P2 0, P3 5.</result> <usage><subagent_tokens>103369</subagent_tokens><tool_uses>19</tool_uses><duration_ms>289571</duration_ms></usage> </task-notification>
<task-notification> <task-id>bqwioi7i5</task-id> <tool-use-id>toolu_0116TFM5MMxG565YXpNNxP4j</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/05c816f1-0a2d-43e3-9285-de8352549786/tasks/bqwioi7i5.output</output-file> <status>completed</status> <summary>Background command "D=/home/paulca/amadan.net/carlos/platform/.claude/worktrees/region-ha-p3b-build/.superpowers/sdd/2026-11-04-region-ha-p3b-group; $D/wait-astra.sh t3 $D/task-3-report.md" completed (exit code 0)</summary> </task-notification>
<task-notification> <task-id>a07b619232f539365</task-id> <tool-use-id>toolu_01C4gwMuXcaD2ftPu6bkMgZu</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/05c816f1-0a2d-43e3-9285-de8352549786/tasks/a07b619232f539365.output</output-file> <status>completed</status> <summary>Agent "Review Task 3 (spec + quality)" finished</summary> <note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note> <result>**Verdict: Approved.** Round 1 found no P1, so the review stops here under the AGENTS.md rules. It found 0 P1, 1 P2 and 8 P3 issues. I'd still fix the P2 before any live group boot. The full review is at `/home/paulca/amadan.net/carlos/platform/.claude/worktrees/region-ha-p3b-build/.superpowers/sdd/2026-11-04-region-ha-p3b-group/task-3-review-r1.md`. I ran one focused check: a group config file written by the boot script's Python code parses cleanly in the Go loader (`ParseGroupConfig`). The two languages compute the config's checksum the same way, which no existing test covered. I ran it through `go test -overlay` and removed the scratch files; the worktree is unchanged at HEAD 43177b60. **P2** - **P2-1 (I1 clock source, boot order):** the chrony time source is never loaded on the first boot. `apt-get install chrony` starts chronyd before the config file is written. The later `systemctl enable --now chrony.service` does nothing to a running service, so `chronyc waitsync` checks against the distribution's default time sources (`group-init.sh.tftpl:60,103-107`). The fix is to restart chrony after writing the file and assert the 169.254.169.123 source is active before `waitsync`. **P3** - **P3-1 (T1/N-HA14):** bootstrap starts `carlos-adopt.timer`, `carlos-restart.path` and `carlos-system-update.path` on group boxes before Task 4's root restart guard exists. `Restart=no` only stops systemd's automatic restarts, not a root unit restarting the agent. This must go into Task 4's acceptance. - **P3-2 (I3/I6):** the boot queue URL read from SSM is never compared with the queue URL tofu renders into the same script. A mis-seeded value could point group members at a fixed box's queue. One equality check in the boot script closes it. - **P3-3:** a cancelled context is reported as `group_launch_deadline_passed` (`group_receipt.go:93`). - **P3-4 (fixed-box byte-identity):** the agent, bootstrap and install-channel now read the group config file on every box. Any read error other than file-not-found, such as permission denied on a hand-built `/etc/carlos`, now stops a fixed box's agent. - **P3-5 (E1, availability):** a credential or connection failure before the completion request is sent is treated as "outcome unknown". The member then stays closed until health checks replace it. This is safe but wastes a box. - **P3-6:** test gaps. - The boot-order test only checks stage comment headings, not the commands under them. - The tenant-start paths have no group-mode (non-nil launch) test variant. - The departure controller's `step` and `complete` paths are only tested indirectly while closed. - **P3-7 (I3/I6, E1):** fixed boxes that opted into admission with a drain or platform role now never acknowledge their departure messages. Each message is redelivered every 120 seconds indefinitely. - **P3-8:** the boot script depends on the AMI. Risks are a missing timer failing `set -e`, a dpkg lock or interrupted-install race, and `timeout` not killing child processes. All fail closed. Also, Debian AMIs lack amazon-ssm-agent, which Task 7's Session Manager maintenance needs. The rest of the brief is met and wired into production code: - **Launch completion:** completion goes through the real admission path. The four-attempt budget and the "outcome unknown" state persist across agent restarts, closing admission wins during an in-flight call, and root never reads the receipt. - **Departure gating:** a closed member only records departure messages. It never imports duties or acknowledges a message. - **Install floor:** the check refuses when only one half is present or a read fails. - **Boot queue override:** the boot queue overrides a copied fixed queue, with a test. - **Fixed boxes:** fixed host.env allowlists are unchanged. I could not confirm two points: - The 30-second healthy-consumer startup budget does not appear in this diff. - The tenant-start paths are covered only by the existing fixed-mode tests.</result> <usage><subagent_tokens>248942</subagent_tokens><tool_uses>54</tool_uses><duration_ms>784306</duration_ms></usage> </task-notification>
<task-notification> <task-id>bmd4170w2</task-id> <tool-use-id>toolu_01NCwZSmsh7VojPfJgnZs5TJ</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/05c816f1-0a2d-43e3-9285-de8352549786/tasks/bmd4170w2.output</output-file> <status>completed</status> <summary>Background command "D=/home/paulca/amadan.net/carlos/platform/.claude/worktrees/region-ha-p3b-build/.superpowers/sdd/2026-11-04-region-ha-p3b-group; $D/wait-astra.sh t4 $D/task-4-report.md" completed (exit code 0)</summary> </task-notification>
Attributed to this commit: 59.5 g CO₂e (7,041,446 tokens). This is an attribution, not a measurement — usage counted from this commit's own marker forward to the next one on region-ha-p3b-build, 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/infra/modules/region-host/group-init.sh.tftpl b/infra/modules/region-host/group-init.sh.tftpl| index 57de1c142..2c90627bc 100644 |
| --- a/infra/modules/region-host/group-init.sh.tftpl |
| +++ b/infra/modules/region-host/group-init.sh.tftpl |
| @@ -103,7 +103,22 @@ nft list table inet carlos_group_imds >/dev/null |
| # configure chrony |
| printf '%s\n' 'server 169.254.169.123 prefer iburst minpoll 4 maxpoll 4' > /run/carlos-group-boot/chrony.conf |
| install -o root -g root -m 0644 /run/carlos-group-boot/chrony.conf /etc/chrony/conf.d/carlos-group.conf |
| -systemctl enable --now chrony.service |
| +systemctl enable chrony.service |
| +systemctl restart chrony.service |
| +python3 - <<'PYCHRONY' |
| +import subprocess, time |
| +for attempt in range(20): |
| + try: |
| + sources = subprocess.check_output(['chronyc', '-n', 'sources'], text=True, timeout=2) |
| + except (subprocess.CalledProcessError, subprocess.TimeoutExpired): |
| + sources = '' |
| + if any(len(fields) >= 2 and fields[0] in ('^*', '^+') and fields[1] == '169.254.169.123' |
| + for fields in (line.split() for line in sources.splitlines())): |
| + break |
| + time.sleep(1) |
| +else: |
| + raise SystemExit('group_boot_clock_source') |
| +PYCHRONY |
| chronyc waitsync 20 2 |
| # fetch verified bootstrap |
| @@ -128,6 +143,8 @@ params = response.get('Parameters', []) |
| if response.get('InvalidParameters') or len(params) != len(names) or {p['Name'] for p in params} != set(names): |
| raise SystemExit('group_boot_parameters') |
| values = {p['Name']: p['Value'] for p in params} |
| +if values[names[2]] != E['CARLOS_TERMINATION_QUEUE_URL']: |
| + raise SystemExit('group_boot_queue') |
| obj = json.loads(values[names[0]]) |
| if set(obj) != {'key', 'version', 'known_readers', 'deployment_aws_region'} or not isinstance(obj['known_readers'], list) or len(obj['known_readers']) > 1000: |
| raise SystemExit('group_boot_object') |
diff --git a/internal/edge/group_admission_external_test.go b/internal/edge/group_admission_external_test.go| index cddba0d00..b45f70eca 100644 |
| --- a/internal/edge/group_admission_external_test.go |
| +++ b/internal/edge/group_admission_external_test.go |
| @@ -2,22 +2,38 @@ package edge_test |
| import ( |
| "context" |
| + "errors" |
| "github.com/carlosframework/platform/internal/activator" |
| "github.com/carlosframework/platform/internal/edge" |
| + "github.com/carlosframework/platform/internal/groupadmission" |
| "github.com/carlosframework/platform/internal/registry" |
| + "net/http" |
| + "net/http/httptest" |
| "sync/atomic" |
| "testing" |
| ) |
| type admissionBackend struct { |
| activator.Backend |
| - acquires atomic.Int32 |
| + acquires, starts, restores atomic.Int32 |
| } |
| func (b *admissionBackend) Acquire(context.Context, registry.Route) (activator.Lease, error) { |
| b.acquires.Add(1) |
| return nil, activator.ErrTenantAdmission |
| } |
| +func (b *admissionBackend) Start(context.Context, registry.Route) (activator.Proc, string, error) { |
| + b.starts.Add(1) |
| + return nil, "", activator.ErrTenantAdmission |
| +} |
| +func (b *admissionBackend) StartWorker(context.Context, registry.Route, map[string]string) (activator.Proc, string, error) { |
| + b.starts.Add(1) |
| + return nil, "", activator.ErrTenantAdmission |
| +} |
| +func (b *admissionBackend) Restore(context.Context, registry.Route) (bool, error) { |
| + b.restores.Add(1) |
| + return false, activator.ErrTenantAdmission |
| +} |
| func TestAdmissionAllUnhealthyNLB(t *testing.T) { |
| b := &admissionBackend{} |
| a := activator.New(activator.Config{}, b, nil) |
| @@ -48,3 +64,50 @@ func TestAdmissionShutdownOrder(t *testing.T) { |
| t.Fatal("activator shutdown did not close") |
| } |
| } |
| + |
| +type groupCompletionFunc func(context.Context, groupadmission.Launch) error |
| + |
| +func (f groupCompletionFunc) Complete(ctx context.Context, l groupadmission.Launch) error { |
| + return f(ctx, l) |
| +} |
| +func TestGroupAdmissionAllIngress(t *testing.T) { |
| + for _, missing := range []string{"env", "reconcile", "publication", "consumer"} { |
| + t.Run(missing, func(t *testing.T) { |
| + var state groupadmission.State |
| + facts := groupadmission.Facts{EnvLoaded: true, Reconciled: true, RolePublished: true, TerminationStarted: true} |
| + switch missing { |
| + case "env": |
| + facts.EnvLoaded = false |
| + case "reconcile": |
| + facts.Reconciled = false |
| + case "publication": |
| + facts.RolePublished = false |
| + case "consumer": |
| + facts.TerminationStarted = false |
| + } |
| + state.Observe(facts) |
| + launch := &groupadmission.Launch{Group: "group", Hook: "initial", Instance: "i-0123456789abcdef0"} |
| + complete := groupCompletionFunc(func(context.Context, groupadmission.Launch) error { |
| + t.Error("completion with facts withheld") |
| + return nil |
| + }) |
| + if err := state.Admit(t.Context(), launch, complete, func() bool { return true }); !errors.Is(err, groupadmission.ErrNotReady) { |
| + t.Fatalf("admit: %v", err) |
| + } |
| + b := &admissionBackend{} |
| + svc := activator.New(activator.Config{}, b, nil) |
| + svc.TenantAdmittedFunc, svc.TenantStartAllowed = state.Admitted, state.Admitted |
| + edge.AdmissionIngressWitness(t, svc) |
| + rt := registry.Route{Host: "worker.example.com", Kind: "sidecar", Status: "ready"} |
| + if err := svc.WakeWorker(rt); !errors.Is(err, activator.ErrTenantAdmission) { |
| + t.Fatalf("worker: %v", err) |
| + } |
| + rt.Kind, rt.Hibernate, rt.Socket = "instance", true, "unused.sock" |
| + w := httptest.NewRecorder() |
| + svc.ServeScheduled(w, httptest.NewRequest("POST", "https://"+rt.Host+"/job", nil), rt, http.HandlerFunc(func(http.ResponseWriter, *http.Request) { t.Error("timer delivered") })) |
| + if w.Code != 503 || b.acquires.Load() != 0 || b.starts.Load() != 0 || b.restores.Load() != 0 { |
| + t.Fatalf("timer=%d acquires=%d starts=%d restores=%d", w.Code, b.acquires.Load(), b.starts.Load(), b.restores.Load()) |
| + } |
| + }) |
| + } |
| +} |
diff --git a/internal/host/agent.go b/internal/host/agent.go| index 703f6eea4..1d2a4ed19 100644 |
| --- a/internal/host/agent.go |
| +++ b/internal/host/agent.go |
| @@ -623,7 +623,7 @@ func runAgent(args []string, buildClaims ClaimFactory) { |
| }, reg) // the registry satisfies activator.DueStore directly |
| svc.DutyStore = reg |
| admissionOption = wireAgentAdmission(admission, svc, eb, func() hadeparture.Lifecycle { |
| - departures, departureLife, err = armHADepartures(agentCtx, departureArm{Admitted: func() bool { return admission == nil || admission.startAllowed() }, BeginWork: admission.beginDepartureWork, Getenv: os.Getenv, Registry: reg, Service: svc, Backend: eb, Confirmer: confirmer, Inventory: boxDepartureInventory, OpenStore: openDeployStore}) |
| + departures, departureLife, err = armHADepartures(agentCtx, departureArm{Admitted: admission.departureAllowed, BeginWork: admission.beginDepartureWork, Getenv: os.Getenv, Registry: reg, Service: svc, Backend: eb, Confirmer: confirmer, Inventory: boxDepartureInventory, OpenStore: openDeployStore}) |
| if err != nil { |
| log.Printf("ha_departure_init code=unavailable") |
| } |
diff --git a/internal/host/group_admission.go b/internal/host/group_admission.go| index 07269e836..6948c9454 100644 |
| --- a/internal/host/group_admission.go |
| +++ b/internal/host/group_admission.go |
| @@ -202,7 +202,7 @@ func (a *fixedAdmission) Close() { |
| // Work is registered before mutation; shutdown closes admission, cancels and |
| // joins registered import/ack operations before consumer shutdown proceeds. |
| func (a *fixedAdmission) beginDepartureWork(parent context.Context) (context.Context, func(), bool) { |
| - if a == nil { |
| + if a == nil || !a.group { |
| return parent, func() {}, true |
| } |
| a.workMu.Lock() |
| @@ -350,3 +350,7 @@ func cachedGroupReaders() edgesfile.ReaderSnapshot { |
| } |
| return edgesfile.ReaderSnapshot{} |
| } |
| + |
| +func (a *fixedAdmission) departureAllowed() bool { |
| + return a == nil || !a.group || a.startAllowed() |
| +} |
diff --git a/internal/host/group_admission_fix_test.go b/internal/host/group_admission_fix_test.go| index cf501cd6e..195058a70 100644 |
| --- a/internal/host/group_admission_fix_test.go |
| +++ b/internal/host/group_admission_fix_test.go |
| @@ -76,9 +76,19 @@ func openAdmission(t *testing.T, a *fixedAdmission) { |
| t.Fatal("admission did not open") |
| } |
| } |
| -func TestPreAdmissionAgentWiring(t *testing.T) { |
| +func TestPreAdmissionAgentWiring(t *testing.T) { testPreAdmissionAgentWiring(t, false) } |
| +func TestGroupPreAdmissionAgentWiring(t *testing.T) { testPreAdmissionAgentWiring(t, true) } |
| +func testPreAdmissionAgentWiring(t *testing.T, group bool) { |
| _, svc, b, rt := admissionWorkerFixture(t) |
| a := newFixedAdmission(admissionEnv, admissionHealth()) |
| + if group { |
| + a = readyGroupAdmission(t) |
| + a.completer = groupCompleteFunc(func(context.Context, groupadmission.Launch) error { |
| + t.Error("completion with facts withheld") |
| + return nil |
| + }) |
| + a.tick(t.Context()) |
| + } |
| eb := &activator.ExecBackend{ConfigGate: func(context.Context, registry.Route) error { return errors.New("unexpected backend work") }} |
| opt := wireAgentAdmission(a, svc, eb, func() hadeparture.Lifecycle { |
| if svc.TenantAdmitted() { |
diff --git a/internal/host/group_boot.go b/internal/host/group_boot.go| index 4c70c2f71..2e1d5c4ad 100644 |
| --- a/internal/host/group_boot.go |
| +++ b/internal/host/group_boot.go |
| @@ -9,6 +9,7 @@ import ( |
| "github.com/carlosframework/platform/internal/boxid" |
| "github.com/carlosframework/platform/internal/hostenv" |
| "github.com/carlosframework/platform/internal/rootaws" |
| + "log" |
| "os" |
| "strings" |
| "time" |
| @@ -39,10 +40,24 @@ func validateGroupSwitches(getenv func(string) string) error { |
| // Every production group entry proves the immutable marker and its companion |
| // configuration. A present marker cannot fall back to fixed mode via flags. |
| func loadGroupConfiguration(getenv func(string) string) (*hostenv.GroupConfig, error) { |
| - raw, err := hostenv.ReadGroupFile(hostenv.GroupConfigPath, 0, 0644) |
| - if errors.Is(err, os.ErrNotExist) && !groupReferenced(getenv) { |
| + return loadGroupConfigurationAt(getenv, hostenv.GroupConfigPath) |
| +} |
| + |
| +func loadGroupConfigurationAt(getenv func(string) string, marker string) (*hostenv.GroupConfig, error) { |
| + // Detect the leaf before checking protected parents: fixed boxes may have |
| + // an unrelated unsafe or unreadable /etc/carlos. Any visible marker, |
| + // including a dangling symlink, still requires strict group validation. |
| + _, statErr := os.Lstat(marker) |
| + if statErr != nil { |
| + if groupReferenced(getenv) { |
| + return nil, statErr |
| + } |
| + if !errors.Is(statErr, os.ErrNotExist) { |
| + log.Printf("group marker could not be inspected; continuing in fixed mode: %v", statErr) |
| + } |
| return nil, validateGroupSwitches(getenv) |
| } |
| + raw, err := hostenv.ReadGroupFile(marker, 0, 0644) |
| if err != nil { |
| return nil, err |
| } |
diff --git a/internal/host/group_boot_test.go b/internal/host/group_boot_test.go| index 9de60e57a..7e533a022 100644 |
| --- a/internal/host/group_boot_test.go |
| +++ b/internal/host/group_boot_test.go |
| @@ -2,10 +2,14 @@ package host |
| import ( |
| "context" |
| + "fmt" |
| "github.com/carlosframework/platform/internal/boxroles" |
| "github.com/carlosframework/platform/internal/edgesfile" |
| "github.com/carlosframework/platform/internal/groupadmission" |
| "os" |
| + "os/exec" |
| + "path/filepath" |
| + "strconv" |
| "strings" |
| "testing" |
| "time" |
| @@ -102,6 +106,7 @@ func TestGroupBootOrder(t *testing.T) { |
| if err != nil { |
| t.Fatal(err) |
| } |
| + assertGroupClockOrder(t, string(b)) |
| last := -1 |
| for _, s := range []string{"# disable unattended updates", "# harden metadata", "# configure chrony", "# fetch verified bootstrap", "# write immutable group configuration", "# install dormant hairpin", "# bootstrap and install channel", "# start guarded agent"} { |
| n := strings.Index(string(b), s) |
| @@ -117,6 +122,7 @@ func TestGroupInitNoAutoRestart(t *testing.T) { |
| t.Fatal(err) |
| } |
| s := string(b) |
| + assertGroupClockOrder(t, s) |
| for _, needle := range []string{"systemctl enable nftables.service", "/etc/nftables.conf", "Requires=nftables.service", "After=nftables.service"} { |
| if !strings.Contains(s, needle) { |
| t.Fatal("metadata gate must survive reboot", needle) |
| @@ -207,3 +213,135 @@ func TestGroupAdmissionFactsAndReceipt(t *testing.T) { |
| } |
| }) |
| } |
| + |
| +func assertGroupClockOrder(t *testing.T, s string) { |
| + t.Helper() |
| + last := -1 |
| + for _, command := range []string{ |
| + "apt-get -y -q install", "install -o root -g root -m 0644 /run/carlos-group-boot/chrony.conf", |
| + "systemctl restart chrony.service", "['chronyc', '-n', 'sources']", "chronyc waitsync 20 2", "response = aws('ssm'", |
| + } { |
| + n := strings.Index(s, command) |
| + if n <= last { |
| + t.Fatalf("missing or unordered command %s", command) |
| + } |
| + last = n |
| + } |
| +} |
| + |
| +func TestGroupBootQueueBinding(t *testing.T) { |
| + raw, err := os.ReadFile("../../infra/modules/region-host/group-init.sh.tftpl") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + s := string(raw) |
| + start, end := strings.Index(s, "values = {"), strings.Index(s, "obj = json.loads") |
| + if start < 0 || end <= start { |
| + t.Fatal("missing boot parameter validation") |
| + } |
| + for _, queue := range []string{"rendered-group-queue", "fixed-queue"} { |
| + t.Run(queue, func(t *testing.T) { |
| + setup := "E = {'CARLOS_TERMINATION_QUEUE_URL': 'rendered-group-queue'}\nnames = ['object', 'hash', 'queue']\nparams = [{'Name': 'queue', 'Value': " + strconv.Quote(queue) + "}]\n" |
| + cmd := exec.Command("python3", "-c", setup+s[start:end]) |
| + out, err := cmd.CombinedOutput() |
| + if queue == "rendered-group-queue" && err != nil { |
| + t.Fatalf("matching queue refused: %v %s", err, out) |
| + } |
| + if queue != "rendered-group-queue" && (err == nil || !strings.Contains(string(out), "group_boot_queue")) { |
| + t.Fatalf("foreign queue accepted: %v %s", err, out) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestGroupMarkerFixedMode(t *testing.T) { |
| + for _, mode := range []string{"absent", "present", "dangling", "parent-loop"} { |
| + for _, group := range []bool{false, true} { |
| + t.Run(fmt.Sprintf("%s/group=%t", mode, group), func(t *testing.T) { |
| + dir := t.TempDir() |
| + marker := filepath.Join(dir, "group.json") |
| + switch mode { |
| + case "present": |
| + if err := os.WriteFile(marker, []byte("{}"), 0644); err != nil { |
| + t.Fatal(err) |
| + } |
| + case "dangling": |
| + if err := os.Symlink(filepath.Join(dir, "absent"), marker); err != nil { |
| + t.Fatal(err) |
| + } |
| + case "parent-loop": |
| + parent := filepath.Join(dir, "loop") |
| + if err := os.Symlink(parent, parent); err != nil { |
| + t.Fatal(err) |
| + } |
| + marker = filepath.Join(parent, "group.json") |
| + } |
| + get := func(k string) string { |
| + if group && k == "CARLOS_BOX_REFERENCE" { |
| + return "group" |
| + } |
| + return "" |
| + } |
| + c, err := loadGroupConfigurationAt(get, marker) |
| + fixed := !group && (mode == "absent" || mode == "parent-loop") |
| + if fixed && (c != nil || err != nil) { |
| + t.Fatalf("fixed box refused: %v", err) |
| + } |
| + if !fixed && err == nil { |
| + t.Fatal("group marker bypassed") |
| + } |
| + }) |
| + } |
| + } |
| +} |
| + |
| +func TestGroupBootClockSource(t *testing.T) { |
| + raw, err := os.ReadFile("../../infra/modules/region-host/group-init.sh.tftpl") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + parts := strings.Split(string(raw), "python3 - <<'PYCHRONY'\n") |
| + if len(parts) != 2 { |
| + t.Fatal("missing bounded source check") |
| + } |
| + script := strings.SplitN(parts[1], "\nPYCHRONY", 2)[0] |
| + for _, source := range []string{"^* 169.254.169.123", "^+ 169.254.169.123", "^? 169.254.169.123", "^* 192.0.2.1", "timeout"} { |
| + t.Run(source, func(t *testing.T) { |
| + setup := `import subprocess, time |
| +calls = 0 |
| +sleeps = 0 |
| +def sources(args, text, timeout): |
| + global calls |
| + calls += 1 |
| + assert args == ['chronyc', '-n', 'sources'] and text and timeout == 2 |
| + if source == 'timeout': |
| + raise subprocess.TimeoutExpired(args, timeout) |
| + return source |
| +def sleep(seconds): |
| + global sleeps |
| + sleeps += 1 |
| + assert seconds == 1 |
| +subprocess.check_output = sources |
| +time.sleep = sleep |
| +` |
| + tail := ` |
| +try: |
| + exec(script) |
| +except SystemExit as err: |
| + assert str(err) == 'group_boot_clock_source' |
| + assert not active and calls == 20 and sleeps == 20 |
| +else: |
| + assert active and calls == 1 and sleeps == 0 |
| +` |
| + active := strings.HasPrefix(source, "^*") && strings.Contains(source, "169.254.169.123") || strings.HasPrefix(source, "^+") |
| + activeValue := "False" |
| + if active { |
| + activeValue = "True" |
| + } |
| + code := "source = " + strconv.Quote(source) + "\nscript = " + strconv.Quote(script) + "\nactive = " + activeValue + "\n" + setup + tail |
| + if out, err := exec.Command("python3", "-c", code).CombinedOutput(); err != nil { |
| + t.Fatalf("source check: %v %s", err, out) |
| + } |
| + }) |
| + } |
| +} |
diff --git a/internal/host/group_departure_test.go b/internal/host/group_departure_test.go| index bee7391bd..ccf75d13a 100644 |
| --- a/internal/host/group_departure_test.go |
| +++ b/internal/host/group_departure_test.go |
| @@ -2,11 +2,15 @@ package host |
| import ( |
| "context" |
| + "errors" |
| + "github.com/carlosframework/platform/internal/boxroles" |
| "github.com/carlosframework/platform/internal/groupadmission" |
| "github.com/carlosframework/platform/internal/hadeparture" |
| "github.com/carlosframework/platform/internal/hafresh" |
| "github.com/carlosframework/platform/internal/provision" |
| "github.com/carlosframework/platform/internal/registry" |
| + "os" |
| + "reflect" |
| "sync" |
| "sync/atomic" |
| "testing" |
| @@ -112,3 +116,145 @@ func TestGroupDepartureAdmission(t *testing.T) { |
| } |
| }) |
| } |
| + |
| +func TestAdmissionFixedDepartureAck(t *testing.T) { |
| + for _, role := range []boxroles.Role{boxroles.Serve, boxroles.Drain, boxroles.Platform} { |
| + t.Run(string(role), func(t *testing.T) { |
| + cfg, _, _ := departureArmFixture(t) |
| + a := newFixedAdmission(admissionEnv, admissionHealth()) |
| + if err := a.applyRole(role, true); err != nil { |
| + t.Fatal(err) |
| + } |
| + cfg.Admitted, cfg.BeginWork = a.departureAllowed, a.beginDepartureWork |
| + q := &groupHintQueue{message: hadeparture.Message{ID: "invalid", Receipt: "receipt", Body: []byte("invalid")}} |
| + cfg.MakeQueue = func(context.Context) (hadeparture.Queue, error) { return q, nil } |
| + c, life, err := armHADepartures(t.Context(), cfg) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer life.Stop(context.Background()) |
| + select { |
| + case <-life.Started(): |
| + case <-time.After(time.Second): |
| + t.Fatal("not started") |
| + } |
| + if q.deletes.Load() != 1 { |
| + t.Fatalf("fixed %s did not acknowledge before admission: %d", role, q.deletes.Load()) |
| + } |
| + a.observe(groupadmission.Facts{EnvLoaded: true, Reconciled: true, RolePublished: true, TerminationStarted: true}) |
| + a.tick(t.Context()) |
| + if !a.TenantAdmitted() { |
| + t.Fatal("fixed admission did not open") |
| + } |
| + if err := c.record(t.Context(), q.message); err != nil { |
| + t.Fatal(err) |
| + } |
| + if q.deletes.Load() != 2 { |
| + t.Fatalf("fixed %s did not acknowledge after admission", role) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestGroupDepartureStepAndComplete(t *testing.T) { |
| + for _, entry := range []string{"step", "complete"} { |
| + t.Run(entry, func(t *testing.T) { |
| + x := newScanRig(t, 1) |
| + x.c.cfg.Identities = &departureIdentities{Registry: x.r} |
| + a := readyGroupAdmission(t) |
| + x.c.cfg.Admitted, x.c.cfg.BeginWork = a.departureAllowed, a.beginDepartureWork |
| + var q *scanQueue |
| + if entry == "complete" { |
| + q = x.start(t, "receipt") |
| + scan, err := x.r.DepartureScan(t.Context(), x.d.ID) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + scan.Generation = departureInventoryDigest(x.inv) |
| + if err := x.r.SaveDepartureScan(t.Context(), x.d.ID, "scanning", scan); err != nil { |
| + t.Fatal(err) |
| + } |
| + scan.Version++ |
| + if err := x.r.SaveDepartureScan(t.Context(), x.d.ID, "authority_complete", scan); err != nil { |
| + t.Fatal(err) |
| + } |
| + } else { |
| + if err := x.r.RecordTermination(t.Context(), "invalid", []byte("invalid"), x.now); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + before, err := x.r.Departure(t.Context(), x.d.ID) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + scanBefore, err := x.r.DepartureScan(t.Context(), x.d.ID) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + run := func() error { |
| + if entry == "step" { |
| + return x.c.step(t.Context()) |
| + } |
| + return x.c.complete(t.Context(), x.d.ID) |
| + } |
| + err = run() |
| + if entry == "step" && err != nil { |
| + t.Fatal(err) |
| + } |
| + if entry == "complete" && !errors.Is(err, errDeparturePending) { |
| + t.Fatalf("closed complete: %v", err) |
| + } |
| + after, err := x.r.Departure(t.Context(), x.d.ID) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + scanAfter, err := x.r.DepartureScan(t.Context(), x.d.ID) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if q != nil && q.deleted.Load() != 0 { |
| + t.Fatal("closed completion acknowledged") |
| + } |
| + if !reflect.DeepEqual(before, after) || !reflect.DeepEqual(scanBefore, scanAfter) || x.imports != 0 || x.locks.reads != 0 { |
| + t.Fatal("closed controller changed departure or imported duties") |
| + } |
| + if _, _, err := x.store.Get(t.Context(), x.d.EdgesKey); err != nil { |
| + t.Fatalf("closed controller deleted evidence: %v", err) |
| + } |
| + if entry == "step" { |
| + rows, err := x.r.TerminationInbox(t.Context(), x.now.Add(time.Hour), 32) |
| + if err != nil || len(rows) != 1 { |
| + t.Fatalf("closed step changed journal: %v %v", rows, err) |
| + } |
| + } |
| + a.observe(groupadmission.Facts{TerminationStarted: true}) |
| + a.tick(t.Context()) |
| + if !a.startAllowed() { |
| + t.Fatal("not admitted") |
| + } |
| + if err := run(); err != nil { |
| + t.Fatal(err) |
| + } |
| + if entry == "step" { |
| + rows, err := x.r.TerminationInbox(t.Context(), x.now.Add(time.Hour), 32) |
| + if err != nil || len(rows) != 0 { |
| + t.Fatalf("admitted step did not process journal: %v %v", rows, err) |
| + } |
| + if x.imports != 1 || x.locks.reads == 0 { |
| + t.Fatalf("admitted step did not import: imports=%d reads=%d", x.imports, x.locks.reads) |
| + } |
| + } else { |
| + after, err := x.r.Departure(t.Context(), x.d.ID) |
| + if err != nil || after.Phase != "complete" { |
| + t.Fatalf("admitted completion: %+v %v", after, err) |
| + } |
| + if q.deleted.Load() != 1 { |
| + t.Fatalf("admitted completion acknowledgments=%d", q.deleted.Load()) |
| + } |
| + if _, _, err := x.store.Get(t.Context(), x.d.EdgesKey); !errors.Is(err, os.ErrNotExist) { |
| + t.Fatalf("admitted completion retained evidence: %v", err) |
| + } |
| + } |
| + }) |
| + } |
| +} |
diff --git a/internal/host/group_receipt.go b/internal/host/group_receipt.go| index 3cf40d0bd..09bd6c45e 100644 |
| --- a/internal/host/group_receipt.go |
| +++ b/internal/host/group_receipt.go |
| @@ -16,6 +16,7 @@ var errGroupLaunch = errors.New("group_launch_unacknowledged") |
| var errGroupLaunchUnknown = errors.New("group_launch_outcome_unknown") |
| var errGroupLaunchExhausted = errors.New("group_launch_attempts_exhausted") |
| var errGroupLaunchReceipt = errors.New("group_launch_receipt_invalid") |
| +var errGroupLaunchCancelled = errors.New("group_launch_cancelled") |
| var errGroupLaunchExpired = errors.New("group_launch_deadline_passed") |
| type groupReceiptBinding struct { |
| @@ -90,14 +91,23 @@ func (c *groupReceiptCompleter) completeLocked(ctx context.Context, l groupadmis |
| } |
| for j.Attempts < 4 { |
| now := c.now() |
| - if ctx.Err() != nil || !now.Before(time.Unix(j.Deadline, 0)) { |
| + if err := ctx.Err(); err != nil { |
| + return errors.Join(errGroupLaunchCancelled, err) |
| + } |
| + if !now.Before(time.Unix(j.Deadline, 0)) { |
| return errGroupLaunchExpired |
| } |
| if pause := time.Unix(0, j.Next).Sub(now); pause > 0 { |
| if err := c.wait(ctx, pause); err != nil { |
| + if ctx.Err() != nil { |
| + return errors.Join(errGroupLaunchCancelled, ctx.Err()) |
| + } |
| return err |
| } |
| } |
| + if err := ctx.Err(); err != nil { |
| + return errors.Join(errGroupLaunchCancelled, err) |
| + } |
| if !c.now().Add(2 * time.Second).Before(time.Unix(j.Deadline, 0)) { |
| return errGroupLaunchExpired |
| } |
| @@ -149,10 +159,13 @@ func decodeGroupReceipt(b []byte, out any) error { |
| } |
| func groupLaunchFailureCode(err error) string { |
| - for _, code := range []error{errGroupLaunchUnknown, errGroupLaunchExhausted, errGroupLaunchReceipt, errGroupLaunchExpired} { |
| + for _, code := range []error{errGroupLaunchUnknown, errGroupLaunchExhausted, errGroupLaunchReceipt, errGroupLaunchExpired, errGroupLaunchCancelled} { |
| if errors.Is(err, code) { |
| return code.Error() |
| } |
| } |
| + if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) { |
| + return errGroupLaunchCancelled.Error() |
| + } |
| return "group_launch_unacknowledged" |
| } |
diff --git a/internal/host/group_receipt_test.go b/internal/host/group_receipt_test.go| index 12ff7ac06..1ecfc3038 100644 |
| --- a/internal/host/group_receipt_test.go |
| +++ b/internal/host/group_receipt_test.go |
| @@ -108,3 +108,53 @@ func TestGroupReceiptReuse(t *testing.T) { |
| }) |
| } |
| } |
| + |
| +func TestGroupLaunchCancellation(t *testing.T) { |
| + for _, phase := range []string{"before", "backoff", "in-flight", "expired"} { |
| + t.Run(phase, func(t *testing.T) { |
| + calls := 0 |
| + ctx, cancel := context.WithCancel(t.Context()) |
| + defer cancel() |
| + c := groupLaunchFixture(t, func(context.Context, groupadmission.Launch) error { |
| + calls++ |
| + if phase == "in-flight" { |
| + cancel() |
| + return ctx.Err() |
| + } |
| + return nil |
| + }) |
| + var j groupLaunchJournal |
| + if err := readGroupReceiptFile(c.dir, "attempt.json", &j); err != nil { |
| + t.Fatal(err) |
| + } |
| + switch phase { |
| + case "before": |
| + cancel() |
| + case "backoff": |
| + j.Next = time.Now().Add(time.Minute).UnixNano() |
| + c.wait = func(context.Context, time.Duration) error { cancel(); return ctx.Err() } |
| + case "expired": |
| + j.Deadline = time.Now().Add(-time.Second).Unix() |
| + } |
| + if err := writeGroupReceiptFile(c.dir, "attempt.json", j); err != nil { |
| + t.Fatal(err) |
| + } |
| + err := c.Complete(ctx, c.binding.launch()) |
| + want, wantCalls := "group_launch_cancelled", 0 |
| + if phase == "expired" { |
| + want = "group_launch_deadline_passed" |
| + } |
| + if phase == "in-flight" { |
| + want, wantCalls = "group_launch_outcome_unknown", 1 |
| + } |
| + if groupLaunchFailureCode(err) != want || calls != wantCalls { |
| + t.Fatalf("reason=%s calls=%d want %s/%d err=%v", groupLaunchFailureCode(err), calls, want, wantCalls, err) |
| + } |
| + if phase == "before" || phase == "backoff" { |
| + if !errors.Is(err, context.Canceled) { |
| + t.Fatalf("lost cancellation: %v", err) |
| + } |
| + } |
| + }) |
| + } |
| +} |