carlos / platform Public

region HA P3b T4: review fixes for bootstrap, permits and return

Cover bootstrap's group launch plan, masks and fixed-box behavior.
Return quiesce refusals explicitly and restrict guarded operations to
named permit actions without consuming refused staging permits.
Resume ambiguous return completions from phase readback within the
persisted attempt budget, with failure alerts before the deadline.

Task 4 review round 1 is closed: 0 P1, 2 P2, 5 P3. Addresses P2-1,
P2-2, P3-1 and P3-2; the other P3 findings remain deferred.
Validated targeted RED/GREEN tests, the bootstrap mutation, covering
host regressions, build, vet, gofmt and Darwin/Windows builds.
Co-Authored-By: GPT-6 Astra (codex) <noreply@openai.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev 2722ac0d35716e0c3d889e995b809935d8f689cd parent 77a57e4
5 files changed, +286 −35
  • internal/host/bootstrap.go +14 −7
  • internal/host/group_maintenance.go +5 −4
  • internal/host/group_maintenance_protocol_test.go +87 −8
  • internal/host/group_maintenance_test.go +160 −2
  • internal/host/systemapply.go +20 −14

Intent

Human

<task-notification> <task-id>a3627b90f959c4eb8</task-id> <tool-use-id>toolu_01CvBVYnCcaAmVTjHy56LwDy</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/05c816f1-0a2d-43e3-9285-de8352549786/tasks/a3627b90f959c4eb8.output</output-file> <status>completed</status> <summary>Agent "Re-review Task 3 fix diff" finished</summary> <note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note> <result>All six in-scope fixes are in place, and the fix diff (43177b60..609fde28) introduces no new P1 or P2 problems. I didn't run any tests or call AWS, so test results are as the implementer reported them. The full check is written to `/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-fix.md`. ## Per finding - **P2-1 ADDRESSED** (`infra/modules/region-host/group-init.sh.tftpl:105-122`): - The order is now: install the chrony config, enable, restart, then check that `169.254.169.123` is the selected (`^*`) or combined (`^+`) source, then `waitsync`. The check is bounded at 20 tries and fails with `group_boot_clock_source`. - The firewall rules block only `.254` and `fd00:ec2::254`, so the time server at `.123` is still reachable. - Tested by `assertGroupClockOrder` (`internal/host/group_boot_test.go:217`, called at :109 and :125) and `TestGroupBootClockSource` (:298). - **P3-2 ADDRESSED** (`group-init.sh.tftpl:146-147`): - The boot script refuses unless the queue URL from SSM equals the exported `CARLOS_TERMINATION_QUEUE_URL`. - tofu renders both from `aws_sqs_queue.terminations.id` (`group.tf:195` and `:255`), so a correct deployment always matches. - The check runs before the bootstrap fetch and before the marker is written. Tested by `TestGroupBootQueueBinding` (:232). - **P3-3 ADDRESSED** (`internal/host/group_receipt.go:93-110`, `:162-168`): - Cancellation before an attempt, during backoff or after backoff is now reported as `group_launch_cancelled`. - An in-flight cancellation or the 2-second per-attempt timeout still reports `outcome_unknown`, because unknown is checked first and every provider error other than a rejection is wrapped as unknown. - Tested by `TestGroupLaunchCancellation` (`group_receipt_test.go:112`). - **P3-4 ADDRESSED** (`internal/host/group_boot.go:46-61`). Both sides of the invariant hold: - **Fixed boxes:** a fixed box (no `CARLOS_BOX_REFERENCE=group`) whose marker check fails with anything other than "not found" now logs and continues in fixed mode. Before, it stopped the agent with `log.Fatal`. - **Group boxes:** with the group reference set, any marker check error refuses. Any marker that exists, including a dangling symlink, goes through the strict read, and every error from that read refuses. - Every group `host.env` sets the reference (`hostenv/group.go:130`, `hostenv.go:367`). - Bootstrap and install-channel run as root, so a permissions error can't hide the marker from them. - Tested by `TestGroupMarkerFixedMode` (:257). - **P3-6 ADDRESSED.** - The boot-order tests now check the actual commands in order. - New group-mode tests: `TestGroupPreAdmissionAgentWiring`, and `TestGroupAdmissionAllIngress` (`internal/edge/group_admission_external_test.go:73`). The latter covers direct, verified-hop, public-backhaul and tunnel requests plus worker and timer starts, and asserts zero acquires, starts and restores. - `TestGroupDepartureStepAndComplete` (`group_departure_test.go:159`) calls `step` and `complete` directly, both while closed and after admission. - **P3-7 ADDRESSED** (`internal/host/agent.go:626`, `internal/host/group_admission.go:205` and `:354-356`): - The departure gate now applies only to group members (`a == nil || !a.group || a.startAllowed()`). On fixed boxes, `beginDepartureWork` returns the parent context with no gate. - Before Task 3 (4573a815, `agent.go:600`), no box had a departure gate at all. So fixed boxes of any role now take the pre-Task-3 path through every gate that Task 3 added in `hadepartures.go`. - Group members stay gated: the group flag comes only from the marker, and `hadepartures_wiring.go:57` refuses to start departures on a group box without the gate. - Tested by `TestAdmissionFixedDepartureAck` (`group_departure_test.go:120`) for serve, drain and platform roles, before and after admission. ## New breakage in fix diff (P1/P2) None. ## Out of scope (one line each) - A group box would fall back to fixed mode only if root removed the group reference line from `host.env` and also caused a non-"not found" marker check error. That is two separate root-level changes, so it is P3 at most. - The "present" case in `TestGroupMarkerFixedMode` partly passes because the test's temp directory isn't root-owned. It proves the marker isn't bypassed, but not which strict check caught it. - This comes from the original Task 3 code, not the fix: on fixed boxes, a cancelled context now makes departure ack report `errDeparturePending` instead of the context error at shutdown. Only the error label changes. - The admission tick still records `group_launch_cancelled` as a lasting launch failure, as it did with the old wrong label. This can't happen yet, because the tick runs with `context.Background()`. - P3-1 (Task 4 acceptance), P3-5 and P3-8 (controller follow-up list) were left alone, as instructed.</result> <usage><subagent_tokens>90693</subagent_tokens><tool_uses>16</tool_uses><duration_ms>193065</duration_ms></usage> </task-notification>

Human

<task-notification> <task-id>bwafhiqd5</task-id> <tool-use-id>toolu_01RWGkv4X4ymYSxKF8PMADhq</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/05c816f1-0a2d-43e3-9285-de8352549786/tasks/bwafhiqd5.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 t5 $D/task-5-report.md" completed (exit code 0)</summary> </task-notification>

Human

<task-notification> <task-id>bhkc5pfpp</task-id> <tool-use-id>toolu_01LUCYGi6cSSY2BmDjoCDbpP</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/05c816f1-0a2d-43e3-9285-de8352549786/tasks/bhkc5pfpp.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 t4b $D/task-4-report.md" completed (exit code 0)</summary> </task-notification>

Human

<task-notification> <task-id>bplymnw0f</task-id> <tool-use-id>toolu_01VqTsTcihyDyEgjzA5qexAf</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/05c816f1-0a2d-43e3-9285-de8352549786/tasks/bplymnw0f.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 t5b $D/task-5-report.md" completed (exit code 0)</summary> </task-notification>

Attributed to this commit: 96.0 g CO₂e (9,079,513 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/internal/host/bootstrap.go b/internal/host/bootstrap.go
index 5a2d87550..0d766dd73 100644
--- a/internal/host/bootstrap.go
+++ b/internal/host/bootstrap.go
@@ -402,6 +402,11 @@ func bootstrapWith(root string, consumers []string, planJSON bool) error {
}
defer unlock()
}
+ return bootstrapWithGroup(root, consumers, planJSON, group)
+}
+
+func bootstrapWithGroup(root string, consumers []string, planJSON, group bool) error {
+ live := filepath.Clean(root) == "/"
hostEnv := filepath.Join(root, "etc", "carlos", "host.env")
if live {
hostEnv = claimBootstrapHostEnv
@@ -628,7 +633,7 @@ func bootstrapWith(root string, consumers []string, planJSON bool) error {
if err := writeFileDurable(filepath.Join(root, "etc/tmpfiles.d/carlos-group-maintenance.conf"), []byte("d /run/carlos-group-maintenance 0700 root root -\n"), 0644); err != nil {
return err
}
- if err := preserveGroupUnits("/etc"); err != nil {
+ if err := preserveGroupUnits(filepath.Join(root, "etc")); err != nil {
return err
}
}
@@ -637,6 +642,12 @@ func bootstrapWith(root string, consumers []string, planJSON bool) error {
}
fmt.Fprintf(out, " wrote %s\n", tmpfilesPath)
+ toEnable := enabledUnits
+ if group {
+ toEnable = groupManualUnits(toEnable)
+ }
+ launchPlan := systemctlPlan(toEnable)
+
if !live {
if planJSON {
return json.NewEncoder(os.Stdout).Encode(currentBootstrapPlan())
@@ -651,7 +662,7 @@ func bootstrapWith(root string, consumers []string, planJSON bool) error {
fmt.Printf(" %s\n", strings.Join(args, " "))
}
fmt.Printf(" %s\n", strings.Join(tmpfilesApply, " "))
- for _, args := range systemctlPlan(enabledUnits) {
+ for _, args := range launchPlan {
fmt.Printf(" systemctl %s\n", strings.Join(args, " "))
}
fmt.Printf(" systemctl %s\n", strings.Join(journaldReload, " "))
@@ -665,11 +676,7 @@ func bootstrapWith(root string, consumers []string, planJSON bool) error {
if out, err := exec.Command(tmpfilesApply[0], tmpfilesApply[1:]...).CombinedOutput(); err != nil {
return fmt.Errorf("%s: %v: %s", strings.Join(tmpfilesApply, " "), err, strings.TrimSpace(string(out)))
}
- toEnable := enabledUnits
- if group {
- toEnable = groupManualUnits(toEnable)
- }
- for _, args := range systemctlPlan(toEnable) {
+ for _, args := range launchPlan {
if err := systemctl(args...); err != nil {
return err
}
diff --git a/internal/host/group_maintenance.go b/internal/host/group_maintenance.go
index 21079bfbb..1548aaf49 100644
--- a/internal/host/group_maintenance.go
+++ b/internal/host/group_maintenance.go
@@ -8,6 +8,7 @@ import (
"os"
"path/filepath"
"regexp"
+ "slices"
"time"
"github.com/carlosframework/platform/internal/hostenv"
@@ -86,7 +87,7 @@ func groupDigest(s string) bool {
// Called under the apply lock before mutation. Each process consumes an action
// once, durably, before its first side effect. A crash requires a new operator
// decision; changing phases or replaying the same permit cannot replay it.
-func (a *systemApplier) requireGroupMaintenance(action string) error {
+func (a *systemApplier) requireGroupMaintenance(action string, alternatives ...string) error {
c, err := a.maintenanceConfig()
if err != nil || c == nil {
return err
@@ -108,7 +109,7 @@ func (a *systemApplier) requireGroupMaintenance(action string) error {
default:
return errGroupMaintenance
}
- if action == "mutation" {
+ if slices.Contains(alternatives, p.Action) {
action = p.Action
}
if action != "check" && action != p.Action && !(action == "rollback" && p.AllowRollback && p.Action == "apply") {
@@ -310,7 +311,7 @@ func (a *systemApplier) groupStageDigest(digest string) error {
if !groupMarkerPresent(a.etcDir) || a.maintenance().initial {
return nil
}
- if err := a.requireGroupMaintenance("mutation"); err != nil {
+ if err := a.requireGroupMaintenance("apply", "install"); err != nil {
return err
}
p := a.maintenance().permit
@@ -323,7 +324,7 @@ func (a *systemApplier) groupExecutable(path string) error {
if !groupMarkerPresent(a.etcDir) {
return nil
}
- if err := a.requireGroupMaintenance("mutation"); err != nil {
+ if err := a.requireGroupMaintenance("apply", "rollback"); err != nil {
return err
}
p := a.maintenance().permit
diff --git a/internal/host/group_maintenance_protocol_test.go b/internal/host/group_maintenance_protocol_test.go
index df4ece1ea..4afb4a6f5 100644
--- a/internal/host/group_maintenance_protocol_test.go
+++ b/internal/host/group_maintenance_protocol_test.go
@@ -23,13 +23,14 @@ type maintenanceCloud struct {
now, deadline time.Time
hook, loseEnter, loseExit, loseComplete, dropAfterExit, apiDown bool
rejected int
+ notLanded int
replacements, boxCompletions, operatorCompletions, reads int
writes []string
}
type maintenanceJournal struct {
transaction, iid, boot, process, exitActivity string
phase string
- observed time.Time
+ observed, nextAttempt time.Time
attempts int
unknown, failed, alert, permit bool
}
@@ -164,10 +165,18 @@ func (o *fakeMaintenanceOperator) returnMember() error {
}
// This journal is separate from the original launch receipt and survives
// operator restart. Ambiguous outcomes require describe before retry.
- if j.unknown {
- return errors.New("return completion unknown")
- }
- for j.attempts < 4 {
+ j.unknown = false
+ for j.attempts < 4 && !j.failed {
+ next := c.now
+ if j.nextAttempt.After(next) {
+ next = j.nextAttempt
+ }
+ if !next.Add(7 * time.Second).Before(c.deadline) {
+ j.failed = true
+ j.alert = true
+ return errors.New("return deadline near")
+ }
+ c.now = next
if !o.ready() {
j.failed = true
j.alert = true
@@ -177,15 +186,19 @@ func (o *fakeMaintenanceOperator) returnMember() error {
j.unknown = true
c.operatorCompletions++
c.now = c.now.Add(2 * time.Second)
+ if j.attempts < 4 {
+ j.nextAttempt = c.now.Add(time.Duration(1<<uint(j.attempts-1)) * time.Second)
+ }
c.writes = append(c.writes, "continue")
if c.rejected > 0 {
c.rejected--
j.unknown = false
- if j.attempts < 4 {
- c.now = c.now.Add(time.Duration(1<<uint(j.attempts-1)) * time.Second)
- }
continue
}
+ if c.notLanded > 0 {
+ c.notLanded--
+ return errors.New("lost completion request")
+ }
c.phase = "InService"
c.targets = [2]string{"healthy", "healthy"}
if c.loseComplete {
@@ -440,3 +453,69 @@ func TestGroupStandbyReturnAttemptBudget(t *testing.T) {
t.Fatal("resume reset completion attempts")
}
}
+
+func TestGroupStandbyReturnAmbiguousCompletion(t *testing.T) {
+ for _, mode := range []string{"not-landed", "landed", "proceed", "exhausted", "deadline"} {
+ t.Run(mode, func(t *testing.T) {
+ o := heldTransaction(t)
+ o.c.hook = true
+ finishLocal(o)
+ _ = o.observeReady()
+ if mode == "landed" || mode == "proceed" {
+ o.c.loseComplete = true
+ } else {
+ o.c.notLanded = 1
+ }
+ if mode == "exhausted" {
+ o.c.rejected = 3
+ }
+ if err := o.returnMember(); err == nil || !o.j.unknown {
+ t.Fatal("fixture did not lose completion", err, o.j)
+ }
+ beforeAttempts, beforeReads := o.j.attempts, o.c.reads
+ if mode == "proceed" {
+ o.c.phase = "Pending:Proceed"
+ }
+ if mode == "deadline" {
+ o.c.now = o.c.deadline.Add(-3 * time.Second)
+ }
+ o = &fakeMaintenanceOperator{c: o.c, j: o.j}
+ err := o.returnMember()
+ if o.c.reads <= beforeReads {
+ t.Fatal("no phase readback before retry")
+ }
+ if mode == "exhausted" || mode == "deadline" {
+ if err == nil || !o.j.failed || !o.j.alert || !o.c.now.Before(o.c.deadline) || o.j.attempts != beforeAttempts {
+ t.Fatalf("no fail and alert before deadline: %v %+v %+v", err, o.j, o.c)
+ }
+ } else if mode == "proceed" {
+ if err == nil || o.j.attempts != beforeAttempts {
+ t.Fatal("blind retry while proceeding", err, o.j)
+ }
+ o.c.phase = "InService"
+ if err := o.returnMember(); err != nil {
+ t.Fatal(err)
+ }
+ } else {
+ want := 1
+ if mode == "not-landed" {
+ want = 2
+ }
+ if err != nil || o.c.phase != "InService" || o.j.attempts != want || o.j.permit {
+ t.Fatalf("resume failed: %v %+v %+v", err, o.j, o.c)
+ }
+ if mode == "not-landed" && o.c.now.Sub(o.j.observed) != 5*time.Second {
+ t.Fatal("missing persisted retry backoff", o.c.now.Sub(o.j.observed))
+ }
+ }
+ if o.c.replacements != 0 || o.c.boxCompletions != 0 {
+ t.Fatal("replacement or box completion", o.c)
+ }
+ for _, w := range o.c.writes {
+ if w == "abandon" {
+ t.Fatal("sent abandon")
+ }
+ }
+ })
+ }
+}
diff --git a/internal/host/group_maintenance_test.go b/internal/host/group_maintenance_test.go
index 47cf7e4fb..081a59668 100644
--- a/internal/host/group_maintenance_test.go
+++ b/internal/host/group_maintenance_test.go
@@ -10,6 +10,8 @@ import (
"github.com/carlosframework/platform/internal/hostenv"
"os"
"path/filepath"
+ "reflect"
+ "slices"
"strings"
"testing"
"time"
@@ -30,7 +32,7 @@ func TestGroupMaintenanceRestartGuard(t *testing.T) {
case "restart":
err = f.a.restartEdge()
case "quiesce":
- f.a.quiesce()
+ _, err = f.a.quiesce()
case "repoint":
err = f.a.activationGuard(t.Context(), "v1.1.0", "v1.0.0", func(context.Context) error { f.calls = append(f.calls, "REPOINT"); return nil })
case "units":
@@ -45,7 +47,7 @@ func TestGroupMaintenanceRestartGuard(t *testing.T) {
in := channelInstall{a: f.a}
_, err = in.run(t.Context())
}
- if entry != "quiesce" && !errors.Is(err, errGroupMaintenance) {
+ if !errors.Is(err, errGroupMaintenance) {
t.Error("entry accepted group without permit")
}
for _, call := range f.calls {
@@ -473,3 +475,159 @@ func TestGroupMaintenanceArtifactLink(t *testing.T) {
t.Fatal("followed artifact link", err, f.calls)
}
}
+
+func TestGroupMaintenanceBootstrapLaunchPlan(t *testing.T) {
+ for _, group := range []bool{false, true} {
+ t.Run(fmtGroupMode(group), func(t *testing.T) {
+ root := t.TempDir()
+ output, err := os.CreateTemp(t.TempDir(), "bootstrap-output")
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer output.Close()
+ original := os.Stdout
+ os.Stdout = output
+ defer func() { os.Stdout = original }()
+ err = bootstrapWithGroup(root, nil, false, group)
+ os.Stdout = original
+ if err != nil {
+ t.Fatal(err)
+ }
+ printed, err := os.ReadFile(output.Name())
+ if err != nil {
+ t.Fatal(err)
+ }
+ names, err := unitNames()
+ if err != nil {
+ t.Fatal(err)
+ }
+ automatic := []string{"carlos-system-update.path", "carlos-system-update.service", "carlos-system-recover.service"}
+ for _, name := range names {
+ path := filepath.Join(root, "etc/systemd/system", name)
+ if group && slices.Contains(automatic, name) {
+ if to, err := os.Readlink(path); err != nil || to != "/dev/null" {
+ t.Errorf("automatic unit not masked: %s %s %v", name, to, err)
+ }
+ if strings.Contains(string(printed), "wrote "+path) {
+ t.Errorf("automatic unit written: %s", name)
+ }
+ continue
+ }
+ got, err := os.ReadFile(path)
+ want, _ := unitsFS.ReadFile("units/" + name)
+ want = claimUnitContent(name, want, claimUnitSettings{})
+ if err != nil || !bytes.Equal(got, want) {
+ t.Errorf("unit changed: %s %v", name, err)
+ }
+ }
+ var commands [][]string
+ for _, line := range strings.Split(string(printed), "\n") {
+ if strings.HasPrefix(line, " systemctl ") && !strings.Contains(line, "systemd-journald") {
+ commands = append(commands, strings.Fields(strings.TrimPrefix(line, " systemctl ")))
+ }
+ }
+ wantEnabled := append([]string(nil), enabledUnits...)
+ if group {
+ wantEnabled = slices.DeleteFunc(wantEnabled, func(u string) bool { return slices.Contains(automatic, u) })
+ drop, err := os.ReadFile(filepath.Join(root, "etc/systemd/system/carlos-edge.service.d/50-group.conf"))
+ if err != nil || string(drop) != groupUnitProtection {
+ t.Errorf("group drop-in: %s %v", drop, err)
+ }
+ conf, err := os.ReadFile(filepath.Join(root, "etc/tmpfiles.d/carlos-group-maintenance.conf"))
+ if err != nil || string(conf) != "d /run/carlos-group-maintenance 0700 root root -\n" {
+ t.Errorf("group runtime directory: %s %v", conf, err)
+ }
+ } else {
+ if _, err := os.Stat(filepath.Join(root, "etc/systemd/system/carlos-edge.service.d/50-group.conf")); !errors.Is(err, os.ErrNotExist) {
+ t.Fatal("fixed bootstrap gained group drop-in", err)
+ }
+ conf, err := os.ReadFile(filepath.Join(root, "etc/tmpfiles.d/carlos.conf"))
+ if err != nil || string(conf) != tmpfilesConf {
+ t.Fatal("fixed tmpfiles changed", err)
+ }
+ }
+ if !reflect.DeepEqual(commands, systemctlPlan(wantEnabled)) {
+ t.Errorf("launch plan: got %v want %v", commands, systemctlPlan(wantEnabled))
+ }
+ })
+ }
+}
+func fmtGroupMode(group bool) string {
+ if group {
+ return "group"
+ }
+ return "fixed"
+}
+
+func TestGroupMaintenanceActionBinding(t *testing.T) {
+ entries := map[string]func(*applyFixture) error{
+ "quiesce": func(f *applyFixture) error { _, err := f.a.quiesce(); return err },
+ "repoint": func(f *applyFixture) error {
+ return f.a.activationGuard(t.Context(), "v1", "v1", func(context.Context) error { f.calls = append(f.calls, "REPOINT"); return nil })
+ },
+ "units": func(f *applyFixture) error { return f.a.installUnits(t.Context(), t.TempDir(), nil) },
+ "stage-plan": func(f *applyFixture) error {
+ _, _, err := f.a.stagePlan(t.Context(), systemBinaryPath(f.a.optDir), t.TempDir())
+ return err
+ },
+ "restart-edge": func(f *applyFixture) error { return f.a.restartEdge() },
+ "restart-control": func(f *applyFixture) error { return f.a.restartInstanceControl() },
+ "restart-relay": func(f *applyFixture) error { f.a.restartRelay(); return nil },
+ "arm": func(f *applyFixture) error { return f.a.arm(currentBootstrapPlan()) },
+ "rearm": func(f *applyFixture) error { return f.a.rearm([]string{"carlos-adopt.timer"}) },
+ "rearm-pending": func(f *applyFixture) error {
+ if err := f.a.notePendingRearm([]string{"carlos-adopt.timer"}); err != nil {
+ return err
+ }
+ f.a.rearmPending()
+ return nil
+ },
+ }
+ for name, entry := range entries {
+ for _, action := range []string{"install", "repair"} {
+ t.Run(name+"/"+action, func(t *testing.T) {
+ f, p := maintenanceFixture(t)
+ p.Action = action
+ writeMaintenancePermit(t, f, p)
+ err := entry(f)
+ if name != "restart-relay" && name != "rearm-pending" && !errors.Is(err, errGroupMaintenance) {
+ t.Errorf("wrong action accepted: %v", err)
+ }
+ if len(f.calls) != 0 {
+ t.Errorf("wrong action mutated: %v", f.calls)
+ }
+ if _, err := os.Stat(filepath.Join(f.a.maintenance().dir, "used-"+p.Transaction+"-"+action)); !errors.Is(err, os.ErrNotExist) {
+ t.Error("wrong action consumed", err)
+ }
+ if name == "rearm-pending" {
+ if _, err := os.Stat(f.a.file(rearmPendingFile)); err != nil {
+ t.Error("refusal lost pending rearm", err)
+ }
+ }
+ })
+ }
+ }
+ for _, action := range []string{"rollback", "repair"} {
+ t.Run("stage/"+action, func(t *testing.T) {
+ f, p := maintenanceFixture(t)
+ p.Action = action
+ writeMaintenancePermit(t, f, p)
+ if err := f.a.groupStageDigest(p.NewSHA256); !errors.Is(err, errGroupMaintenance) {
+ t.Fatal("staged wrong action", err)
+ }
+ if _, err := os.Stat(filepath.Join(f.a.maintenance().dir, "used-"+p.Transaction+"-"+action)); !errors.Is(err, os.ErrNotExist) {
+ t.Error("staging consumed refused permit", err)
+ }
+ f.a.resetGroupMaintenance()
+ if err := f.a.requireGroupMaintenance(action); err != nil {
+ t.Fatal("refused permit cannot authorize its own action", err)
+ }
+ })
+ }
+ t.Run("generic-mutation", func(t *testing.T) {
+ f, _ := maintenanceFixture(t)
+ if err := f.a.requireGroupMaintenance("mutation"); !errors.Is(err, errGroupMaintenance) {
+ t.Fatal("generic mutation accepted", err)
+ }
+ })
+}
diff --git a/internal/host/systemapply.go b/internal/host/systemapply.go
index 5df5d2909..85cae12dc 100644
--- a/internal/host/systemapply.go
+++ b/internal/host/systemapply.go
@@ -635,7 +635,10 @@ func (a *systemApplier) install(ctx context.Context, req systemRequest, p *relea
// before the rename; one that is already running is killed, and those
// passes are idempotent. Which of their triggers were active is kept, so
// a refused rename can put them back.
- prior := a.quiesce()
+ prior, err := a.quiesce()
+ if err != nil {
+ return a.abandonInstall(req, err, prior)
+ }
// The activation rule again, at the step it guards (moves spec §11): the
// check before staging can have gone stale, since the agent may have
// raised the floor or held a row since. activationGuard holds the floor
@@ -784,9 +787,9 @@ func (a *systemApplier) rearmPending() {
// timers and paths among them that were active, for rearm to start again
// if the step they were paused for is refused. When their state cannot be
// read, all of them are returned: active is what an armed box has.
-func (a *systemApplier) quiesce() []string {
- if err := a.requireGroupMaintenance("mutation"); err != nil {
- return nil
+func (a *systemApplier) quiesce() ([]string, error) {
+ if err := a.requireGroupMaintenance("apply", "rollback"); err != nil {
+ return nil, err
}
var triggers []string
for _, u := range systemQuiesceUnits {
@@ -809,12 +812,12 @@ func (a *systemApplier) quiesce() []string {
if _, err := a.ops.systemctl(append([]string{"stop"}, systemQuiesceUnits...)...); err != nil {
a.ops.logf("system apply: quiesce: %v (continuing)", err)
}
- return prior
+ return prior, nil
}
// rearm starts units again (nothing to do for none).
func (a *systemApplier) rearm(units []string) error {
- if err := a.requireGroupMaintenance("mutation"); err != nil {
+ if err := a.requireGroupMaintenance("apply", "rollback"); err != nil {
return err
}
if groupMarkerPresent(a.etcDir) {
@@ -1105,7 +1108,7 @@ func (e activationDeferred) Unwrap() error { return e.error }
// since reading it runs a binary. A refusal or deferral comes back typed;
// fn's own error comes back as it is.
func (a *systemApplier) activationGuard(ctx context.Context, target, running string, fn func(context.Context) error) error {
- if err := a.requireGroupMaintenance("mutation"); err != nil {
+ if err := a.requireGroupMaintenance("apply", "rollback"); err != nil {
return err
}
guard := func(ctx context.Context) error {
@@ -1126,7 +1129,7 @@ func (a *systemApplier) activationGuard(ctx context.Context, target, running str
if a.beforeSwap != nil {
a.beforeSwap()
}
- if err := a.requireGroupMaintenance("mutation"); err != nil {
+ if err := a.requireGroupMaintenance("apply", "rollback"); err != nil {
return err
}
return fn(ctx)
@@ -1412,7 +1415,7 @@ func (a *systemApplier) journal(j systemJournal) error {
// next boot — then daemon-reload. Never the staging root's data/: it holds
// a 0-byte registry.db.
func (a *systemApplier) installUnits(ctx context.Context, stagedRoot string, remove []string) error {
- if err := a.requireGroupMaintenance("mutation"); err != nil {
+ if err := a.requireGroupMaintenance("apply", "rollback"); err != nil {
return err
}
if groupMarkerPresent(a.etcDir) {
@@ -1546,7 +1549,7 @@ func (a *systemApplier) installUnits(ctx context.Context, stagedRoot string, rem
// restartEdge resets the failure counter FIRST — a unit that hit its start
// limit refuses restart, and so would the rollback — then restarts.
func (a *systemApplier) restartEdge() error {
- if err := a.requireGroupMaintenance("mutation"); err != nil {
+ if err := a.requireGroupMaintenance("apply", "rollback"); err != nil {
return err
}
a.ops.systemctl("reset-failed", systemEdgeUnit)
@@ -1585,7 +1588,7 @@ func (a *systemApplier) restartEdge() error {
// systemctl. reset-failed first, as restartEdge does, so a unit that hit
// its start limit can be restarted at all.
func (a *systemApplier) restartInstanceControl() error {
- if err := a.requireGroupMaintenance("mutation"); err != nil {
+ if err := a.requireGroupMaintenance("apply", "rollback"); err != nil {
return err
}
if _, err := os.Stat(filepath.Join(a.etcDir, "systemd", "system", systemControlUnit)); err != nil {
@@ -1618,7 +1621,7 @@ func (a *systemApplier) restartInstanceControl() error {
// a failure of the update — the edge, the binary and the gate are all fine —
// and `carlos relay status` is where a dead region is meant to be read.
func (a *systemApplier) restartRelay() {
- if err := a.requireGroupMaintenance("mutation"); err != nil {
+ if err := a.requireGroupMaintenance("apply", "rollback"); err != nil {
return
}
a.ops.systemctl("reset-failed", systemRelayUnit)
@@ -1793,7 +1796,7 @@ func (a *systemApplier) gateCheck(ctx context.Context, target string) (string, e
// than the relay. Now the list comes from the target build, so the guarantee
// is enforced here instead, explicitly.
func (a *systemApplier) arm(plan bootstrapPlan) error {
- if err := a.requireGroupMaintenance("mutation"); err != nil {
+ if err := a.requireGroupMaintenance("apply", "rollback"); err != nil {
return err
}
if groupMarkerPresent(a.etcDir) {
@@ -1957,7 +1960,10 @@ func (a *systemApplier) restoreFiles(ctx context.Context, j *systemJournal) (boo
}
// The same quiesce the install did: a root pass that is mid-flight
// against the failed build must not run on across the swap back.
- prior := a.quiesce()
+ prior, err := a.quiesce()
+ if err != nil {
+ return bootstrapPlan{}, err
+ }
// carlos.prev is copied beside the binary first, outside any lock, and
// renamed over it under the activation guard, so the rule's inputs are
// held still for a rename rather than a whole binary copy.