Keep HA termination witness evidence through fast shutdown
Upload SIGTERM and unit-stop evidence before final journal capture. Stream bounded journal chunks while ready and report each observer failure without skipping later shutdown evidence. Skip the root witness when unconfigured. Cover upload failures, cursor advancement and bounds with tagged local tests.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
internal/host/haterminate_rootrunner_linux_test.go+306 −28
CI cancelled — superseded by a newer push — run details
Intent
<task-notification> <task-id>a6c1149835755c08c</task-id> <tool-use-id>toolu_01TYn8wMP68Cmrp9KrhV2acn</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/c23f0319-4761-45f6-bac7-f9471c7b9ab1/tasks/a6c1149835755c08c.output</output-file> <status>completed</status> <summary>Agent "Re-review Task 1 fix round 2" 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>**Finding Verdicts** - **Edge's `Wants=carlos-instance-control.service` starts control before the edge, so the cgroup-ro probe reads a missing `carlos-edge.service` cgroup and the box is not ready for up to 5 minutes after boot** — ADDRESSED. `internal/host/units/carlos-edge.service` (diff lines 83-85) now has `Wants=network-online.target` only. The `After=` line with the control socket, control service and `dbus.service` is unchanged (diff line 79). `TimeoutStopSec=120` is kept, and the test still asserts it (`units_shutdown_test.go`, diff lines 142-144). Control is again socket-activated by the agent's first request after the edge starts, and `After=` still orders its stop after the edge's. - The edge unit comment now says why: control's start probe needs the edge's cgroup. - The control unit header (diff lines 104-106) describes socket activation by the agent and "stays up through the edge's stop (T1/DR-4 ordering)". - `After=nftables.service` on control is kept; the test still asserts it (diff lines 153-155). - `units_shutdown_test.go` (diff lines 146-152) now fails if the edge has `Wants` or `Requires` on `carlos-instance-control.service`. The `After` assertions are kept. The `[Unit]Wants` expectation changed to `network-online.target`. - Census notes, the overlay TSV and the chain seals were regenerated. The report shows `TestPlan14RootReadCensus`, `TestCensusScopeIsTheRootBinary` and `TestPlan14RootInputInventoryCoverage` passing, plus clean vet, gofmt and `git diff --check`. ### New Breakage in the Fix Diff None. - **Minor, unverified:** the report does not show `TestEdgeShutdownKeepsControlAvailable` itself being run. It shows only the census tests, vet and gofmt. By reading the diff, the new assertions are consistent with the unit files. - **Minor, by design:** there is no `Wants` on control, so on a box where control is not running at shutdown (the agent never reached it), the pending-stop-job activation concern from the earlier round could recur. That is the same behaviour as before the original change, and the brief accepts it. ### Out-of-Scope Observations - `docs/superpowers/plans/2026-11-08-region-ha-graceful-terminate.md:76` still shows `Wants=network-online.target carlos-instance-control.service`. The plan is now stale against the shipped unit. - The report's systemd static verification exited 1 for both the base and group variants, because `/opt/carlos/carlos` is absent on this host. It reported no ordering cycle. The real boot witness was not rerun. ### Verdict **Fix round:** All findings addressed, no new Critical/Important breakage.</result> <usage><subagent_tokens>61803</subagent_tokens><tool_uses>4</tool_uses><duration_ms>20425</duration_ms></usage> </task-notification>
<task-notification> <task-id>b7chiwmdp</task-id> <tool-use-id>toolu_01BREhVXFZENGE1xdfaqMcPU</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/c23f0319-4761-45f6-bac7-f9471c7b9ab1/tasks/b7chiwmdp.output</output-file> <status>completed</status> <summary>Background command "python3 -u /home/paulca/.cache/region-ha-graceful/witness.py --worktree $PWD --expect present > ~/.cache/region-ha-graceful/fix-driver-2.log 2>&1; echo exit $? >> ~/.cache/region-ha-graceful/fix-driver-2.log" completed (exit code 0)</summary> </task-notification>
Attributed to this commit: 22.0 g CO₂e (2,722,503 tokens). This is an attribution, not a measurement — usage counted from this commit's own marker forward to the next one on region-ha-graceful-terminate, 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/haterminate_rootrunner_linux_test.go b/internal/host/haterminate_rootrunner_linux_test.go| index 936af81f5..e81bf16bf 100644 |
| --- a/internal/host/haterminate_rootrunner_linux_test.go |
| +++ b/internal/host/haterminate_rootrunner_linux_test.go |
| @@ -101,6 +101,7 @@ type terminateMirror struct { |
| prefix string |
| mu sync.Mutex |
| failure string |
| + command func(context.Context, string, ...string) ([]byte, error) |
| } |
| func newTerminateMirror(t *testing.T, run string) *terminateMirror { |
| @@ -170,28 +171,178 @@ func (m *terminateMirror) wrap(next http.Handler) http.Handler { |
| }) |
| } |
| -func (m *terminateMirror) finish(at time.Time) error { |
| - ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) |
| +const terminateJournalChunkLimit = 256 << 10 |
| +const terminateJournalTotalLimit = 16 << 20 |
| +const terminateJournalCountLimit = 900 |
| + |
| +type terminateBoundedOutput struct { |
| + buffer bytes.Buffer |
| + limit int |
| +} |
| + |
| +func (b *terminateBoundedOutput) Write(p []byte) (int, error) { |
| + if len(p) > b.limit-b.buffer.Len() { |
| + return 0, fmt.Errorf("observer command output exceeds %d bytes", b.limit) |
| + } |
| + return b.buffer.Write(p) |
| +} |
| + |
| +func (m *terminateMirror) run(ctx context.Context, name string, args ...string) ([]byte, error) { |
| + ctx, cancel := context.WithTimeout(ctx, 2*time.Second) |
| defer cancel() |
| - journal, err := exec.CommandContext(ctx, "journalctl", "-u", "carlos-edge.service", "-u", "carlos-instance-control.service", "-u", "carlos-instance*", "-u", terminateWitnessUnit, "-b", "--no-pager", "-o", "short-iso-precise").CombinedOutput() |
| + if m.command != nil { |
| + return m.command(ctx, name, args...) |
| + } |
| + cmd := exec.CommandContext(ctx, name, args...) |
| + out := &terminateBoundedOutput{limit: terminateJournalChunkLimit} |
| + cmd.Stdout, cmd.Stderr = out, out |
| + err := cmd.Run() |
| + return out.buffer.Bytes(), err |
| +} |
| + |
| +func (m *terminateMirror) observerPut(ctx context.Context, key string, raw []byte) error { |
| + ctx, cancel := context.WithTimeout(ctx, 3*time.Second) |
| + defer cancel() |
| + _, err := m.client.PutObject(ctx, &s3.PutObjectInput{Bucket: aws.String(terminateWitnessBucket), Key: aws.String(m.prefix + key), Body: bytes.NewReader(raw)}) |
| + return err |
| +} |
| + |
| +func (m *terminateMirror) observerEvent(ctx context.Context, e terminateEvent) error { |
| + raw, err := json.Marshal(e) |
| if err != nil { |
| - return fmt.Errorf("journal: %w: %s", err, journal) |
| + return err |
| + } |
| + return m.observerPut(ctx, fmt.Sprintf("events/%d-%s.json", e.At.UnixNano(), e.Kind), raw) |
| +} |
| + |
| +func (m *terminateMirror) observerError(ctx context.Context, step string, err error) { |
| + if err == nil || ctx.Err() != nil { |
| + return |
| + } |
| + message := err.Error() |
| + if len(message) > 2048 { |
| + message = message[:2048] |
| + } |
| + fmt.Fprintf(os.Stderr, "observer %s: %s\n", step, message) |
| + _ = m.observerEvent(ctx, terminateEvent{At: time.Now().UTC(), Kind: step + "-error", Error: message}) |
| +} |
| + |
| +func (m *terminateMirror) journal(ctx context.Context, cursors [2]string) ([]byte, [2]string, error) { |
| + var journal []byte |
| + for i := range cursors { |
| + args := []string{"-b", "--no-pager", "--quiet", "--utc", "-o", "short-iso-precise", "--show-cursor"} |
| + if cursors[i] != "" { |
| + args = append(args, "--after-cursor="+cursors[i]) |
| + } |
| + if i == 0 { |
| + args = append(args, "-u", "carlos-edge.service", "-u", "carlos-instance-control.service", "-u", "carlos-instance*", "-u", terminateWitnessUnit) |
| + } else { |
| + args = append(args, "_PID=1") |
| + } |
| + raw, err := m.run(ctx, "journalctl", args...) |
| + if err != nil { |
| + return nil, cursors, fmt.Errorf("journal source %d: %w", i, err) |
| + } |
| + for _, line := range strings.SplitAfter(string(raw), "\n") { |
| + if strings.HasPrefix(line, "-- cursor: ") { |
| + cursors[i] = strings.TrimSpace(strings.TrimPrefix(line, "-- cursor: ")) |
| + } else { |
| + journal = append(journal, line...) |
| + } |
| + } |
| + if len(journal) > terminateJournalChunkLimit { |
| + return nil, cursors, fmt.Errorf("journal chunk exceeds %d bytes", terminateJournalChunkLimit) |
| + } |
| } |
| - if err := m.put("journal.txt", journal); err != nil { |
| + return journal, cursors, nil |
| +} |
| + |
| +type terminateJournalStream struct { |
| + cursors [2]string |
| + seq, size int |
| +} |
| + |
| +func (m *terminateMirror) streamJournal(ctx context.Context, stream *terminateJournalStream) error { |
| + if stream.seq >= terminateJournalCountLimit || stream.size >= terminateJournalTotalLimit { |
| + return fmt.Errorf("journal stream limit reached") |
| + } |
| + raw, cursors, err := m.journal(ctx, stream.cursors) |
| + if err != nil { |
| return err |
| } |
| - units, err := exec.CommandContext(ctx, "systemctl", "show", "carlos-edge.service", "carlos-instance-control.service", "-p", "Id", "-p", "ActiveState", "-p", "SubState", "-p", "MainPID").CombinedOutput() |
| + if len(raw) > terminateJournalTotalLimit-stream.size { |
| + return fmt.Errorf("journal stream byte limit reached") |
| + } |
| + if len(raw) > 0 { |
| + if err := m.observerPut(ctx, fmt.Sprintf("journal/%06d.txt", stream.seq), raw); err != nil { |
| + return err |
| + } |
| + stream.seq++ |
| + stream.size += len(raw) |
| + } |
| + stream.cursors = cursors |
| + return nil |
| +} |
| + |
| +func (m *terminateMirror) observe(ctx context.Context) { |
| + journalTick := time.NewTicker(2 * time.Second) |
| + heartbeatTick := time.NewTicker(10 * time.Second) |
| + defer journalTick.Stop() |
| + defer heartbeatTick.Stop() |
| + stream := &terminateJournalStream{} |
| + streamFailed := false |
| + attempts := 0 |
| + for { |
| + select { |
| + case <-ctx.Done(): |
| + return |
| + case <-journalTick.C: |
| + if attempts < terminateJournalCountLimit { |
| + attempts++ |
| + if err := m.streamJournal(ctx, stream); err != nil { |
| + if !streamFailed { |
| + m.observerError(ctx, "journal-stream", err) |
| + } |
| + streamFailed = true |
| + } else { |
| + streamFailed = false |
| + } |
| + if attempts == terminateJournalCountLimit { |
| + m.observerError(ctx, "journal-stream", fmt.Errorf("journal polling limit reached")) |
| + } |
| + } |
| + case <-heartbeatTick.C: |
| + m.mu.Lock() |
| + failure := m.failure |
| + m.mu.Unlock() |
| + err := m.observerEvent(ctx, terminateEvent{At: time.Now().UTC(), Kind: "heartbeat", Error: failure}) |
| + m.observerError(ctx, "heartbeat", err) |
| + } |
| + } |
| +} |
| + |
| +func (m *terminateMirror) finish(at time.Time) { |
| + ctx := context.Background() |
| + m.observerError(ctx, "sigterm", m.observerEvent(ctx, terminateEvent{At: at, Kind: "sigterm"})) |
| + units, err := m.run(ctx, "systemctl", "show", "carlos-edge.service", "carlos-instance-control.service", "-p", "Id", "-p", "ActiveState", "-p", "SubState", "-p", "MainPID") |
| + m.observerError(ctx, "unit-state", err) |
| m.mu.Lock() |
| failure := m.failure |
| m.mu.Unlock() |
| + m.observerError(ctx, "unit-stop", m.observerEvent(ctx, terminateEvent{At: time.Now().UTC(), Kind: "unit-stop", Units: string(units), Error: failure})) |
| + journal, _, err := m.journal(ctx, [2]string{}) |
| if err != nil { |
| - failure += fmt.Sprintf(" unit state: %v", err) |
| + m.observerError(ctx, "journal", err) |
| + } else { |
| + m.observerError(ctx, "journal", m.observerPut(ctx, "journal.txt", journal)) |
| } |
| - return m.event(terminateEvent{At: at, Kind: "unit-stop", Error: failure, Units: string(units)}) |
| } |
| func TestRootHATerminateRelease(t *testing.T) { |
| run := os.Getenv("HA_TERMINATE_RUN") |
| + if run == "" { |
| + t.Skip("HA_TERMINATE_RUN is unset") |
| + } |
| if !regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9-]{0,79}$`).MatchString(run) { |
| t.Fatal("HA_TERMINATE_RUN must name this driver's isolated root-runner prefix") |
| } |
| @@ -252,28 +403,17 @@ func TestRootHATerminateRelease(t *testing.T) { |
| t.Fatal("mirror failed before ready: " + failure) |
| } |
| lifecycleCheck(t, "initial heartbeat", mirror.event(terminateEvent{At: time.Now().UTC(), Kind: "heartbeat"})) |
| + observeCtx, stopObserver := context.WithCancel(context.Background()) |
| + defer stopObserver() |
| + go mirror.observe(observeCtx) |
| lifecycleCheck(t, "off-box ready", mirror.put("ready.json", raw)) |
| lifecycleCheck(t, "local ready", os.WriteFile(filepath.Join(terminateWitnessRoot, "ready"), raw, 0600)) |
| - ticker := time.NewTicker(10 * time.Second) |
| - defer ticker.Stop() |
| - for { |
| - select { |
| - case <-stopped: |
| - err := mirror.finish(time.Now().UTC()) |
| - if err != nil { |
| - fmt.Fprintf(os.Stderr, "final mirror: %v\n", err) |
| - os.Exit(1) |
| - } |
| - // Shutdown owns the machine now. Avoid test cleanups that would start |
| - // systemctl jobs or unmount fixtures during the poweroff transaction. |
| - os.Exit(0) |
| - case <-ticker.C: |
| - mirror.mu.Lock() |
| - failure := mirror.failure |
| - mirror.mu.Unlock() |
| - lifecycleCheck(t, "heartbeat", mirror.event(terminateEvent{At: time.Now().UTC(), Kind: "heartbeat", Error: failure})) |
| - } |
| - } |
| + <-stopped |
| + stopObserver() |
| + mirror.finish(time.Now().UTC()) |
| + // Shutdown owns the machine now. Avoid test cleanups that would start |
| + // systemctl jobs or unmount fixtures during the poweroff transaction. |
| + os.Exit(0) |
| } |
| func terminateRootLaunch(t *testing.T, run string) { |
| @@ -390,3 +530,141 @@ func TestHATerminateMirror(t *testing.T) { |
| }) |
| } |
| } |
| + |
| +func TestHATerminateMirrorFinish(t *testing.T) { |
| + for _, fail := range []string{"", "sigterm", "systemctl", "unit-stop", "journalctl", "journal.txt", "all-uploads"} { |
| + t.Run("failure="+fail, func(t *testing.T) { |
| + var steps []string |
| + var events []terminateEvent |
| + remote := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + key := strings.TrimPrefix(r.URL.Path, "/"+terminateWitnessBucket+"/") |
| + step := key |
| + if strings.HasPrefix(key, "events/") { |
| + var event terminateEvent |
| + if err := json.NewDecoder(r.Body).Decode(&event); err != nil { |
| + t.Error(err) |
| + } |
| + step = event.Kind |
| + events = append(events, event) |
| + } |
| + steps = append(steps, step) |
| + if step == fail || fail == "all-uploads" { |
| + w.WriteHeader(http.StatusServiceUnavailable) |
| + } |
| + })) |
| + defer remote.Close() |
| + mirror := &terminateMirror{client: s3.NewFromConfig(aws.Config{Region: "eu-west-1", Credentials: credentials.NewStaticCredentialsProvider("x", "x", ""), RetryMaxAttempts: 1}, func(o *s3.Options) { |
| + o.BaseEndpoint = aws.String(remote.URL) |
| + o.UsePathStyle = true |
| + })} |
| + mirror.command = func(ctx context.Context, name string, args ...string) ([]byte, error) { |
| + steps = append(steps, name) |
| + if _, ok := ctx.Deadline(); !ok { |
| + t.Error("command has no deadline") |
| + } |
| + if name == fail { |
| + return nil, fmt.Errorf("injected %s failure", name) |
| + } |
| + if name == "systemctl" { |
| + return []byte("Id=carlos-edge.service\nActiveState=inactive\n"), nil |
| + } |
| + return []byte("2026-11-08T04:00:00+00:00 journal\n-- cursor: test\n"), nil |
| + } |
| + at := time.Now().UTC() |
| + mirror.finish(at) |
| + if steps[0] != "sigterm" || events[0].At != at || events[0].Units != "" || events[0].Error != "" { |
| + t.Fatalf("first event must be timestamp-only sigterm: %v %+v", steps, events[0]) |
| + } |
| + positions := map[string]int{} |
| + for i, step := range steps { |
| + if _, ok := positions[step]; !ok { |
| + positions[step] = i |
| + } |
| + } |
| + for _, step := range []string{"systemctl", "unit-stop", "journalctl"} { |
| + if _, ok := positions[step]; !ok { |
| + t.Fatalf("did not attempt %s after failure: %v", step, steps) |
| + } |
| + } |
| + if positions["systemctl"] >= positions["unit-stop"] || positions["unit-stop"] >= positions["journalctl"] { |
| + t.Fatalf("wrong shutdown evidence order: %v", steps) |
| + } |
| + if fail != "" && fail != "all-uploads" { |
| + errorStep := map[string]string{"systemctl": "unit-state", "journalctl": "journal", "journal.txt": "journal"}[fail] |
| + if errorStep == "" { |
| + errorStep = fail |
| + } |
| + if _, ok := positions[errorStep+"-error"]; !ok { |
| + t.Fatalf("failure not reported: %v", steps) |
| + } |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestHATerminateMirrorJournal(t *testing.T) { |
| + var keys []string |
| + var bodies []string |
| + fail := true |
| + remote := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + raw, _ := io.ReadAll(r.Body) |
| + keys = append(keys, r.URL.Path) |
| + bodies = append(bodies, string(raw)) |
| + if fail { |
| + w.WriteHeader(http.StatusServiceUnavailable) |
| + } |
| + })) |
| + defer remote.Close() |
| + mirror := &terminateMirror{client: s3.NewFromConfig(aws.Config{Region: "eu-west-1", Credentials: credentials.NewStaticCredentialsProvider("x", "x", ""), RetryMaxAttempts: 1}, func(o *s3.Options) { |
| + o.BaseEndpoint = aws.String(remote.URL) |
| + o.UsePathStyle = true |
| + })} |
| + var calls [][]string |
| + mirror.command = func(ctx context.Context, name string, args ...string) ([]byte, error) { |
| + calls = append(calls, args) |
| + if args[len(args)-1] == "_PID=1" { |
| + return []byte("systemd stop job\n-- cursor: manager\n"), nil |
| + } |
| + return []byte("edge: draining and shutting down\n-- cursor: units\n"), nil |
| + } |
| + ctx := context.Background() |
| + stream := &terminateJournalStream{} |
| + if mirror.streamJournal(ctx, stream) == nil || *stream != (terminateJournalStream{}) { |
| + t.Fatalf("failed upload advanced journal: %+v", stream) |
| + } |
| + fail = false |
| + if err := mirror.streamJournal(ctx, stream); err != nil { |
| + t.Fatal(err) |
| + } |
| + if stream.seq != 1 || stream.cursors != [2]string{"units", "manager"} || stream.size != len(bodies[1]) { |
| + t.Fatalf("wrong progress: %+v", stream) |
| + } |
| + if err := mirror.streamJournal(ctx, stream); err != nil { |
| + t.Fatal(err) |
| + } |
| + if keys[0] != keys[1] || !strings.HasSuffix(keys[2], "/journal/000001.txt") || strings.Contains(bodies[1], "-- cursor:") || !strings.Contains(bodies[1], "systemd stop job") { |
| + t.Fatalf("wrong chunks: %v %v", keys, bodies) |
| + } |
| + if !strings.Contains(strings.Join(calls[4], " "), "--after-cursor=units") || !strings.Contains(strings.Join(calls[5], " "), "--after-cursor=manager") { |
| + t.Fatalf("cursors not resumed: %v", calls) |
| + } |
| + for _, capped := range []terminateJournalStream{{seq: terminateJournalCountLimit}, {size: terminateJournalTotalLimit}, {size: terminateJournalTotalLimit - 1}} { |
| + if err := mirror.streamJournal(ctx, &capped); err == nil { |
| + t.Fatal("stream exceeded bound") |
| + } |
| + } |
| + mirror.command = func(context.Context, string, ...string) ([]byte, error) { |
| + return bytes.Repeat([]byte("x"), terminateJournalChunkLimit+1), nil |
| + } |
| + if err := mirror.streamJournal(ctx, &terminateJournalStream{}); err == nil { |
| + t.Fatal("oversized chunk accepted") |
| + } |
| + mirror.command = nil |
| + if raw, err := mirror.run(ctx, "head", "-c", "262145", "/dev/zero"); err == nil || len(raw) > terminateJournalChunkLimit { |
| + t.Fatalf("real command exceeded bound: size=%d err=%v", len(raw), err) |
| + } |
| + out := &terminateBoundedOutput{limit: 3} |
| + if _, err := out.Write([]byte("four")); err == nil || out.buffer.Len() != 0 { |
| + t.Fatal("command output bound not enforced") |
| + } |
| +} |