carlos / platform Public

system update: same-second replay refused, and no-op decided from the installed binary (hunt H6-M11, H6-M12)

H6-M11. seen.json kept one promoted_at per channel and refused only a
pointer strictly older than it. PromoteSystem stamps whole seconds, so two
promotions of a channel in one second share a stamp, and a bucket writer who
saved the first could put it back after a box took the second: equal passed
the floor, root installed the superseded build, and the agent scheduled it
first. The watermark now has a second half, seen-versions.json, the version
admitted at the stamp. systemSeenAdmits is the one rule both halves of the
box apply: later is news, older is a replay, and at the same stamp the
pointer must be the admitted one (the retry the spec allows) or list it in
its History (a successor signed in the same second does; a saved predecessor
cannot). This is the system-pointer twin of release's watermark.admits
(H3-M5); seen.json keeps its shape, so a channel with a stamp and no version
yet keeps the stamp-only rule until its next admission. carlos system
install writes both halves too.

H6-M12. Root took the request's noop at its word and wrote noted without
asking the installed binary; a uid-carlos writer who flipped the flag on a
pending update left a noted result the agent read as done, until a different
promotion. Noted now follows only from the installed binary's version. A
request that still says no-op for a build this box is not on is deferred,
not installed and not noted: a no-op fetched nothing into the cache, and
deferred is the outcome the agent answers by writing its own request again.

Tests: the verifier's H6-M11 and H6-M12 tests, plus deterministic cases for
the floor (strictly later passes and advances both halves; same-second
predecessor refused by root and skipped by the agent; same-second retry
proceeds) and for the deferred no-op. TestApplyReplayGuard's box is now on
the no-op's version, since the request alone no longer makes one; the no-op
test allows the one command that decides it, the installed binary's version.
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude Fable (hunt fix) pushed by claude agent, operated by paul@keymail.dev a4ade4d4a81306c1e5a909bec3490874d720ad41 parent 0e2afda
8 files changed, +494 −12
  • internal/host/hunt_H6-M11_test.go +129 −0
  • internal/host/hunt_H6-M12_test.go +98 −0
  • internal/host/installchannel.go +5 −2
  • internal/host/systemapply.go +24 −6
  • internal/host/systemapply_test.go +9 −3
  • internal/host/systemleg.go +2 −1
  • internal/host/systemseen_test.go +165 −0
  • internal/host/systemstate.go +62 −0
diff --git a/internal/host/hunt_H6-M11_test.go b/internal/host/hunt_H6-M11_test.go
new file mode 100644
index 000000000..38ecee8c5
--- /dev/null
+++ b/internal/host/hunt_H6-M11_test.go
@@ -0,0 +1,129 @@
+package host
+
+import (
+ "context"
+ "crypto/sha256"
+ "encoding/hex"
+ "os"
+ "path/filepath"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/release"
+)
+
+// huntPromoteRaw signs a stable pointer for version through the real
+// PromoteSystem and mirrors its artifact, returning the pointer and the
+// exact signed wrapper bytes a bucket reader could save.
+func huntPromoteRaw(t *testing.T, f *applyFixture, version string, body []byte) (*release.SystemPointer, []byte) {
+ t.Helper()
+ ctx := context.Background()
+ sum := sha256.Sum256(body)
+ rel := release.SystemRelease{Version: version, Artifacts: map[string]release.SystemArtifact{
+ "linux-arm64": {Key: release.SystemArtifactKey(version, "linux-arm64"), SHA256: hex.EncodeToString(sum[:])}}}
+ if _, err := f.store.Put(ctx, rel.Artifacts["linux-arm64"].Key, body, ""); err != nil {
+ t.Fatal(err)
+ }
+ p, err := release.PromoteSystem(ctx, f.store, release.RootSigner(f.priv), "router", f.a.channel, rel, release.SystemPromoteOptions{})
+ if err != nil {
+ t.Fatal(err)
+ }
+ raw, _, err := f.store.Get(ctx, release.SystemPointerKey("router", f.a.channel))
+ if err != nil {
+ t.Fatal(err)
+ }
+ return p, raw
+}
+
+// huntScriptCandidate makes the staged candidate answer as version, the way
+// applyHappyVersion scripts the external `carlos version`/`bootstrap -root`.
+func huntScriptCandidate(f *applyFixture, version string) {
+ staged := filepath.Join(f.a.stagingDir(), "carlos")
+ f.answer["version:"+staged] = "carlos " + version + "\n"
+ f.answer["plan:"+staged] = `{"enabled":["carlos-edge.service","carlos-adopt.timer","carlos-adopt.path","carlos-stage.path","carlos-restart.path","carlos-system-update.path","carlos-system-recover.service"],"inert":["carlos-restore-verify.timer"]}`
+ f.answer["units:"+staged] = "carlos-edge.service carlos-adopt.timer carlos-adopt.path carlos-stage.path carlos-restart.path carlos-system-update.path carlos-system-update.service carlos-system-recover.service carlos-instance-control.service"
+ prev := systemPrevPath(f.a.optDir)
+ f.answer["plan:"+prev] = f.answer["plan:"+staged]
+ f.answer["units:"+prev] = f.answer["units:"+staged]
+ delete(f.answer, "version:"+systemBinaryPath(f.a.optDir))
+ delete(f.answer, "version:"+prev)
+}
+
+// H6-M11: two distinct signed promotions A (v2) then B (v3) of the same
+// channel within one second carry equal PromotedAt. The box accepts B; a
+// bucket writer restores A's saved wrapper. SECURE expectation: A is refused
+// as a superseded promotion, by the agent and by root.
+func TestHunt_H6_M11_SameSecondSupersededPromotionIsRefused(t *testing.T) {
+ var (
+ f *applyFixture
+ pA, pB *release.SystemPointer
+ savedA []byte
+ bodyA = []byte("#!/bin/sh\necho carlos v2\n")
+ bodyB = []byte("#!/bin/sh\necho carlos v3\n")
+ gotEqual bool
+ )
+ for attempt := 0; attempt < 5 && !gotEqual; attempt++ {
+ // Start just after a second boundary so both promotes land in it.
+ now := time.Now()
+ time.Sleep(time.Until(now.Truncate(time.Second).Add(time.Second + 5*time.Millisecond)))
+ f = newApplyFixture(t, "stable", "v1")
+ pA, savedA = huntPromoteRaw(t, f, "v2", bodyA)
+ pB, _ = huntPromoteRaw(t, f, "v3", bodyB)
+ gotEqual = pA.PromotedAt.Equal(pB.PromotedAt)
+ }
+ if !gotEqual {
+ t.Skip("could not land two promotions in one second")
+ }
+ if pA.Current.Version == pB.Current.Version {
+ t.Fatal("setup: A and B must be different promotions")
+ }
+
+ // The box takes B through the real agent leg and root apply.
+ leg := huntLegFor(f, "v1")
+ leg.observe(context.Background())
+ leg.tick(context.Background(), leg.now())
+ if r := readHuntRequest(t, f.a.dataDir); r == nil || r.Version != "v3" {
+ t.Fatalf("setup: agent request for B = %+v", r)
+ }
+ huntScriptCandidate(f, "v3")
+ if err := f.a.Run(context.Background(), false); err != nil {
+ t.Fatal(err)
+ }
+ if r := f.result(); r == nil || r.Outcome != systemOutcomeApplied || f.onDisk() != "v3" {
+ t.Fatalf("setup: B not applied: %+v on disk %q", r, f.onDisk())
+ }
+ seen, _ := readSystemSeen(f.a.optDir)
+ if !seen["stable"].Equal(pB.PromotedAt) {
+ t.Fatalf("setup: watermark %v, want B's %v", seen["stable"], pB.PromotedAt)
+ }
+
+ // The attacker restores A's authentic wrapper at the channel key.
+ _, etag, _ := f.store.Get(context.Background(), release.SystemPointerKey("router", "stable"))
+ if _, err := f.store.Put(context.Background(), release.SystemPointerKey("router", "stable"), savedA, etag); err != nil {
+ t.Fatal(err)
+ }
+
+ // The agent, now running v3, observes and ticks.
+ os.Remove(systemRequestPath(f.a.dataDir))
+ leg = huntLegFor(f, "v3")
+ leg.observe(context.Background())
+ leg.tick(context.Background(), leg.now())
+ if r := readHuntRequest(t, f.a.dataDir); r != nil && r.Version == "v2" {
+ t.Errorf("H6-M11 agent: scheduled the replayed same-second promotion A (v2@%s) after accepting B (v3@%s); systemleg.go:117 rejects only strictly older",
+ pA.PromotedAt.Format(time.RFC3339), pB.PromotedAt.Format(time.RFC3339))
+ } else {
+ // Make root's check reachable anyway: the request a uid-carlos
+ // writer (or this agent) would leave.
+ writeJSONDurable(systemRequestPath(f.a.dataDir), systemRequest{Version: "v2", PromotedAt: pA.PromotedAt, SeenAt: leg.now()}, 0o644)
+ os.MkdirAll(filepath.Dir(systemCachePath(f.a.dataDir, "v2")), 0o755)
+ os.WriteFile(systemCachePath(f.a.dataDir, "v2"), bodyA, 0o644)
+ }
+ huntScriptCandidate(f, "v2")
+ if err := f.a.Run(context.Background(), false); err != nil {
+ t.Fatal(err)
+ }
+ r := f.result()
+ if onDisk := f.onDisk(); onDisk != "v3" || (r != nil && r.Version == "v2" && r.Outcome == systemOutcomeApplied) {
+ t.Errorf("H6-M11 root: replayed superseded promotion A installed: result %+v, on disk %q (systemapply.go:423 rejects only strictly older PromotedAt)", r, onDisk)
+ }
+}
diff --git a/internal/host/hunt_H6-M12_test.go b/internal/host/hunt_H6-M12_test.go
new file mode 100644
index 000000000..a6568cc72
--- /dev/null
+++ b/internal/host/hunt_H6-M12_test.go
@@ -0,0 +1,98 @@
+package host
+
+import (
+ "context"
+ "os"
+ "testing"
+ "time"
+)
+
+// huntLegFor builds the production systemLeg over an applyFixture's store,
+// key and directories: the agent half of the same box root's applier serves.
+func huntLegFor(f *applyFixture, build string) *systemLeg {
+ getenv := func(k string) string {
+ if k == systemChannelEnv {
+ return f.a.channel
+ }
+ return ""
+ }
+ leg := newSystemLeg(f.store, f.pub, getenv, f.a.dataDir, f.a.optDir)
+ leg.build = build
+ leg.platform = "linux-arm64"
+ now := time.Date(2026, 9, 6, 12, 0, 0, 0, time.UTC)
+ leg.now = func() time.Time { return now }
+ leg.jitter = func(time.Duration) time.Duration { return 0 }
+ leg.logf = f.t.Logf
+ return leg
+}
+
+// H6-M12: a uid-carlos writer flips noop=true in the agent's request for a
+// pending signed update. Root verifies the pointer and the tuple, then trusts
+// req.NoOp and writes "noted" without checking the installed build. SECURE
+// expectation: a box still running v1 never records v2 as noted, and the
+// agent eventually requests the real install.
+func TestHunt_H6_M12_ForgedNoOpCannotSuppressASignedUpdate(t *testing.T) {
+ f, req := applyHappy(t) // box on v1; signed stable pointer names v2; agent request written
+ // The attacker's one edit: same Version and PromotedAt, noop=true.
+ forged := req
+ forged.NoOp = true
+ if err := writeJSONDurable(systemRequestPath(f.a.dataDir), forged, 0o644); err != nil {
+ t.Fatal(err)
+ }
+ // Then touches the path-unit trigger; root's update service runs.
+ if err := f.a.Run(context.Background(), false); err != nil {
+ t.Fatal(err)
+ }
+ r := f.result()
+ onDisk := f.onDisk()
+ if r != nil && r.Outcome == systemOutcomeNoted && onDisk != "v2" {
+ t.Errorf("H6-M12 root: forged noop request recorded %s@%s as %q while the installed build is %q (systemapply.go:434 trusts req.NoOp)",
+ r.Version, r.PromotedAt.Format(time.RFC3339), r.Outcome, onDisk)
+ }
+
+ // The attacker stops. The agent (still v1) keeps observing and ticking.
+ leg := huntLegFor(f, "v1")
+ requested := false
+ for i := 0; i < 5; i++ {
+ os.Remove(systemRequestPath(f.a.dataDir)) // only a request the agent writes counts
+ leg.lastObserve = time.Time{}
+ leg.observe(context.Background())
+ leg.tick(context.Background(), leg.now().Add(time.Duration(i)*time.Minute))
+ if got := readHuntRequest(t, f.a.dataDir); got != nil && got.Version == "v2" && !got.NoOp {
+ requested = true
+ break
+ }
+ }
+ if !requested {
+ t.Errorf("H6-M12 agent: after the forged noop the agent never re-requests the v2 install (systemleg.go:173-180 drops pending on the matching noted result); on disk %q", f.onDisk())
+ }
+}
+
+func readHuntRequest(t *testing.T, dataDir string) *systemRequest {
+ t.Helper()
+ var r systemRequest
+ if err := readJSONFile(systemRequestPath(dataDir), &r); err != nil {
+ return nil
+ }
+ return &r
+}
+
+// Control for H6-M12: with no forged noop, the same agent loop requests the
+// v2 install, and root installs it. Proves the loop above can succeed.
+func TestHunt_H6_M12_ControlAgentRequestsAndRootInstallsWithoutForgery(t *testing.T) {
+ f, _ := applyHappy(t)
+ os.Remove(systemRequestPath(f.a.dataDir))
+ leg := huntLegFor(f, "v1")
+ leg.observe(context.Background())
+ leg.tick(context.Background(), leg.now())
+ got := readHuntRequest(t, f.a.dataDir)
+ if got == nil || got.Version != "v2" || got.NoOp {
+ t.Fatalf("control: agent request = %+v, want v2 noop=false", got)
+ }
+ if err := f.a.Run(context.Background(), false); err != nil {
+ t.Fatal(err)
+ }
+ if r := f.result(); r == nil || r.Outcome != systemOutcomeApplied || f.onDisk() != "v2" {
+ t.Fatalf("control: result %+v, on disk %q", r, f.onDisk())
+ }
+}
diff --git a/internal/host/installchannel.go b/internal/host/installchannel.go
index 9410b90e4..0e210dba9 100644
--- a/internal/host/installchannel.go
+++ b/internal/host/installchannel.go
@@ -420,8 +420,11 @@ func (in channelInstall) install(ctx context.Context) (channelInstalled, error)
if err != nil {
return got, err
}
- seen[a.channel] = p.PromotedAt
- if err := writeJSONDurable(a.file("seen.json"), seen, 0o644); err != nil {
+ versions, err := readSystemSeenVersions(a.optDir)
+ if err != nil {
+ return got, err
+ }
+ if err := systemSeenAdvance(a.optDir, seen, versions, a.channel, p); err != nil {
return got, err
}
if err := writeJSONDurable(a.file("applied.json"), systemApplied{Version: p.Current.Version, Channel: a.channel, At: a.ops.now().UTC()}, 0o644); err != nil {
diff --git a/internal/host/systemapply.go b/internal/host/systemapply.go
index da966c116..7502d6b14 100644
--- a/internal/host/systemapply.go
+++ b/internal/host/systemapply.go
@@ -424,17 +424,35 @@ func (a *systemApplier) Run(ctx context.Context, recover bool) (retErr error) {
if err != nil {
return a.record(req, fmt.Errorf("%w: seen.json unreadable: %v", errSystemRefused, err))
}
- if wm, ok := seen[a.channel]; ok && p.PromotedAt.Before(wm) {
- return a.record(req, fmt.Errorf("%w: replay — pointer promoted %s is older than the %s watermark %s", errSystemRefused,
- p.PromotedAt.Format(time.RFC3339), a.channel, wm.Format(time.RFC3339)))
+ versions, err := readSystemSeenVersions(a.optDir)
+ if err != nil {
+ return a.record(req, fmt.Errorf("%w: seen-versions.json unreadable: %v", errSystemRefused, err))
+ }
+ // The replay floor (hunt H6-M11): a pointer no newer than the one this
+ // box already followed, unless it is that pointer or its same-second
+ // successor. systemSeenAdmits says which.
+ if !systemSeenAdmits(seen, versions, a.channel, p) {
+ return a.record(req, fmt.Errorf("%w: replay — pointer %s promoted %s is not after the %s watermark %s (%s)", errSystemRefused,
+ p.Current.Version, p.PromotedAt.Format(time.RFC3339), a.channel, seen[a.channel].Format(time.RFC3339), versions[a.channel]))
}
- seen[a.channel] = p.PromotedAt
- if err := writeJSONDurable(a.file("seen.json"), seen, 0o644); err != nil {
+ if err := systemSeenAdvance(a.optDir, seen, versions, a.channel, p); err != nil {
return err
}
- if req.NoOp || p.Current.Version == a.onDiskBuild(ctx) {
+ // Whether there is anything to install is the installed binary's to
+ // say, never the request's (hunt H6-M12): the request lives under /data,
+ // where every flat workload can rewrite it, and a forged noop that root
+ // took at its word left a noted result the agent read as "done". A
+ // request that says no-op for a build this box is not on is answered
+ // deferred rather than installed: a no-op fetched nothing into the
+ // cache, and deferred is the one outcome the agent answers by writing
+ // its request again, with what it sees.
+ if p.Current.Version == a.onDiskBuild(ctx) {
return a.writeResult(req, systemOutcomeNoted, "")
}
+ if req.NoOp {
+ return a.record(req, fmt.Errorf("%w: request says there is nothing to install, but the installed build is not %s; waiting for the agent's install request",
+ errSystemDeferred, p.Current.Version))
+ }
// The claim release floor's transaction (Plan 8) first, as on main;
// then the moves activation check. Either one refusing refuses; a
// moves refusal after beginGuard leaves no journal, so Run's deferred
diff --git a/internal/host/systemapply_test.go b/internal/host/systemapply_test.go
index ee79416d8..bea367350 100644
--- a/internal/host/systemapply_test.go
+++ b/internal/host/systemapply_test.go
@@ -270,7 +270,10 @@ func TestApplyStaleTupleIsRefusedAgainstTheRequestsTuple(t *testing.T) {
}
func TestApplyReplayGuardIsPerChannelAndEqualIsAllowed(t *testing.T) {
- f := newApplyFixture(t, "stable", "v1")
+ // The box is on v2, so the no-op request is one root agrees with from
+ // the installed binary (root no longer takes the request's word, hunt
+ // H6-M12); the test is about the floor, and ends each run at noted.
+ f := newApplyFixture(t, "stable", "v2")
req := f.promote("v2", []byte("x"), true)
// Older than the watermark → refused, seen unchanged.
writeJSONDurable(filepath.Join(systemRootDir(f.a.optDir), "seen.json"), systemSeen{"stable": req.PromotedAt.Add(time.Hour), "canary": time.Time{}}, 0o644)
@@ -314,8 +317,11 @@ func TestApplyNoOpNotesAndTouchesNothing(t *testing.T) {
if _, err := os.Stat(f.a.stagingDir()); err == nil {
t.Fatal("a no-op created staging/")
}
- if len(f.calls) != 0 {
- t.Fatalf("a no-op ran commands: %v", f.calls)
+ // The one command a no-op runs is the question that makes it one: the
+ // installed binary's version (hunt H6-M12: root decides from disk, not
+ // from the request's noop). Nothing is staged, installed or restarted.
+ if len(f.calls) != 1 || f.calls[0] != "run carlos version" {
+ t.Fatalf("a no-op ran commands: %v, want only the installed binary's version", f.calls)
}
}
diff --git a/internal/host/systemleg.go b/internal/host/systemleg.go
index 3396c851c..154089ade 100644
--- a/internal/host/systemleg.go
+++ b/internal/host/systemleg.go
@@ -115,7 +115,8 @@ func (l *systemLeg) observe(ctx context.Context) {
return
}
seen, _ := readSystemSeen(l.optDir)
- if wm, ok := seen[l.channel]; ok && p.PromotedAt.Before(wm) {
+ versions, _ := readSystemSeenVersions(l.optDir)
+ if !systemSeenAdmits(seen, versions, l.channel, p) {
return // root would refuse it as a replay
}
if res, _ := readSystemResult(l.optDir); res.matches(l.channel, p.Current.Version, p.PromotedAt) && res.terminal() {
diff --git a/internal/host/systemseen_test.go b/internal/host/systemseen_test.go
new file mode 100644
index 000000000..1eb3c09d6
--- /dev/null
+++ b/internal/host/systemseen_test.go
@@ -0,0 +1,165 @@
+package host
+
+import (
+ "context"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/release"
+)
+
+// The replay floor's same-second rule (hunt H6-M11), on the helper both
+// halves of the box call. PromoteSystem stamps whole seconds, so the stamp
+// alone cannot tell the pointer this box followed from a saved predecessor
+// signed in the same second; the admitted version beside it can.
+func TestSystemSeenAdmitsSameSecondSuccessorNotPredecessor(t *testing.T) {
+ at := time.Date(2026, 10, 25, 8, 0, 0, 0, time.UTC)
+ ptr := func(version string, promoted time.Time, history ...string) *release.SystemPointer {
+ p := &release.SystemPointer{Channel: "stable", Current: release.SystemRelease{Version: version}, PromotedAt: promoted}
+ for _, h := range history {
+ p.History = append(p.History, release.SystemRelease{Version: h})
+ }
+ return p
+ }
+ seen := systemSeen{"stable": at}
+ versions := systemSeenVersions{"stable": "v3"}
+ cases := []struct {
+ name string
+ seen systemSeen
+ versions systemSeenVersions
+ p *release.SystemPointer
+ want bool
+ }{
+ {"no entry for the channel admits the first pointer", systemSeen{}, systemSeenVersions{}, ptr("v2", at, "v1"), true},
+ {"strictly later is news", seen, versions, ptr("v4", at.Add(time.Second), "v3"), true},
+ {"strictly later is news whatever it lists", seen, versions, ptr("v2", at.Add(time.Second)), true},
+ {"older is a replay", seen, versions, ptr("v4", at.Add(-time.Second), "v3"), false},
+ {"same second, the admitted pointer again (a retry)", seen, versions, ptr("v3", at, "v2"), true},
+ {"same second, a successor listing the admitted version", seen, versions, ptr("v4", at, "v3", "v2"), true},
+ {"same second, a saved predecessor", seen, versions, ptr("v2", at, "v1"), false},
+ {"same second, a stranger", seen, versions, ptr("v9", at), false},
+ {"same second with no admitted version recorded keeps the stamp-only rule", seen, systemSeenVersions{}, ptr("v2", at, "v1"), true},
+ {"another channel's entry is not this channel's", systemSeen{"canary": at.Add(time.Hour)}, systemSeenVersions{"canary": "v9"}, ptr("v2", at), true},
+ }
+ for _, c := range cases {
+ if got := systemSeenAdmits(c.seen, c.versions, "stable", c.p); got != c.want {
+ t.Errorf("%s: admits = %v, want %v", c.name, got, c.want)
+ }
+ }
+}
+
+func writeSeenFixture(t *testing.T, optDir string, seen systemSeen, versions systemSeenVersions) {
+ t.Helper()
+ os.MkdirAll(systemRootDir(optDir), 0o755)
+ if err := writeJSONDurable(filepath.Join(systemRootDir(optDir), "seen.json"), seen, 0o644); err != nil {
+ t.Fatal(err)
+ }
+ if err := writeJSONDurable(filepath.Join(systemRootDir(optDir), "seen-versions.json"), versions, 0o644); err != nil {
+ t.Fatal(err)
+ }
+}
+
+// A genuine next promotion, stamped strictly after the watermark, still
+// passes the floor and is installed; both halves of the watermark advance.
+func TestApplyStrictlyLaterPromotionPassesTheFloor(t *testing.T) {
+ f, req := applyHappy(t)
+ writeSeenFixture(t, f.a.optDir, systemSeen{"stable": req.PromotedAt.Add(-time.Second)}, systemSeenVersions{"stable": "v1"})
+ if err := f.a.Run(context.Background(), false); err != nil {
+ t.Fatal(err)
+ }
+ if r := f.result(); r == nil || r.Outcome != systemOutcomeApplied || f.onDisk() != "v2" {
+ t.Fatalf("result %+v, on disk %q", r, f.onDisk())
+ }
+ seen, _ := readSystemSeen(f.a.optDir)
+ versions, _ := readSystemSeenVersions(f.a.optDir)
+ if !seen["stable"].Equal(req.PromotedAt) || versions["stable"] != "v2" {
+ t.Fatalf("watermark = %v / %v, want %v / v2", seen["stable"], versions["stable"], req.PromotedAt)
+ }
+}
+
+// Root's half of H6-M11 without racing a second boundary: the watermark
+// says a different version was admitted at this exact stamp, so the pointer
+// is a same-second predecessor put back, and is refused with the box as it
+// was. The same version at the same stamp is the retry the spec allows.
+func TestApplySameSecondSupersededPromotionIsRefusedButARetryProceeds(t *testing.T) {
+ f, req := applyHappy(t)
+ writeSeenFixture(t, f.a.optDir, systemSeen{"stable": req.PromotedAt}, systemSeenVersions{"stable": "v3"})
+ if err := f.a.Run(context.Background(), false); err != nil {
+ t.Fatal(err)
+ }
+ r := f.result()
+ if r == nil || r.Outcome != systemOutcomeRefused || !strings.Contains(r.Reason, "replay") || f.onDisk() != "v1" {
+ t.Fatalf("result %+v, on disk %q", r, f.onDisk())
+ }
+ if versions, _ := readSystemSeenVersions(f.a.optDir); versions["stable"] != "v3" {
+ t.Fatalf("a refused replay moved the watermark: %v", versions)
+ }
+ writeSeenFixture(t, f.a.optDir, systemSeen{"stable": req.PromotedAt}, systemSeenVersions{"stable": "v2"})
+ if err := f.a.Run(context.Background(), false); err != nil {
+ t.Fatal(err)
+ }
+ if r := f.result(); r == nil || r.Outcome != systemOutcomeApplied || f.onDisk() != "v2" {
+ t.Fatalf("retry of the admitted promote: result %+v, on disk %q", r, f.onDisk())
+ }
+}
+
+// Root's half of H6-M12 as an outcome: a request that says no-op for a build
+// this box is not on is deferred, not noted and not installed; the agent's
+// own install request for the same tuple then goes through.
+func TestApplyNoOpRequestForAnotherBuildIsDeferredNotNoted(t *testing.T) {
+ f, req := applyHappy(t)
+ forged := req
+ forged.NoOp = true
+ if err := writeJSONDurable(systemRequestPath(f.a.dataDir), forged, 0o644); err != nil {
+ t.Fatal(err)
+ }
+ if err := f.a.Run(context.Background(), false); err != nil {
+ t.Fatal(err)
+ }
+ if r := f.result(); r == nil || r.Outcome != systemOutcomeDeferred || !r.matches("stable", "v2", req.PromotedAt) || f.onDisk() != "v1" {
+ t.Fatalf("result %+v, on disk %q", r, f.onDisk())
+ }
+ if _, err := os.Stat(f.a.stagingDir()); err == nil {
+ t.Fatal("a no-op request staged a candidate")
+ }
+ if err := writeJSONDurable(systemRequestPath(f.a.dataDir), req, 0o644); err != nil {
+ t.Fatal(err)
+ }
+ if err := f.a.Run(context.Background(), false); err != nil {
+ t.Fatal(err)
+ }
+ if r := f.result(); r == nil || r.Outcome != systemOutcomeApplied || f.onDisk() != "v2" {
+ t.Fatalf("install request: result %+v, on disk %q", r, f.onDisk())
+ }
+}
+
+// The agent's half of H6-M11 without racing a second boundary: root's
+// watermark names another version at the pointer's exact stamp, so the agent
+// schedules nothing for it; with the pointer's own version recorded it is a
+// retry and is requested.
+func TestSystemLegSkipsASameSecondSupersededPromotion(t *testing.T) {
+ f := newLegFixture(t, "stable", "v1")
+ f.promote("v2", []byte("x"), 0)
+ p, _, err := release.GetSystemPointer(context.Background(), f.store, f.leg.pub, release.SystemComponentRouter, "stable")
+ if err != nil {
+ t.Fatal(err)
+ }
+ writeSeenFixture(t, f.opt, systemSeen{"stable": p.PromotedAt}, systemSeenVersions{"stable": "v3"})
+ f.leg.observe(context.Background())
+ f.leg.tick(context.Background(), f.now)
+ if f.leg.pending != nil {
+ t.Fatalf("scheduled a same-second superseded promotion: %+v", f.leg.pending)
+ }
+ if _, err := f.marker(); err == nil {
+ t.Fatal("requested a pointer root would refuse as a replay")
+ }
+ writeSeenFixture(t, f.opt, systemSeen{"stable": p.PromotedAt}, systemSeenVersions{"stable": "v2"})
+ f.leg.observe(context.Background())
+ f.leg.tick(context.Background(), f.now)
+ if r := f.request(); r == nil || r.Version != "v2" || r.NoOp {
+ t.Fatalf("retry of the admitted promote not requested: %+v", r)
+ }
+}
diff --git a/internal/host/systemstate.go b/internal/host/systemstate.go
index a9d59381a..73002222c 100644
--- a/internal/host/systemstate.go
+++ b/internal/host/systemstate.go
@@ -7,8 +7,10 @@ import (
"os"
"path/filepath"
"regexp"
+ "slices"
"time"
+ "github.com/carlosframework/platform/internal/release"
"github.com/carlosframework/platform/internal/safefile"
)
@@ -92,6 +94,54 @@ type systemApplied struct {
// has verified. Advanced on every verified pointer, including no-ops.
type systemSeen map[string]time.Time
+// systemSeenVersions is the other half of the watermark (hunt H6-M11): the
+// version of the pointer root admitted at seen.json's stamp, per channel,
+// in seen-versions.json beside it. PromoteSystem stamps whole seconds, so
+// two promotions of one channel in one second share a PromotedAt, and the
+// stamp alone cannot tell the one this box followed from a saved
+// predecessor put back at the channel key. A channel with a stamp but no
+// version (a box that last admitted a pointer before this file existed)
+// keeps the stamp-only rule until its next admission.
+type systemSeenVersions map[string]string
+
+// systemSeenAdmits is the replay floor both halves of the box apply to a
+// verified pointer: the agent before it schedules one (systemleg.go), root
+// before it acts on one (systemapply.go). It is the system-pointer twin of
+// release's watermark.admits. A later stamp is news. An older stamp is a
+// replay. The same stamp needs a closer look: the pointer already admitted
+// (a retry of the same promote, which the spec allows) passes; a successor
+// signed in the same second lists the admitted version at History[0], since
+// PromoteSystem and RollbackSystem both put the head they replace there,
+// and passes; a pointer saved before the admitted head lists neither and is
+// refused.
+func systemSeenAdmits(seen systemSeen, versions systemSeenVersions, channel string, p *release.SystemPointer) bool {
+ wm, ok := seen[channel]
+ switch {
+ case !ok || p.PromotedAt.After(wm):
+ return true
+ case p.PromotedAt.Before(wm):
+ return false
+ }
+ admitted, known := versions[channel]
+ if !known {
+ return true
+ }
+ return p.Current.Version == admitted || slices.ContainsFunc(p.History, func(r release.SystemRelease) bool { return r.Version == admitted })
+}
+
+// systemSeenAdvance records p as the newest pointer admitted on channel,
+// seen.json first and then seen-versions.json, both durable. A version write
+// that fails leaves the stamp in place with the previous version beside it,
+// which the next admission overwrites; the floor reads both.
+func systemSeenAdvance(optDir string, seen systemSeen, versions systemSeenVersions, channel string, p *release.SystemPointer) error {
+ seen[channel] = p.PromotedAt
+ versions[channel] = p.Current.Version
+ if err := writeJSONDurable(filepath.Join(systemRootDir(optDir), "seen.json"), seen, 0o644); err != nil {
+ return err
+ }
+ return writeJSONDurable(filepath.Join(systemRootDir(optDir), "seen-versions.json"), versions, 0o644)
+}
+
// systemJournal is the open transaction. Written before every box-changing
// step, removed last; a run that finds one recovers before anything else.
// Target and PromotedAt are the promote it belongs to: the same tuple the
@@ -207,6 +257,18 @@ func readSystemSeen(optDir string) (systemSeen, error) {
return s, err
}
+func readSystemSeenVersions(optDir string) (systemSeenVersions, error) {
+ v := systemSeenVersions{}
+ err := readJSONFile(filepath.Join(systemRootDir(optDir), "seen-versions.json"), &v)
+ if errors.Is(err, os.ErrNotExist) {
+ return systemSeenVersions{}, nil
+ }
+ if v == nil {
+ v = systemSeenVersions{}
+ }
+ return v, err
+}
+
func readSystemApplied(optDir string) (*systemApplied, error) {
var a systemApplied
err := readJSONFile(filepath.Join(systemRootDir(optDir), "applied.json"), &a)