carlos / platform Public

Fix group maintenance apply configuration and preparation reporting

Run attended group apply with checked host.env under the existing command lock and guard. Bound preparation to five minutes, report matching prior outcomes, and clean only its stale private scratch.

Report process start at second precision with a separate clock error. Add production-configuration fixtures and failing-first regressions for the R13 fixes.
Paul Campbell pushed by claude agent, operated by paul@keymail.dev 36bdeb0df1a84c4382f8fc401bb1af23f6acfec1 parent d48d82d
5 files changed, +473 −33
  • internal/host/group_maintenance_clock.go +4 −2
  • internal/host/group_maintenance_prepare.go +81 −14
  • internal/host/group_maintenance_prepare_test.go +5 −4
  • internal/host/group_maintenance_round1_test.go +358 −0
  • internal/host/group_maintenance_verbs.go +25 −13

Intent

Human

<task-notification> <task-id>bbg9htze4</task-id> <tool-use-id>toolu_01F1d1JFLDBxv4RvNXiv4UZ8</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/e47280e8-3e59-4dc1-95d2-11de7237d34c/tasks/bbg9htze4.output</output-file> <status>completed</status> <summary>Background command ".superpowers/sdd/2026-11-04-region-ha-p3b-group/run-astra.sh b2b" completed (exit code 0)</summary> </task-notification>

Human

<task-notification> <task-id>a65aadac5d36a347a</task-id> <tool-use-id>toolu_011SPGMbSMZRfV4LUe1z3u3S</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/e47280e8-3e59-4dc1-95d2-11de7237d34c/tasks/a65aadac5d36a347a.output</output-file> <status>completed</status> <summary>Agent "Review B2b (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>### Spec Compliance **prepare** - ✅ It refuses on a fixed box, on a bad marker and when not root, under the apply lock. The dispatch sits after the existing checks and the re-check under the lock (`group_maintenance_verbs.go:96-135`). Tests: `fixed`, `marker`, `not-root`, `busy`. - ✅ It uses the same pointer verifier as systemLeg and apply. That is `release.GetSystemPointer` (`group_maintenance_prepare.go:118`, matching `systemleg.go:125` and `systemapply.go:2295`), with the shared `systemLegForPreparation` constructor (`systemleg.go:85`). The signature mutation hit the shared verifier and was caught. - ✅ The digest is pinned to the pointer's artifact for this box's arch (`:123`), and the version is validated before it is used as a path (`:126`). No release_tag is required. - ✅ It reuses `fetch`, `systemCacheHolds` and `writeRequest` (`:155-161`), working in root scratch and publishing through safefile. - ✅ It does not stage, repoint or restart. The test checks no calls, no staging dir and no `.prev`. - ✅ It checks host.env read-only with the strict root reader (0600) and `AssembleGroup` against the marker. There is no SSM fetch (`:44-80`). - ✅ The JSON result is v1 and bounded. The help says prepare is attended and makes cloud GETs. - ⚠️ `groupReaderTargetAllowed` is not applied. The justification (it is the fixed-reader gate, and an attended group process has no fold cache) is reasonable, but it leaves downgrade safety to the operator. That needs a controller decision. - ❌ Contract gap, not a guard gap. The "prepare → permit → `carlos system apply`" proof (`group_maintenance_prepare_test.go` `TestGroupMaintenancePrepareApply`) calls `f.a.Run` on a preconfigured fixture. It does not use the production entry an operator can actually run. See Important 1. **Requests cannot apply without a permit** - ✅ I checked every consumer of `requested.json`. Run is guarded by `requireGroupMaintenance("check")` at the top of `runLocked`, then by `groupStageDigest` before staging. The update path, update service and recover units are masked on groups (`groupAutomaticUnit`). Recover uses the request only to label the result tuple (`systemapply.go:2125`). `claimcensus.go:104` only lists the path. No adopt consumer exists. **Guard** - ✅ `group_maintenance.go`, `group_maintenance_linux.go` and the guard and protocol tests are unchanged from 8b294028 to d48d82d1. Compared with f86e9792, the only change is B2's shared-validator refactor (bdaca007), which was reviewed earlier. This task adds none. **rollback** - ✅ It needs an explicit permit with action `rollback`. It also needs the same transaction's consumed apply record, `carlos.prev` holding OldSHA256 and the current binary holding NewSHA256. It refuses if a journal exists. All of this happens under the command's lock before consumption (`group_maintenance_prepare.go:194-221`). - ✅ `groupTarget(prev, true)` writes `used-&lt;tx&gt;-rollback` and re-hashes prev before anything that changes the box (`:235`). `restoreVersion`, `stagePlan` and `beginExecutableChange` all come after it. - ✅ Replay is refused by `maintenanceUnconsumed` on the "check" pass. Tests cover consumed, wrong-old (no marker written), wrong-transaction, apply-consumed and replay. - ✅ The edge restart reuses the existing `a.rollback`, i.e. the `restoreFiles`, `restartInstanceControl`, `restartEdge` and gate sequence (`systemapply.go:1875-1904`). There is no new restart path. It does not call the console channel rollback. **Other** - ✅ `started_at` is btime + ticks/AT_CLKTCK read from auxv, and is null with an error when unknown (`group_maintenance_clock.go`, `group_maintenance_verbs.go:316-326`). It does have a precision caveat (Important 2). - ✅ Fixed boxes are unchanged. `Run` is identical before the lock, `runLocked` is the old body verbatim, the `RunSystemApply` literal was only extracted, and the rollback error text is identical. - ✅ Cross-platform builds and cgo: I ran `GOOS=darwin/arm64` and `windows/amd64` builds of `./internal/host`, and both pass. No `import "C"`. The new test file is linux-tagged. - ⚠️ `configureMaintenanceApplier`, the production `/proc` wiring and the real auxv layout are not exercised by any test, because tests leave `configure` nil. ### Strengths - Agent-cache reads are handled properly. The cache is opened through safefile (no symlinks, a regular file with one link, a size bound), copied into root-private scratch, and re-hashed against the signed digest. Writes back into the data dir go through `safefile.Write`. `TestGroupMaintenancePrepareCache` shows that tampering with the cache after prepare is refused by the real apply staging. - Rollback reuses `runLocked`, so recovery, floor, settlement and cleanup ordering are not forked. The internal `systemRollbackCompleted` type keeps the ordinary apply's error text unchanged. - The rollback checks are ordered so that a refusal consumes nothing. The wrong-old mutation proves it. - The report says exactly which root reads of agent-writable paths were added, which the census reviewer will ask for. ### Issues **Important** 1. **The production apply step after prepare is undefined and fails silently.** Evidence: `systemapply.go:121-133`, `systemapply.go:175-185`, `systemapply.go:2234`, `group_maintenance_prepare.go:19-41`. - **What:** prepare and rollback set themselves up from host.env (`configureMaintenanceApplier`). `carlos system apply` does not: it reads the shell's environment. The update service is masked on groups, so the operator has to run apply by hand from a Session Manager shell, which (as the code itself notes) has not sourced host.env. - **Missing store settings:** `openSystemStore` fails, `verifyPointer` records "deferred", and Run exits 0 with nothing applied. That is the same gap B3 reported as finding 1. - **Channel mismatch:** if the shell's `CARLOS_SYSTEM_CHANNEL` differs from host.env's, `groupStageDigest` consumes `used-&lt;tx&gt;-apply` before its digest check and then refuses. The permit is burned. - **Why it matters:** the brief's end-to-end claim is only proven through a fixture applier. B3 has no tested way to run the apply. - **Fix (needs a controller choice):** - Option A: add `group-maintenance apply`. It would run `configure` and then `withSystemRelease(runLocked(ctx, false, nil))` under the command's lock, the way rollback does. That changes no guard. Add one test through the production `configure` path. - Option B: define and test the exact invocation (for example `systemd-run --wait --pipe -p EnvironmentFile=/etc/carlos/host.env …`) and put it in the help and the B3 brief. 2. **`started_at` can be up to about 1 s early, and the "one clock" comment hides that.** Evidence: `group_maintenance_clock.go:14-15, 78`. - **What:** `/proc/stat` btime is truncated to whole seconds, so the computed start can be up to 1 s before the real start. Edges `generation` is also truncated to seconds (`edgesfile.go:998`). The output is RFC3339Nano (".5Z"), which suggests sub-second accuracy it does not have. - **Why it matters:** this value exists for R6's "published after this process started" check. An old process's last publication made within about 1 s before a quick restart could pass a naive `generation &gt;= started_at`. - **Fix:** say in the comment and help that the value is a lower bound with up to 1 s error. Either print at second precision rounded up (btime+1), or tell B3 to require `generation &gt; started_at + 1s` alongside the identity check. **Minor** - **Untested wiring:** `configureMaintenanceApplier` (`group_maintenance_prepare.go:21`, which clears the environment and swaps in the production applier) has no test. Add a getenv-seam test that the channel, pubkey, bucket and roots come from host.env and that opt/data/etc are preserved. - **No timeout on prepare:** prepare holds the apply lock across S3 GETs with `context.Background()` and no deadline (`group_maintenance_verbs.go:66`). A hung GET blocks status, permit and revoke, since all of them take the lock nonblocking. Add a bounded context to prepare. - **Re-preparing after a rollback silently no-ops:** after an operator rollback, result.json records `rolled_back` for (channel, version, promoted_at). Preparing the same pointer again still prints `request_written:true`, but apply then exits 0 without applying (`systemapply.go:437-441`). Either have prepare refuse or report it, or tell B3 to always read back the binary digest. - **Leftover scratch:** a killed prepare leaves a `.prepare-*` copy of the artifact (up to the artifact size limit) under the root system dir, and nothing sweeps it. Sweep stale `.prepare-*` directories at the next prepare. - **Ambiguous status:** status can show `edge.state:"known"` together with a non-null `edge.error` when only the clock conversion failed (`group_maintenance_verbs.go:316-326`). Consider a separate `started_at_error` field. ### Assessment **Task quality:** Needs fixes I found no unsafe path in what the box accepts. The guard is untouched, requests cannot apply without a permit, and rollback runs its old-sha check, writes its consumed marker and blocks replay before anything changes on the box. But the prepare → permit → apply sequence has no tested production apply entry: the obvious invocation exits 0 having done nothing, or burns the permit. And `started_at` needs its ±1 s bound written down before B3 relies on it.</result> <usage><subagent_tokens>134828</subagent_tokens><tool_uses>25</tool_uses><duration_ms>293544</duration_ms></usage> </task-notification>

diff --git a/internal/host/group_maintenance_clock.go b/internal/host/group_maintenance_clock.go
index 6f863cf24..ccf0147e8 100644
--- a/internal/host/group_maintenance_clock.go
+++ b/internal/host/group_maintenance_clock.go
@@ -12,7 +12,9 @@ import (
)
// The edges object's generation is written by this box's own agent using the
-// same clock. The operator compares publication and process start on one clock.
+// same clock. btime has whole-second precision. started_at is a lower bound,
+// up to one second early; compare with a generation at least one second later
+// and check the edge identity has not changed.
func maintenanceProcessStartedAt(procRoot, start string) (string, error) {
ticks, err := strconv.ParseUint(start, 10, 64)
if err != nil || ticks == 0 {
@@ -75,7 +77,7 @@ func maintenanceProcessStartedAt(procRoot, start string) (string, error) {
if boot > maxRFC3339Second || seconds > maxRFC3339Second-boot {
return "", errors.New("process start time out of range")
}
- return time.Unix(int64(boot+seconds), int64((ticks%hz)*1e9/hz)).UTC().Format(time.RFC3339Nano), nil
+ return time.Unix(int64(boot+seconds), 0).UTC().Format(time.RFC3339), nil
}
func maintenanceReadProc(path string, limit int64) ([]byte, error) {
diff --git a/internal/host/group_maintenance_prepare.go b/internal/host/group_maintenance_prepare.go
index a8c8c05ca..a98a5b5d7 100644
--- a/internal/host/group_maintenance_prepare.go
+++ b/internal/host/group_maintenance_prepare.go
@@ -8,7 +8,9 @@ import (
"io"
"os"
"path/filepath"
+ "strconv"
"strings"
+ "time"
"github.com/carlosframework/platform/internal/appconfig"
"github.com/carlosframework/platform/internal/hostenv"
@@ -80,18 +82,67 @@ func (cmd *groupMaintenanceCommand) localConfiguration(c *hostenv.GroupConfig) (
}
type maintenancePrepared struct {
- V int `json:"v"`
- Version string `json:"version"`
- ReleaseTag string `json:"release_tag"`
- ArtifactSHA256 string `json:"artifact_sha256"`
- CachePath string `json:"cache_path"`
- CacheState string `json:"cache_state"`
- RequestWritten bool `json:"request_written"`
- OldBinarySHA256 string `json:"old_binary_sha256"`
- ConfigCheck string `json:"config_check"`
+ V int `json:"v"`
+ Version string `json:"version"`
+ ReleaseTag string `json:"release_tag"`
+ ArtifactSHA256 string `json:"artifact_sha256"`
+ CachePath string `json:"cache_path"`
+ CacheState string `json:"cache_state"`
+ RequestWritten bool `json:"request_written"`
+ OldBinarySHA256 string `json:"old_binary_sha256"`
+ ConfigCheck string `json:"config_check"`
+ PreviousResult *string `json:"previous_result"`
+}
+
+// One deadline covers configuration, store opening and both GETs while the
+// command holds the apply lock. A slow artifact never gets a fresh budget.
+const maintenancePrepareTimeout = 5 * time.Minute
+const maintenancePreparePrefix = ".prepare-"
+
+// Only MkdirTemp's decimal suffixes in the root-owned apply directory belong
+// to prepare. The command holds the apply lock; no active preparation can race
+// this sweep. Do not follow symlinks or touch another operation's scratch.
+func sweepMaintenancePreparation(root string) error {
+ entries, err := os.ReadDir(root)
+ if err != nil {
+ return err
+ }
+ for _, entry := range entries {
+ suffix, ok := strings.CutPrefix(entry.Name(), maintenancePreparePrefix)
+ if !ok || !entry.IsDir() {
+ continue
+ }
+ n, err := strconv.ParseUint(suffix, 10, 32)
+ if err != nil || strconv.FormatUint(n, 10) != suffix {
+ continue
+ }
+ if err := os.RemoveAll(filepath.Join(root, entry.Name())); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+func (cmd *groupMaintenanceCommand) apply(ctx context.Context, c *hostenv.GroupConfig) error {
+ env, err := cmd.localConfiguration(c)
+ if err != nil {
+ return err
+ }
+ if cmd.configure != nil {
+ if err := cmd.configure(cmd.a, env); err != nil {
+ return err
+ }
+ }
+ a := cmd.a
+ return a.withSystemRelease(ctx, func(ctx context.Context) error { return a.runLocked(ctx, false, nil) })
}
func (cmd *groupMaintenanceCommand) prepare(ctx context.Context, c *hostenv.GroupConfig, out io.Writer) error {
+ ctx, cancel := context.WithTimeout(ctx, maintenancePrepareTimeout)
+ defer cancel()
+ if err := sweepMaintenancePreparation(cmd.a.rootDir()); err != nil {
+ return err
+ }
if !groupDigest(cmd.sha256) {
return errors.New("invalid artifact digest")
}
@@ -130,10 +181,20 @@ func (cmd *groupMaintenanceCommand) prepare(ctx context.Context, c *hostenv.Grou
// group-only entry is the serialized operator's path; it has no cached fold
// and cannot manufacture the operator's deployment-wide retirement evidence.
pending := &systemPending{version: p.Current.Version, promotedAt: p.PromotedAt, artifact: art}
+ prior, err := readSystemResult(a.optDir)
+ if err != nil {
+ return err
+ }
+ var previousResult *string
+ completed := false
+ if prior.matches(l.channel, pending.version, pending.promotedAt) {
+ previousResult = &prior.Outcome
+ completed = prior.Outcome == systemOutcomeApplied || prior.Outcome == systemOutcomeRolledBack || prior.Outcome == systemOutcomeRollbackFailed
+ }
// Root never feeds an agent path to fetch/writeRequest's ordinary mkdirs.
// Work in root's private scratch, then publish with safefile's descriptor
// traversal and private temporary files. Apply re-verifies the published copy.
- scratch, err := os.MkdirTemp(a.rootDir(), ".prepare-")
+ scratch, err := os.MkdirTemp(a.rootDir(), maintenancePreparePrefix)
if err != nil {
return err
}
@@ -158,7 +219,8 @@ func (cmd *groupMaintenanceCommand) prepare(ctx context.Context, c *hostenv.Grou
if !systemCacheHolds(cache, art.SHA256) {
return errors.New("cached artifact digest mismatch")
}
- if err := l.writeRequest(pending, a.ops.now()); err != nil {
+
+ if err := ctx.Err(); err != nil {
return err
}
dst := systemCachePath(a.dataDir, pending.version)
@@ -168,10 +230,15 @@ func (cmd *groupMaintenanceCommand) prepare(ctx context.Context, c *hostenv.Grou
if err := copyFileDurable(cache, dst, 0644); err != nil {
return err
}
- if err := copyFileDurable(systemRequestPath(scratch), systemRequestPath(a.dataDir), 0644); err != nil {
- return err
+ if !completed {
+ if err := l.writeRequest(pending, a.ops.now()); err != nil {
+ return err
+ }
+ if err := copyFileDurable(systemRequestPath(scratch), systemRequestPath(a.dataDir), 0644); err != nil {
+ return err
+ }
}
- result := maintenancePrepared{V: 1, Version: p.Current.Version, ReleaseTag: p.Current.ReleaseTag, ArtifactSHA256: art.SHA256, CachePath: dst, CacheState: "verified", RequestWritten: true, OldBinarySHA256: old, ConfigCheck: "valid"}
+ result := maintenancePrepared{V: 1, Version: p.Current.Version, ReleaseTag: p.Current.ReleaseTag, ArtifactSHA256: art.SHA256, CachePath: dst, CacheState: "verified", RequestWritten: !completed, OldBinarySHA256: old, ConfigCheck: "valid", PreviousResult: previousResult}
b, err := json.Marshal(result)
if err != nil {
return err
diff --git a/internal/host/group_maintenance_prepare_test.go b/internal/host/group_maintenance_prepare_test.go
index f4dd08a2f..811aed593 100644
--- a/internal/host/group_maintenance_prepare_test.go
+++ b/internal/host/group_maintenance_prepare_test.go
@@ -270,7 +270,7 @@ func TestGroupMaintenanceStartedAt(t *testing.T) {
}
got, err := maintenanceProcessStartedAt(root, start)
if bad == "valid" {
- if err != nil || got != "2023-11-14T22:13:22.5Z" {
+ if err != nil || got != "2023-11-14T22:13:22Z" {
t.Fatalf("%q %v", got, err)
}
} else if err == nil {
@@ -285,8 +285,9 @@ func TestGroupMaintenanceStartedAt(t *testing.T) {
}
var s struct {
Edge struct {
- Started *string `json:"started_at"`
- Error *string `json:"error"`
+ Started *string `json:"started_at"`
+ Error *string `json:"error"`
+ ClockError *string `json:"started_at_error"`
} `json:"edge"`
}
if json.Unmarshal(raw, &s) != nil {
@@ -296,7 +297,7 @@ func TestGroupMaintenanceStartedAt(t *testing.T) {
if s.Edge.Started == nil || *s.Edge.Started != got {
t.Fatal(string(raw))
}
- } else if s.Edge.Started != nil || s.Edge.Error == nil {
+ } else if s.Edge.Started != nil || s.Edge.ClockError == nil || s.Edge.Error != nil {
t.Fatal(string(raw))
}
})
diff --git a/internal/host/group_maintenance_round1_test.go b/internal/host/group_maintenance_round1_test.go
new file mode 100644
index 000000000..235238db8
--- /dev/null
+++ b/internal/host/group_maintenance_round1_test.go
@@ -0,0 +1,358 @@
+//go:build linux
+
+package host
+
+import (
+ "bytes"
+ "context"
+ "crypto/ed25519"
+ "encoding/json"
+ "errors"
+ "io"
+ "os"
+ "path/filepath"
+ "reflect"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/release"
+)
+
+// Configure really replaces the process environment. Restore it before the
+// next test, including TMPDIR, without ever printing its contents.
+func maintenanceRestoreEnvironment(t *testing.T) {
+ t.Helper()
+ t.Setenv("CARLOS_MAINTENANCE_TEST", "1")
+ saved := os.Environ()
+ t.Cleanup(func() {
+ os.Clearenv()
+ for _, entry := range saved {
+ k, v, _ := strings.Cut(entry, "=")
+ if err := os.Setenv(k, v); err != nil {
+ t.Error(err)
+ }
+ }
+ })
+}
+
+func maintenanceProductionConfigure(t *testing.T, f *applyFixture, cmd *groupMaintenanceCommand) *int {
+ t.Helper()
+ maintenanceRestoreEnvironment(t)
+ fake := *f.a
+ configured := 0
+ cmd.configure = func(a *systemApplier, env map[string]string) error {
+ configured++
+ lock, err := openMaintenanceLock(a.lockPath(), false)
+ if err != nil {
+ t.Fatal(err)
+ }
+ lockErr := flockExclusiveNonblock(lock)
+ lock.Close()
+ if lockErr == nil {
+ t.Fatal("configuration ran without the command lock")
+ }
+ if err := configureMaintenanceApplier(a, env); err != nil {
+ return err
+ }
+ if a.channel != env["CARLOS_SYSTEM_CHANNEL"] || a.optDir != fake.optDir || a.dataDir != fake.dataDir || a.etcDir != fake.etcDir || a.groupMaintenance != fake.groupMaintenance {
+ t.Fatal("configuration lost channel, locked roots or guard")
+ }
+ for _, key := range []string{"CARLOS_RELEASE_PUBKEY", "CARLOS_DEPLOYMENT_BUCKET", "CARLOS_OPT_DIR", "CARLOS_DATA_DIR"} {
+ if os.Getenv(key) != env[key] {
+ t.Fatalf("configuration did not replace %s", key)
+ }
+ }
+ if os.Getenv("CARLOS_MAINTENANCE_TEST") != "" || os.Getenv("AWS_PROFILE") != "" || os.Getenv("INVOCATION_ID") != "" || !a.handRun {
+ t.Fatal("caller environment survived configuration")
+ }
+ if os.Getenv("PATH") != "/usr/sbin:/usr/bin:/sbin:/bin" || os.Getenv("AWS_MAX_ATTEMPTS") != "1" {
+ t.Fatal("missing fixed execution environment")
+ }
+ // The production constructor and environment selection have run. Keep
+ // all I/O local: use the signed fixture store and fake box operations.
+ a.openStore = func(context.Context) (release.Store, ed25519.PublicKey, error) {
+ pub, err := release.ParsePublicKey(os.Getenv("CARLOS_RELEASE_PUBKEY"), "CARLOS_RELEASE_PUBKEY")
+ if !bytes.Equal(pub, f.pub) {
+ t.Fatal("wrong configured verification key")
+ }
+ if os.Getenv("CARLOS_DEPLOYMENT_BUCKET") != env["CARLOS_DEPLOYMENT_BUCKET"] {
+ t.Fatal("wrong configured bucket")
+ }
+ return f.store, pub, err
+ }
+ a.ops, a.platform, a.build, a.soak = fake.ops, fake.platform, fake.build, fake.soak
+ a.floorHook, a.rootMoves, a.openRegistry = fake.floorHook, fake.rootMoves, fake.openRegistry
+ return nil
+ }
+ return &configured
+}
+
+func TestGroupMaintenanceConfiguredApply(t *testing.T) {
+ for _, permit := range []bool{false, true} {
+ t.Run(map[bool]string{false: "no-permit", true: "permit"}[permit], func(t *testing.T) {
+ f, p, cmd := maintenancePrepareFixture(t)
+ configured := maintenanceProductionConfigure(t, f, cmd)
+ t.Setenv("CARLOS_SYSTEM_CHANNEL", "canary")
+ t.Setenv("CARLOS_OPT_DIR", t.TempDir())
+ t.Setenv("CARLOS_DATA_DIR", t.TempDir())
+ t.Setenv("CARLOS_RELEASE_PUBKEY", "wrong")
+ t.Setenv("CARLOS_DEPLOYMENT_BUCKET", "wrong")
+ t.Setenv("AWS_PROFILE", "wrong")
+ t.Setenv("INVOCATION_ID", "wrong")
+ if _, err := runMaintenanceVerb(cmd, "prepare", nil); err != nil {
+ t.Fatal(err)
+ }
+ if permit {
+ b, _ := json.Marshal(p)
+ if _, err := runMaintenanceVerb(cmd, "permit", b); err != nil {
+ t.Fatal(err)
+ }
+ }
+ // Model a new operator shell which has not sourced host.env.
+ if err := os.Setenv("CARLOS_SYSTEM_CHANNEL", "canary"); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.Setenv("CARLOS_MAINTENANCE_TEST", "1"); err != nil {
+ t.Fatal(err)
+ }
+ f.a.channel = "canary"
+ _, err := runMaintenanceVerb(cmd, "apply", nil)
+ if *configured != 2 {
+ t.Fatalf("configure calls = %d; apply error = %v", *configured, err)
+ }
+ if !permit {
+ if !errors.Is(err, errGroupMaintenance) || len(f.calls) != 0 || !groupArtifactHolds(systemBinaryPath(f.a.optDir), p.OldSHA256) {
+ t.Fatalf("unguarded apply: %v %v", err, f.calls)
+ }
+ if _, err := os.Stat(f.a.stagingDir()); !os.IsNotExist(err) {
+ t.Fatalf("unguarded staging: %v", err)
+ }
+ } else if err != nil || !groupArtifactHolds(systemBinaryPath(f.a.optDir), p.NewSHA256) || f.result() == nil || f.result().Outcome != systemOutcomeApplied || f.result().Channel != "stable" || !f.called("systemctl restart carlos-edge") {
+ t.Fatalf("configured apply: %v %+v %v", err, f.result(), f.calls)
+ }
+ })
+ }
+}
+
+func TestGroupMaintenanceApplyEntry(t *testing.T) {
+ verb, _, err := maintenanceArguments([]string{"apply"})
+ if err != nil || verb != "apply" {
+ t.Errorf("apply arguments: %q %v", verb, err)
+ }
+ if _, _, err := maintenanceArguments([]string{"apply", "extra"}); err == nil {
+ t.Fatal("accepted apply arguments")
+ }
+ for _, bad := range []string{"fixed", "marker", "not-root", "busy", "config"} {
+ t.Run(bad, func(t *testing.T) {
+ f, p, cmd := maintenancePrepareFixture(t)
+ switch bad {
+ case "fixed":
+ os.Remove(filepath.Join(f.a.etcDir, "carlos", "group.json"))
+ case "marker":
+ os.WriteFile(filepath.Join(f.a.etcDir, "carlos", "group.json"), []byte("{}"), 0644)
+ case "not-root":
+ cmd.euid = func() int { return 1 }
+ case "config":
+ os.Remove(filepath.Join(f.a.etcDir, "carlos", "host.env"))
+ case "busy":
+ lock, err := openMaintenanceLock(f.a.lockPath(), true)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer lock.Close()
+ if err := flockExclusiveNonblock(lock); err != nil {
+ t.Fatal(err)
+ }
+ }
+ cmd.configure = func(*systemApplier, map[string]string) error { t.Fatal("configured before local refusal"); return nil }
+ if _, err := runMaintenanceVerb(cmd, "apply", nil); err == nil {
+ t.Fatal("accepted " + bad)
+ }
+ if len(f.calls) != 0 || !groupArtifactHolds(systemBinaryPath(f.a.optDir), p.OldSHA256) {
+ t.Fatal("refusal changed box")
+ }
+ })
+ }
+ for _, phrase := range []string{"group-maintenance apply", "never bare", "five minutes", "previous_result", "a lower bound, up to one second early; compare with a generation at least one second later and check the edge identity has not changed"} {
+ if !strings.Contains(groupMaintenanceHelp, phrase) {
+ t.Errorf("help missing %q", phrase)
+ }
+ }
+}
+
+type maintenanceDeadlineStore struct {
+ release.Store
+ t *testing.T
+ deadline time.Time
+ cancel context.CancelFunc
+ key string
+}
+
+func (s *maintenanceDeadlineStore) Get(ctx context.Context, key string) ([]byte, string, error) {
+ s.t.Helper()
+ deadline, ok := ctx.Deadline()
+ if !ok || time.Until(deadline) > 5*time.Minute || time.Until(deadline) <= 0 {
+ s.t.Fatal("prepare GET has no five-minute deadline")
+ }
+ if !s.deadline.IsZero() && !s.deadline.Equal(deadline) {
+ s.t.Fatal("GET reset the total deadline")
+ }
+ s.deadline = deadline
+ if strings.Contains(key, s.key) {
+ s.cancel()
+ <-ctx.Done()
+ return nil, "", ctx.Err()
+ }
+ return s.Store.Get(ctx, key)
+}
+
+func TestGroupMaintenancePrepareDeadline(t *testing.T) {
+ for _, phase := range []string{"pointer", "artifact"} {
+ t.Run(phase, func(t *testing.T) {
+ f, p, cmd := maintenancePrepareFixture(t)
+ ctx, cancel := context.WithCancel(t.Context())
+ defer cancel()
+ key := release.SystemPointerKey("router", f.a.channel)
+ if phase == "artifact" {
+ key = release.SystemArtifactKey("v2.0.0", f.a.platform)
+ }
+ store := &maintenanceDeadlineStore{Store: f.store, t: t, cancel: cancel, key: key}
+ f.a.openStore = func(ctx context.Context) (release.Store, ed25519.PublicKey, error) {
+ if deadline, ok := ctx.Deadline(); !ok || time.Until(deadline) > 5*time.Minute {
+ t.Fatal("store open is unbounded")
+ }
+ return store, f.pub, nil
+ }
+ if err := cmd.run(ctx, "prepare", strings.NewReader(""), io.Discard); !errors.Is(err, context.Canceled) {
+ t.Fatalf("cancel: %v", err)
+ }
+ if len(f.calls) != 0 || !groupArtifactHolds(systemBinaryPath(f.a.optDir), p.OldSHA256) {
+ t.Fatal("canceled prepare changed system")
+ }
+ if _, err := os.Stat(systemRequestPath(f.a.dataDir)); !os.IsNotExist(err) {
+ t.Fatalf("canceled request: %v", err)
+ }
+ if _, err := runMaintenanceVerb(cmd, "revoke", nil); err != nil {
+ t.Fatalf("lock retained: %v", err)
+ }
+ entries, err := os.ReadDir(f.a.rootDir())
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, entry := range entries {
+ if strings.HasPrefix(entry.Name(), ".prepare-") {
+ t.Fatal("scratch retained on cancellation")
+ }
+ }
+ })
+ }
+}
+
+func TestGroupMaintenancePreparePreviousResult(t *testing.T) {
+ for _, mode := range []string{systemOutcomeApplied, systemOutcomeRolledBack, systemOutcomeRollbackFailed, "other-channel", "other-version", "other-promotion", systemOutcomeRefused, "corrupt"} {
+ t.Run(mode, func(t *testing.T) {
+ f, _, cmd := maintenancePrepareFixture(t)
+ p, _, err := release.GetSystemPointer(t.Context(), f.store, f.pub, "router", f.a.channel)
+ if err != nil {
+ t.Fatal(err)
+ }
+ previous := systemResult{Channel: f.a.channel, Version: p.Current.Version, PromotedAt: p.PromotedAt, Outcome: systemOutcomeRolledBack, At: f.now}
+ skip := false
+ switch mode {
+ case systemOutcomeApplied, systemOutcomeRolledBack, systemOutcomeRollbackFailed:
+ previous.Outcome = mode
+ skip = true
+ case "other-channel":
+ previous.Channel = "canary"
+ case "other-version":
+ previous.Version = "v1.5.0"
+ case "other-promotion":
+ previous.PromotedAt = previous.PromotedAt.Add(-time.Second)
+ case systemOutcomeRefused:
+ previous.Outcome = mode
+ }
+ if err := writeJSONDurable(f.a.file("result.json"), previous, 0644); err != nil {
+ t.Fatal(err)
+ }
+ if mode == "corrupt" {
+ if err := os.WriteFile(f.a.file("result.json"), []byte("{"), 0644); err != nil {
+ t.Fatal(err)
+ }
+ }
+ raw, err := runMaintenanceVerb(cmd, "prepare", nil)
+ if mode == "corrupt" {
+ if err == nil {
+ t.Fatal("ignored unreadable result")
+ }
+ return
+ }
+ if err != nil {
+ t.Fatal(err)
+ }
+ var got struct {
+ Previous *string `json:"previous_result"`
+ Written bool `json:"request_written"`
+ }
+ if err := json.Unmarshal(raw, &got); err != nil {
+ t.Fatal(err)
+ }
+ if got.Written == skip {
+ t.Fatalf("request_written: %s", raw)
+ }
+ if skip && (got.Previous == nil || *got.Previous != mode) {
+ t.Fatalf("missing previous result: %s", raw)
+ }
+ if !skip && mode != systemOutcomeRefused && got.Previous != nil {
+ t.Fatalf("unrelated previous result: %s", raw)
+ }
+ if skip {
+ if _, err := os.Stat(systemRequestPath(f.a.dataDir)); !os.IsNotExist(err) {
+ t.Fatalf("completed tuple request: %v", err)
+ }
+ }
+ after, err := readSystemResult(f.a.optDir)
+ if err != nil || !reflect.DeepEqual(after, &previous) {
+ t.Fatalf("changed previous result: %+v %v", after, err)
+ }
+ })
+ }
+}
+
+func TestGroupMaintenancePrepareStaleScratch(t *testing.T) {
+ f, _, cmd := maintenancePrepareFixture(t)
+ stale, err := os.MkdirTemp(f.a.rootDir(), ".prepare-")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filepath.Join(stale, "partial"), []byte("partial"), 0600); err != nil {
+ t.Fatal(err)
+ }
+ keep := filepath.Join(f.a.rootDir(), ".prepare-operator-notes")
+ outside := t.TempDir()
+ for _, dir := range []string{keep, filepath.Join(f.a.rootDir(), "staging")} {
+ if err := os.MkdirAll(dir, 0700); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if err := os.WriteFile(filepath.Join(outside, "keep"), []byte("keep"), 0600); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.Symlink(outside, filepath.Join(f.a.rootDir(), ".prepare-12345")); err != nil {
+ t.Fatal(err)
+ }
+ f.a.openStore = func(context.Context) (release.Store, ed25519.PublicKey, error) {
+ if _, err := os.Stat(stale); !os.IsNotExist(err) {
+ t.Fatal("stale scratch remains at store open")
+ }
+ return f.store, f.pub, nil
+ }
+ if _, err := runMaintenanceVerb(cmd, "prepare", nil); err != nil {
+ t.Fatal(err)
+ }
+ for _, path := range []string{keep, filepath.Join(f.a.rootDir(), "staging"), filepath.Join(outside, "keep")} {
+ if _, err := os.Stat(path); err != nil {
+ t.Fatalf("removed unrelated file %s: %v", path, err)
+ }
+ }
+}
diff --git a/internal/host/group_maintenance_verbs.go b/internal/host/group_maintenance_verbs.go
index bfc737946..c3c2cbcf2 100644
--- a/internal/host/group_maintenance_verbs.go
+++ b/internal/host/group_maintenance_verbs.go
@@ -18,19 +18,27 @@ import (
"github.com/carlosframework/platform/internal/release"
)
-const groupMaintenanceHelp = `Usage: carlos system group-maintenance {status|permit|revoke|prepare|rollback}
+const groupMaintenanceHelp = `Usage: carlos system group-maintenance {status|permit|revoke|prepare|apply|rollback}
Root only, on a group member. Use through the attended Session Manager operator.
prepare --sha256 <digest>
Verify the configured signed pointer, cache its artifact and write a request.
Check local restart configuration. No staging, repoint or restart.
Makes cloud GETs only when attended and operator-invoked, never on a timer.
+ The total prepare timeout is five minutes.
+ previous_result reports the last outcome for this exact promotion.
+ An applied, rolled-back or rollback-failed result leaves request_written false.
+ apply Run the normal permit-gated apply using the checked local host.env.
+ On a group member use carlos system group-maintenance apply, never bare
+ carlos system apply.
rollback Restore this member's previous artifact using an explicit rollback permit.
Use the same transaction and old/new digests after revoking the apply permit.
Local only. A consumed rollback permit cannot be replayed.
permit Read at most 4096 bytes of permit JSON from stdin and install it.
revoke Remove the permit. Keep all consumed-action records.
status Print one v1 JSON object, at most 8192 bytes. Make one local health GET.
-Status includes edge.started_at in UTC, derived from kernel boot time and clock ticks.
+Status includes edge.started_at in UTC at second precision, derived from kernel boot time and clock ticks.
+It is a lower bound, up to one second early; compare with a generation at least one second later and check the edge identity has not changed.
+Clock errors are in edge.started_at_error; edge.error describes the process.
accepted means the guard's validators accept this permit now; it is not readiness: check the action and its consumed flag too.
Status is local evidence, not proof of fresh admission or role publication.
Present and accepted is still not authorization for the operator.
@@ -42,7 +50,7 @@ refuses the command. Unknown status fields are null or state "unknown".
`
// RunGroupMaintenance returns an exit code so command errors never log.Fatal
-// inside tests. Only prepare opens a store; status remains local.
+// inside tests. Prepare and apply open a store; status remains local.
func RunGroupMaintenance(args []string, in io.Reader, out, stderr io.Writer) int {
if len(args) == 1 && (args[0] == "help" || args[0] == "-h" || args[0] == "--help") {
if _, err := io.WriteString(out, groupMaintenanceHelp); err != nil {
@@ -93,7 +101,7 @@ func (cmd *groupMaintenanceCommand) run(ctx context.Context, verb string, in io.
if c == nil {
return errors.New("group marker required")
}
- if verb != "permit" && verb != "revoke" && verb != "status" && verb != "prepare" && verb != "rollback" {
+ if verb != "permit" && verb != "revoke" && verb != "status" && verb != "prepare" && verb != "apply" && verb != "rollback" {
return errors.New("unknown operation")
}
// Use the same lock and refusal behavior as system apply. Refuse before
@@ -131,6 +139,9 @@ func (cmd *groupMaintenanceCommand) run(ctx context.Context, verb string, in io.
if verb == "prepare" {
return cmd.prepare(ctx, c, out)
}
+ if verb == "apply" {
+ return cmd.apply(ctx, c)
+ }
if verb == "rollback" {
return cmd.rollback(ctx, c)
}
@@ -196,12 +207,13 @@ type groupMaintenanceStatus struct {
Health maintenanceHealthStatus `json:"health"`
}
type maintenanceProcessStatus struct {
- State string `json:"state"`
- PID *int `json:"pid"`
- StartTime *string `json:"start_time"`
- StartedAt *string `json:"started_at"`
- Identity *string `json:"identity"`
- Error *string `json:"error"`
+ State string `json:"state"`
+ PID *int `json:"pid"`
+ StartTime *string `json:"start_time"`
+ StartedAt *string `json:"started_at"`
+ StartedAtError *string `json:"started_at_error"`
+ Identity *string `json:"identity"`
+ Error *string `json:"error"`
}
type maintenancePermitStatus struct {
State string `json:"state"`
@@ -316,12 +328,12 @@ func (cmd *groupMaintenanceCommand) status(ctx context.Context, c *hostenv.Group
if cmd.startedAt != nil {
at, err := cmd.startedAt(start)
if err != nil {
- s.Edge.Error = maintenanceError(err)
+ s.Edge.StartedAtError = maintenanceError(err)
} else {
s.Edge.StartedAt = &at
}
} else {
- s.Edge.Error = maintenanceError(errors.New("process clock unavailable"))
+ s.Edge.StartedAtError = maintenanceError(errors.New("process clock unavailable"))
}
} else {
if processErr == nil {
@@ -358,7 +370,7 @@ func maintenanceArguments(args []string) (string, string, error) {
}
return "prepare", *digest, nil
}
- if len(args) == 1 && (args[0] == "permit" || args[0] == "revoke" || args[0] == "status" || args[0] == "rollback") {
+ if len(args) == 1 && (args[0] == "permit" || args[0] == "revoke" || args[0] == "status" || args[0] == "apply" || args[0] == "rollback") {
return args[0], "", nil
}
return "", "", errGroupMaintenance