carlos / platform Public

cold handover admits only a fresh successor; startup settles obsolete barriers (roster binding task 6b, N5, B1, B3)

Root's operation cold handover (serveColdHandover and RecoverPending's
journal recovery) runs admitColdSuccessor before Run takes any step:
RequireNewWork, then the successor's box, enrollment and binding against
the fresh InventoryActor (hostbox ColdHandover.Admit). A replay of a
journaled handover whose successor binding changed is refused.

At startup a journaled handover whose successor binding is not the
startup binding is settled, never resumed (ColdHandover.Obsolete):
hostguard SettleObsoleteColdHandover, under the host lock and only for a
prior with a completed receipt, undoes BeginColdHandover (the deny slot
back to the prior's completed fence), retires the successor's stamp, and
the journal is marked settled; logged. No claim session advance needed.

N5 TestColdHandoverVerifiesSuccessorAtRoot; B1/B3
TestColdHandoverObsoleteBarrierSettledAtStartup (interrupt after
BeginColdHandover, quarantine, readmit, replay refused, startup settles,
the prior's cleanup stop returns its receipt, a clean B1 successor takes
over through the real handler); TestSettleObsoleteColdHandover.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev 4ff5a0c905355718ffae4f1a62fab8227e4e28ec parent 3ee4884
8 files changed, +633 −7
  • internal/host/claim_binding_assembly_linux_test.go +11 −2
  • internal/host/claim_binding_handover_linux_test.go +364 −0
  • internal/host/claimhandover_transport.go +34 −1
  • internal/host/claimretire_transport.go +12 −1
  • internal/host/rootinventory.go +3 −1
  • internal/hostbox/coldhandover.go +47 −2
  • internal/hostguard/coldhandover.go +70 −0
  • internal/hostguard/coldhandover_settle_unix_test.go +92 −0
diff --git a/internal/host/claim_binding_assembly_linux_test.go b/internal/host/claim_binding_assembly_linux_test.go
index 3c8f5fba7..bcd23882e 100644
--- a/internal/host/claim_binding_assembly_linux_test.go
+++ b/internal/host/claim_binding_assembly_linux_test.go
@@ -71,7 +71,10 @@ type assemblyWorld struct {
root ClaimRootHTTP
authority string
journal string
- now time.Time
+ // retire is root's retirement and cold-handover journal namespace,
+ // /var/lib/carlos-claims/retire on a box (claimRetireJournalDir).
+ retire string
+ now time.Time
// interrupt, while set, fails root's next record write after the
// numbered one (a crash after the intent is durable).
interrupt *int
@@ -110,7 +113,12 @@ func newAssemblyWorld(t *testing.T) *assemblyWorld {
t.Fatal(err)
}
}
- w.locks, w.authority, w.journal = t.TempDir(), t.TempDir(), filepath.Join(t.TempDir(), "journals.db")
+ w.locks, w.authority, w.journal, w.retire = t.TempDir(), t.TempDir(), filepath.Join(t.TempDir(), "journals.db"), t.TempDir()
+ // Root's journal namespace is trusted only when no other principal can
+ // write it (hostbox checkTrustedJournalDir).
+ if err := os.Chmod(w.retire, 0700); err != nil {
+ t.Fatal(err)
+ }
never := -1
w.interrupt = &never
originalAuthority, originalJournal := openClaimRootAuthority, openClaimRootJournal
@@ -161,6 +169,7 @@ func (w *assemblyWorld) start() error {
return DrainClaimAcknowledgement(fence, "controller-1", "start-42", nil), nil
})
w.assembly, w.root = a, a.claimRootHTTP(actor, ClaimStopHTTP{Coordinator: c})
+ w.root.Reconcile.Retirement.JournalDir = w.retire
return nil
}
diff --git a/internal/host/claim_binding_handover_linux_test.go b/internal/host/claim_binding_handover_linux_test.go
new file mode 100644
index 000000000..317358989
--- /dev/null
+++ b/internal/host/claim_binding_handover_linux_test.go
@@ -0,0 +1,364 @@
+//go:build linux
+
+package host
+
+import (
+ "bytes"
+ "encoding/json"
+ "errors"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+
+ "github.com/carlosframework/platform/internal/hostbox"
+ "github.com/carlosframework/platform/internal/hostclaim"
+ "github.com/carlosframework/platform/internal/hostguard"
+ "github.com/carlosframework/platform/internal/registry"
+)
+
+// operationStop moves host's claim into an operation session this box
+// executes (a moving op, with a writer session numbered as an admission at
+// this write would number it) by a TEST-ONLY claim transition, then stops
+// it through root's real stop coordinator: the prior's completed fence
+// receipt, stamped with stamp.
+func (w *assemblyWorld) operationStop(host, stamp string) hostclaim.Observed {
+ w.t.Helper()
+ ctx := w.t.Context()
+ o, err := hostclaim.Update(ctx, w.store, w.claim(host), func(c *hostclaim.Claim) error {
+ h := c.Holder
+ h.Session, h.WriterBox, h.Generation = c.Gen+1, "box-1", "g5"
+ h.Admissions = []hostclaim.AdmissionRecord{{Region: "ie", Session: h.Session, Box: "box-1", Generation: "g5", Mode: "fresh"}}
+ c.Op = hostclaim.Op{Kind: hostclaim.KindMoving, ID: "purge-1", Phase: "stopping", Exec: "box-1"}
+ return nil
+ })
+ if err != nil {
+ w.t.Fatal(err)
+ }
+ if _, err := w.root.Stop.Coordinator.FenceAndStop(ctx, w.priorStop(o, stamp)); err != nil {
+ w.t.Fatal("operation stop of the prior:", err)
+ }
+ return o
+}
+
+// priorStop is the agent's stop request for o's writer session.
+func (w *assemblyWorld) priorStop(o hostclaim.Observed, stamp string) StopRequest {
+ h := o.Claim.Holder
+ return StopRequest{Region: "ie", Host: o.Host, Incarnation: h.Incarnation, InstallationStamp: h.Stamp, WriterSession: h.Session, Box: "box-1", Enrollment: w.roster.row().Enrollment,
+ BootID: rootPeer.BootID, ControllerID: rootPeer.ControllerID, ExpectedClaimETag: o.ETag, ExpectedDirectoryRevision: stamp, RosterRevision: w.roster.read().Roster.Revision,
+ OperationID: "purge-1", Phase: "stopping", ObligationID: "pre-teardown-stop"}
+}
+
+// coldAdmit is the executor's real cold writer admission on host's claim.
+func (w *assemblyWorld) coldAdmit(host, generation string) hostclaim.Observed {
+ w.t.Helper()
+ o := w.claim(host)
+ h := o.Claim.Holder
+ next, err := hostclaim.Update(w.t.Context(), w.store, o, hostclaim.AdmitWriter(hostclaim.Admission{ObservedOpID: o.Claim.Op.ID, ObservedPhase: o.Claim.Op.Phase, ObservedSession: h.Session, ObservedGeneration: h.Generation, Box: "box-1", Mode: "cold", NewGeneration: generation, Region: "ie", PredecessorRegion: "ie"}))
+ if err != nil {
+ w.t.Fatal(err)
+ }
+ return next
+}
+
+// agentGuard is the agent's guard: root's fence view over the socket.
+func (w *assemblyWorld) agentGuard(socket string) hostguard.Guard {
+ return hostguard.Guard{DataDir: w.r.DataDir, LockDir: w.locks, Claims: hostguard.StoreReader{Store: w.store}, FenceView: rootFenceViewClient(rootJournalClient(socket))}
+}
+
+// predecessorReceipt is the prior's completed receipt as the agent's
+// production cold admission hook finds it.
+func (w *assemblyWorld) predecessorReceipt(socket string, prior hostclaim.Observed) hostguard.FenceReceipt {
+ w.t.Helper()
+ h := prior.Claim.Holder
+ receipt, err := w.agentGuard(socket).CompletedColdPredecessor(w.t.Context(), prior.Host, hostguard.Captured{Incarnation: h.Incarnation, Stamp: h.Stamp}, h.Session, prior.Claim.Op.ID, prior.Claim.Op.Phase)
+ if err != nil {
+ w.t.Fatal("prior receipt:", err)
+ }
+ return receipt
+}
+
+func coldRequestFor(prior hostguard.FenceTarget, admitted hostclaim.Observed, enrollment, stamp string) coldHandoverRequest {
+ h := admitted.Claim.Holder
+ return coldHandoverRequest{Prior: prior, Next: hostbox.ColdSuccessor{Host: admitted.Host, Incarnation: h.Incarnation, Stamp: h.Stamp, Session: h.Session, Generation: h.Generation, Box: "box-1", Enrollment: enrollment, DirectoryRevision: stamp, ETag: admitted.ETag, Op: admitted.Claim.Op.ID, Phase: admitted.Claim.Op.Phase}}
+}
+
+// coldJournals is root's cold handover journals by file name and phase.
+func (w *assemblyWorld) coldJournals() map[string]string {
+ w.t.Helper()
+ out := map[string]string{}
+ entries, err := os.ReadDir(filepath.Join(w.retire, "cold"))
+ if errors.Is(err, os.ErrNotExist) {
+ return out
+ }
+ if err != nil {
+ w.t.Fatal(err)
+ }
+ for _, e := range entries {
+ if filepath.Ext(e.Name()) != ".json" {
+ continue
+ }
+ raw, err := os.ReadFile(filepath.Join(w.retire, "cold", e.Name()))
+ if err != nil {
+ w.t.Fatal(err)
+ }
+ var j struct{ Phase string }
+ if err := json.Unmarshal(raw, &j); err != nil {
+ w.t.Fatal(err)
+ }
+ out[e.Name()] = j.Phase
+ }
+ return out
+}
+
+// priorIntact asserts nothing of the prior moved: its route row is still
+// owned by its installation and root's active stamp is still its own.
+func (w *assemblyWorld) priorIntact(what string, prior hostguard.FenceTarget, route registry.Route) {
+ w.t.Helper()
+ row, err := w.reg.Get(prior.Host)
+ if err != nil || row == nil || row.ClaimStamp != prior.Stamp || row.ClaimOwnership != route.ClaimOwnership {
+ w.t.Fatalf("%s: the prior's row moved: %+v %v", what, row, err)
+ }
+ if v := w.view(prior.Host, hostguard.Captured{Incarnation: prior.Incarnation, Stamp: prior.Stamp}); v.Installation.Stamp != prior.Stamp {
+ w.t.Fatalf("%s: root's active stamp moved: %+v", what, v.Installation)
+ }
+}
+
+// installedRoute is host's registry row as the agent's install left it.
+func (w *assemblyWorld) installedRoute(host string) registry.Route {
+ w.t.Helper()
+ row, err := w.reg.Get(host)
+ if err != nil || row == nil {
+ w.t.Fatalf("no route for %s: %v", host, err)
+ }
+ return *row
+}
+
+// N5 (roster binding task 6b): root's operation cold handover admits only a
+// successor stamped with today's binding, checked before any successor
+// state. Through root's handler over the socket: a B0 prior (installed and
+// stopped before a quarantine) hands over to a B1 successor after
+// readmission (parked and started); while quarantined the handover is
+// refused; a successor at the old binding is refused with no journal file,
+// no successor inventory and the prior not parked.
+func TestColdHandoverVerifiesSuccessorAtRoot(t *testing.T) {
+ ctx := t.Context()
+ w := newAssemblyWorld(t)
+ w.mustStart()
+ b0 := w.fresh()
+ rec, route := w.newHost("a")
+ if err := w.agent(b0).install(rec, route); err != nil {
+ t.Fatal(err)
+ }
+ route = w.installedRoute(rec.Host)
+ w.roster.holdChurn()
+ prior := w.operationStop(rec.Host, b0.Binding)
+ socket := w.serve()
+ receipt := w.predecessorReceipt(socket, prior)
+ if receipt.Target.DirectoryRevision != b0.Binding {
+ t.Fatalf("prior receipt target stamp %q", receipt.Target.DirectoryRevision)
+ }
+ admitted := w.coldAdmit(rec.Host, "g6")
+ enrollment := w.roster.row().Enrollment
+
+ // Quarantined: refused before any successor state. Through the socket
+ // ServeHTTP's RequireNewWork answers 403; the handler's own admission
+ // answers 409.
+ w.roster.quarantine("loss_1")
+ quarantined := coldRequestFor(receipt.Target, admitted, enrollment, b0.Binding)
+ if status := postRecoveryHandover(t, socket, quarantined); status != http.StatusForbidden {
+ t.Fatalf("quarantined handover through the socket: HTTP %d", status)
+ }
+ body, _ := json.Marshal(quarantined)
+ direct := httptest.NewRecorder()
+ w.root.serveColdHandover(direct, httptest.NewRequest(http.MethodPost, "http://instance-control/claim/handover", bytes.NewReader(body)).WithContext(ctx), rootPeer)
+ if direct.Code != http.StatusConflict {
+ t.Fatalf("quarantined handover at the handler: HTTP %d", direct.Code)
+ }
+
+ // Readmitted: a successor at the old binding is refused before any state.
+ w.roster.readmit()
+ b1 := w.fresh()
+ if b1.Binding == b0.Binding {
+ t.Fatal("readmission did not move the binding")
+ }
+ for _, stamp := range []string{b0.Binding, strings.Repeat("e", 64)} {
+ if status := postRecoveryHandover(t, socket, coldRequestFor(receipt.Target, admitted, enrollment, stamp)); status != http.StatusConflict {
+ t.Fatalf("successor stamped %q: HTTP %d", stamp, status)
+ }
+ }
+ if j := w.coldJournals(); len(j) != 0 {
+ t.Fatalf("refused handover wrote a journal: %v", j)
+ }
+ if _, revision := w.successorInventory(admitted); revision != 0 {
+ t.Fatal("refused handover wrote a successor inventory")
+ }
+ w.priorIntact("refused successor", receipt.Target, route)
+
+ // B0 prior with its receipt, B1 successor through the agent's production
+ // cold admission hook: parked and started.
+ if err := coldAdmissionHook(w.agentGuard(socket), w.owners.base.Identity, socket)(ctx, prior, admitted); err != nil {
+ t.Fatal("B0 prior to B1 successor:", err)
+ }
+ successor, revision := w.successorInventory(admitted)
+ if revision == 0 || successor.DirectoryRevision != b1.Binding {
+ t.Fatalf("successor inventory: revision %d stamp %q", revision, successor.DirectoryRevision)
+ }
+ if row, err := w.reg.Get(rec.Host); err != nil || row == nil || row.ClaimStamp != admitted.Claim.Holder.Stamp {
+ t.Fatalf("successor not started: %+v %v", row, err)
+ }
+ if v := w.view(rec.Host, hostguard.Captured{Incarnation: successor.Incarnation, Stamp: successor.InstallationStamp}); v.Installation.Stamp != admitted.Claim.Holder.Stamp || v.Barrier != nil {
+ t.Fatalf("root after the handover: %+v barrier %v", v.Installation, v.Barrier)
+ }
+ for name, phase := range w.coldJournals() {
+ if phase != "complete" {
+ t.Fatalf("journal %s: %s", name, phase)
+ }
+ }
+}
+
+// N5 extended (B1) and B3: a cold handover interrupted after
+// BeginColdHandover (its barrier durable, nothing of the prior moved); the
+// box is quarantined and readmitted. The agent's replay of the journaled
+// handover is refused (not resumed). Root restarts: startup comes up, its
+// RecoverPending does not resume the handover and settles it instead (the
+// barrier cleared, the successor stamp retired, the journal marked settled,
+// logged). The prior keeps its historical authority: its cleanup stop
+// returns its receipt, and a clean successor admitted under B1 takes over
+// from it through root's handler, parking the prior. Another restart leaves
+// the settled journal alone.
+func TestColdHandoverObsoleteBarrierSettledAtStartup(t *testing.T) {
+ ctx := t.Context()
+ w := newAssemblyWorld(t)
+ w.mustStart()
+ b0 := w.fresh()
+ rec, route := w.newHost("a")
+ if err := w.agent(b0).install(rec, route); err != nil {
+ t.Fatal(err)
+ }
+ route = w.installedRoute(rec.Host)
+ prior := w.operationStop(rec.Host, b0.Binding)
+ socket := w.serve()
+ receipt := w.predecessorReceipt(socket, prior)
+ admitted := w.coldAdmit(rec.Host, "g6")
+ enrollment := w.roster.row().Enrollment
+ request := coldRequestFor(receipt.Target, admitted, enrollment, b0.Binding)
+ successorStamp := hostguard.Captured{Incarnation: admitted.Claim.Holder.Incarnation, Stamp: admitted.Claim.Holder.Stamp}
+ captured := hostguard.Captured{Incarnation: receipt.Target.Incarnation, Stamp: receipt.Target.Stamp}
+
+ // Root dies right after BeginColdHandover's write: the journal's prepare
+ // write and the barrier write succeed, the prior's retirement write fails.
+ *w.interrupt = 2
+ status := postRecoveryHandover(t, socket, request)
+ *w.interrupt = -1
+ if status != http.StatusConflict {
+ t.Fatalf("interrupted handover: HTTP %d", status)
+ }
+ if v := w.view(rec.Host, captured); v.Barrier == nil || v.Barrier.Stamp != successorStamp.Stamp {
+ t.Fatalf("no durable barrier after the interruption: %+v", v.Barrier)
+ }
+ journals := w.coldJournals()
+ if len(journals) != 1 {
+ t.Fatalf("journals %v", journals)
+ }
+ for _, phase := range journals {
+ if phase != "prepared" {
+ t.Fatalf("interrupted journal phase %q", phase)
+ }
+ }
+ w.priorIntact("interrupted", receipt.Target, route)
+
+ // Binding change, then the agent's replay: refused, not resumed.
+ w.roster.quarantine("loss_1")
+ if status := postRecoveryHandover(t, socket, request); status == http.StatusNoContent {
+ t.Fatal("quarantined replay resumed")
+ }
+ w.roster.readmit()
+ b1 := w.fresh()
+ if status := postRecoveryHandover(t, socket, request); status != http.StatusConflict {
+ t.Fatalf("replay with an obsolete successor: HTTP %d", status)
+ }
+ if v := w.view(rec.Host, captured); v.Barrier == nil {
+ t.Fatal("replay refusal cleared the barrier")
+ }
+ w.priorIntact("refused replay", receipt.Target, route)
+
+ // Startup: up, not resumed, settled.
+ logs := captureLog(t)
+ if err := w.restart(); err != nil {
+ t.Fatal("startup with an obsolete handover barrier:", err)
+ }
+ if err := w.root.RecoverPending(ctx); err != nil {
+ t.Fatal("startup recovery with an obsolete handover barrier:", err)
+ }
+ if !strings.Contains(logs(), "obsolete cold handover: stamped "+b0.Binding+" current "+b1.Binding) {
+ t.Fatalf("no settlement log: %s", logs())
+ }
+ v := w.view(rec.Host, captured)
+ if v.Barrier != nil || v.Pending == nil || *v.Pending != receipt.Target || v.Installation.Stamp != receipt.Target.Stamp {
+ t.Fatalf("after settlement: barrier %v pending %v installation %+v", v.Barrier, v.Pending, v.Installation)
+ }
+ retired := false
+ for _, old := range v.Retired {
+ retired = retired || old == successorStamp
+ }
+ if !retired {
+ t.Fatalf("obsolete successor stamp not retired: %v", v.Retired)
+ }
+ for name, phase := range w.coldJournals() {
+ if phase != "settled" {
+ t.Fatalf("journal %s after settlement: %s", name, phase)
+ }
+ }
+ if _, revision := w.successorInventory(admitted); revision != 0 {
+ t.Fatal("the obsolete successor got an inventory")
+ }
+ w.priorIntact("settled", receipt.Target, route)
+
+ // The prior's historical authority: its cleanup stop completes with its
+ // original receipt.
+ socket = w.serve()
+ cleanup := w.priorStop(prior, b0.Binding)
+ cleanup.Cleanup = true
+ stopped, err := w.root.Stop.Coordinator.FenceAndStop(ctx, cleanup)
+ if err != nil || !bytes.Equal(stopped.Bytes, receipt.Bytes) {
+ t.Fatalf("prior's cleanup stop after settlement: %v (same receipt %v)", err, bytes.Equal(stopped.Bytes, receipt.Bytes))
+ }
+ // The obsolete successor is never reused, at any binding.
+ if status := postRecoveryHandover(t, socket, coldRequestFor(receipt.Target, admitted, enrollment, b1.Binding)); status != http.StatusConflict {
+ t.Fatalf("settled successor reused: HTTP %d", status)
+ }
+
+ // Clean reinstall at B1: a new successor admitted after the settlement,
+ // handed the prior through root's handler.
+ clean := w.coldAdmit(rec.Host, "g7")
+ if status := postRecoveryHandover(t, socket, coldRequestFor(receipt.Target, clean, enrollment, b1.Binding)); status != http.StatusNoContent {
+ t.Fatalf("clean reinstall at B1: HTTP %d", status)
+ }
+ successor, revision := w.successorInventory(clean)
+ if revision == 0 || successor.DirectoryRevision != b1.Binding {
+ t.Fatalf("clean successor inventory: revision %d stamp %q", revision, successor.DirectoryRevision)
+ }
+ if row, err := w.reg.Get(rec.Host); err != nil || row == nil || row.ClaimStamp != clean.Claim.Holder.Stamp {
+ t.Fatalf("clean successor not started: %+v %v", row, err)
+ }
+
+ // Another restart: the settled journal is left alone.
+ if err := w.restart(); err != nil {
+ t.Fatal(err)
+ }
+ if err := w.root.RecoverPending(ctx); err != nil {
+ t.Fatal("restart after the clean reinstall:", err)
+ }
+ settled := 0
+ for _, phase := range w.coldJournals() {
+ if phase == "settled" {
+ settled++
+ }
+ }
+ if settled != 1 {
+ t.Fatalf("journals after the reinstall: %v", w.coldJournals())
+ }
+}
diff --git a/internal/host/claimhandover_transport.go b/internal/host/claimhandover_transport.go
index 1b1c891c1..e856cdb42 100644
--- a/internal/host/claimhandover_transport.go
+++ b/internal/host/claimhandover_transport.go
@@ -51,7 +51,7 @@ func (h ClaimRootHTTP) serveColdHandover(w http.ResponseWriter, r *http.Request,
w.WriteHeader(http.StatusServiceUnavailable)
return
}
- handover := hostbox.ColdHandover{OperationsOnly: true, Guard: h.Stop.Coordinator.Guard, Claims: h.Stop.Coordinator.Evidence, Registry: h.Reconcile.Registry, Inventory: h.Reconcile.Inventory, Launches: h.Launches, Roots: h.Roots, JournalDir: filepath.Join(h.Reconcile.Retirement.JournalDir, "cold"), VerifyReceipt: verifyRetirementReceipt}
+ handover := h.coldHandover()
var err error
if request.Next.Op == "" && request.Next.Phase == "" {
serving := h.servingHandover()
@@ -75,6 +75,39 @@ func (h ClaimRootHTTP) serveColdHandover(w http.ResponseWriter, r *http.Request,
}
w.WriteHeader(http.StatusNoContent)
}
+
+// coldHandover is root's operation cold handover. Its successor admission
+// (roster binding N5, B1) runs before Run takes any step, for a new
+// handover and for a replay alike: the prior keeps its historical authority
+// (its exact receipt, record-to-record checks), the successor must be
+// stamped with the binding the roster gives this box now.
+func (h ClaimRootHTTP) coldHandover() hostbox.ColdHandover {
+ return hostbox.ColdHandover{OperationsOnly: true, Guard: h.Stop.Coordinator.Guard, Claims: h.Stop.Coordinator.Evidence, Registry: h.Reconcile.Registry, Inventory: h.Reconcile.Inventory, Launches: h.Launches, Roots: h.Roots, JournalDir: filepath.Join(h.Reconcile.Retirement.JournalDir, "cold"), VerifyReceipt: verifyRetirementReceipt, Admit: h.admitColdSuccessor}
+}
+
+// admitColdSuccessor is the fresh successor check (roster binding N5): new
+// work must be allowed (a quarantined box is refused) and the successor must
+// name this box, its enrollment and its binding as the fresh identity reads
+// them. It is checked before any successor state exists.
+func (h ClaimRootHTTP) admitColdSuccessor(ctx context.Context, next hostbox.ColdSuccessor) error {
+ if h.InventoryActor == nil {
+ return hostbox.ErrUnsupported
+ }
+ if h.RequireNewWork != nil {
+ if err := h.RequireNewWork(ctx); err != nil {
+ return err
+ }
+ }
+ actor, err := h.InventoryActor(ctx)
+ if err != nil {
+ return err
+ }
+ if actor.Binding == "" || next.Box != actor.Box || next.Enrollment != actor.Enrollment || next.DirectoryRevision != actor.Binding {
+ return hostbox.ErrChanged
+ }
+ return nil
+}
+
func coldAdmissionHook(guard hostguard.Guard, identity hostbox.IdentityProvider, socket string) func(context.Context, hostclaim.Observed, hostclaim.Observed) error {
return coldHandoverWith(identity, socket, func(ctx context.Context, prior hostclaim.Observed) (hostguard.FenceReceipt, error) {
old := prior.Claim.Holder
diff --git a/internal/host/claimretire_transport.go b/internal/host/claimretire_transport.go
index b2af45ff1..fd1f38574 100644
--- a/internal/host/claimretire_transport.go
+++ b/internal/host/claimretire_transport.go
@@ -8,6 +8,7 @@ import (
"fmt"
"github.com/carlosframework/platform/internal/rootstate"
"io"
+ "log"
"net"
"net/http"
"os"
@@ -59,7 +60,17 @@ func (h ClaimRootHTTP) RecoverPending(ctx context.Context) (recoveryErr error) {
}
recoveryErr = errors.Join(recoveryErr, h.Stop.RecoverPending(ctx))
recoveryErr = errors.Join(recoveryErr, h.servingHandover().Recover(ctx))
- cold := hostbox.ColdHandover{OperationsOnly: true, Guard: h.Stop.Coordinator.Guard, Claims: h.Stop.Coordinator.Evidence, Registry: h.Reconcile.Registry, Inventory: h.Reconcile.Inventory, Launches: h.Launches, Roots: h.Roots, JournalDir: filepath.Join(h.Reconcile.Retirement.JournalDir, "cold"), VerifyReceipt: verifyRetirementReceipt}
+ // Startup resumes a journaled cold handover only through the fresh
+ // successor admission (B1). One whose successor was stamped under a
+ // binding other than the startup binding is settled instead (B3).
+ cold := h.coldHandover()
+ cold.Obsolete = func(next hostbox.ColdSuccessor) bool {
+ if !h.obsoleteIntent(next.DirectoryRevision) {
+ return false
+ }
+ log.Printf("instance-control: %s: obsolete cold handover: stamped %s current %s", next.Host, next.DirectoryRevision, h.startupBinding)
+ return true
+ }
recoveryErr = errors.Join(recoveryErr, cold.Recover(ctx))
journals, err := hostbox.SavedRetirementJournals(h.Reconcile.Retirement.JournalDir)
recoveryErr = errors.Join(recoveryErr, err)
diff --git a/internal/host/rootinventory.go b/internal/host/rootinventory.go
index 3b3822020..9966a1d3f 100644
--- a/internal/host/rootinventory.go
+++ b/internal/host/rootinventory.go
@@ -388,7 +388,9 @@ func (h ClaimRootHTTP) obsoleteIntent(stamp string, more ...string) bool {
// own leftovers.
//
// Cold-handover barriers (roster binding B3) are not pending installations
-// and are not settled here; their own fenced settlement is phase C's.
+// and are not settled here: RecoverPending's cold handover recovery settles
+// them (hostbox ColdHandover.Obsolete, hostguard
+// SettleObsoleteColdHandover) with the same startup binding.
func (h ClaimRootHTTP) settleObsoleteIntent(ctx context.Context, host string, raw []byte, kind, stamped string) {
err := h.Stop.Coordinator.Guard.AbandonRootInventory(ctx, host, raw, func(*hostclaim.Claim) bool { return true })
log.Printf("instance-control: %s: obsolete pending %s intent: stamped %s current %s", host, kind, stamped, h.startupBinding)
diff --git a/internal/hostbox/coldhandover.go b/internal/hostbox/coldhandover.go
index 3e56dc404..7aa14163b 100644
--- a/internal/hostbox/coldhandover.go
+++ b/internal/hostbox/coldhandover.go
@@ -37,6 +37,16 @@ type ColdHandover struct {
Roots map[string]string
JournalDir string
VerifyReceipt hostguard.CleanupVerify
+ // Admit, when set, is root's fresh successor admission (roster binding
+ // N5, B1). Run calls it before any other step, for a new handover and
+ // for every replay of a journaled one, startup recovery included, so a
+ // successor is started or resumed only under the binding the roster
+ // gives this box now.
+ Admit func(context.Context, ColdSuccessor) error
+ // Obsolete, when set, reports a journaled successor stamped under a
+ // binding other than root's startup binding (roster binding B3).
+ // Recover never resumes such a handover; it settles it (settleObsolete).
+ Obsolete func(ColdSuccessor) bool
}
type coldJournal struct {
ServingInstallation *hostguard.RootInstallation `json:",omitempty"`
@@ -66,6 +76,11 @@ func (h ColdHandover) Run(ctx context.Context, prior hostguard.FenceTarget, next
if h.Claims == nil || h.Registry == nil || h.Inventory == nil || h.Launches == nil || h.VerifyReceipt == nil || !filepath.IsAbs(h.JournalDir) || len(h.Roots) == 0 || next.Host != prior.Host || next.Incarnation != prior.Incarnation || next.Stamp <= prior.Stamp || next.Session <= prior.Session || next.Stamp != next.Session || next.Box != prior.Box || next.Enrollment != prior.Enrollment || next.ETag == "" || next.Generation == "" {
return ErrUnsupported
}
+ if h.Admit != nil {
+ if err := h.Admit(ctx, next); err != nil {
+ return err
+ }
+ }
check := func(c *hostclaim.Claim) error {
if c == nil || c.Host != next.Host || c.Holder == nil || c.Holder.Family != "instance" || c.Holder.Incarnation != next.Incarnation || c.Holder.Stamp != next.Stamp || c.Holder.Session != next.Session || c.Holder.Generation != next.Generation || c.Holder.WriterBox != next.Box || c.Op.ID != next.Op || c.Op.Phase != next.Phase || c.Op.Exec != next.Box {
return ErrChanged
@@ -626,6 +641,7 @@ func (h ColdHandover) Recover(ctx context.Context) error {
if err != nil {
return err
}
+ var settleErr error
for _, entry := range entries {
if entry.IsDir() || filepath.Ext(entry.Name()) != ".json" {
continue
@@ -649,14 +665,43 @@ func (h ColdHandover) Recover(ctx context.Context) error {
continue
}
}
+ if j.Phase == "settled" {
+ continue
+ }
+ if h.Obsolete != nil && h.Obsolete(j.Successor) {
+ // A failed settlement leaves the handover as it was, for the
+ // next startup; the other journals are still recovered.
+ settleErr = errors.Join(settleErr, h.settleObsolete(ctx, filepath.Join(h.JournalDir, entry.Name()), j))
+ continue
+ }
if err = h.Run(ctx, j.Prior, j.Successor); err != nil {
if h.Guard.Root != nil && h.Guard.AbandonColdHandover(ctx, j.Barrier) == nil {
continue
}
- return err
+ return errors.Join(settleErr, err)
}
}
- return nil
+ return settleErr
+}
+
+// settleObsolete settles a journaled cold handover whose successor binding
+// is obsolete (roster binding B3), whatever phase it reached short of
+// complete. The guard clears the barrier and retires the successor's stamp
+// under the host lock, then the journal is rewritten as "settled": Recover
+// skips it from then on and Run refuses it, so the successor is never
+// resumed or reused. The predecessor is untouched: its receipt and active
+// stamp stay, so its stop and retirement still complete, and a new
+// successor admitted under today's binding can take over from it. If the
+// journal rewrite fails, the next startup settles again; the guard step is
+// idempotent.
+func (h ColdHandover) settleObsolete(ctx context.Context, path string, j coldJournal) error {
+ if j.Phase != "prepared" && j.Phase != "parked" && j.Phase != "complete" {
+ return ErrTypedJournal
+ }
+ return h.Guard.SettleObsoleteColdHandover(ctx, j.Prior, j.Barrier, func() error {
+ j.Phase = "settled"
+ return writeColdJournal(path, j)
+ })
}
func (h ColdHandover) atCheckpoint(point string) {
diff --git a/internal/hostguard/coldhandover.go b/internal/hostguard/coldhandover.go
index b0716d536..6a6335aed 100644
--- a/internal/hostguard/coldhandover.go
+++ b/internal/hostguard/coldhandover.go
@@ -177,3 +177,73 @@ func (g Guard) AbandonColdHandover(ctx context.Context, barrier FenceTarget) err
return d.write(r)
})
}
+
+// SettleObsoleteColdHandover settles an interrupted cold handover from prior
+// whose journaled successor root found obsolete at startup: stamped under a
+// box binding other than the one in root's startup roster read (roster
+// binding B3). It is fenced: it runs under the host lock every handover step
+// takes, and only for a prior whose completed fence receipt this record
+// holds. It needs no claim session advance, unlike AbandonColdHandover: the
+// trigger is the binding change, decided by root from its own roster read.
+//
+// It undoes BeginColdHandover: the barrier is cleared and the deny slot it
+// took goes back to the prior's completed fence, the state the prior's stop
+// left. It records the successor's stamp as retired so it is never
+// installed or reused, and then runs record, which persists the settlement
+// in the handover's own journal. The prior keeps its historical cleanup
+// authority: its stamp stays the active one, its completed fence and
+// receipt stay, so its cleanup stop and retirement still complete. Settling
+// again, with the barrier already cleared, only re-runs record.
+func (g Guard) SettleObsoleteColdHandover(ctx context.Context, prior, barrier FenceTarget, record func() error) error {
+ if g.Root == nil {
+ return ErrUnsupported
+ }
+ if record == nil || prior.validate(prior.Host) != nil || barrier.validate(prior.Host) != nil || prior.Host != barrier.Host || prior.Incarnation != barrier.Incarnation || barrier.Stamp <= prior.Stamp || barrier.Session <= prior.Session || barrier.Stamp != barrier.Session {
+ return ErrInvalidInput
+ }
+ return g.locked(ctx, prior.Host, func(d *recordDir) error {
+ r, err := d.read(prior.Host)
+ if err != nil {
+ return err
+ }
+ successor := Captured{Incarnation: barrier.Incarnation, Stamp: barrier.Stamp}
+ retired := false
+ for _, old := range r.rootRetired {
+ if old == successor {
+ retired = true
+ }
+ }
+ // Already settled: only the journal's record may be missing. Whatever
+ // happened to the host since (a new successor, a new stop) stands.
+ if retired && r.barrier == nil && (r.ActiveFence == nil || *r.ActiveFence != barrier) {
+ return record()
+ }
+ found := false
+ for _, receipt := range r.FenceJournal {
+ if receipt.Target == prior {
+ found = true
+ }
+ }
+ if !found {
+ return ErrNoFenceReceipt
+ }
+ if r.Incarnation != prior.Incarnation || r.ActiveStamp != prior.Stamp {
+ return ErrStampMismatch
+ }
+ if r.barrier != nil && *r.barrier != barrier || r.ActiveFence != nil && *r.ActiveFence != barrier && *r.ActiveFence != prior {
+ return ErrFenceTarget
+ }
+ if !retired {
+ r.rootRetired = append(r.rootRetired, successor)
+ }
+ r.barrier = nil
+ if r.ActiveFence != nil && *r.ActiveFence == barrier {
+ restored := prior
+ r.ActiveFence = &restored
+ }
+ if err := d.write(r); err != nil {
+ return err
+ }
+ return record()
+ })
+}
diff --git a/internal/hostguard/coldhandover_settle_unix_test.go b/internal/hostguard/coldhandover_settle_unix_test.go
new file mode 100644
index 000000000..23f77c5c0
--- /dev/null
+++ b/internal/hostguard/coldhandover_settle_unix_test.go
@@ -0,0 +1,92 @@
+//go:build unix
+
+package hostguard
+
+import (
+ "bytes"
+ "context"
+ "errors"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/hostclaim"
+)
+
+// B3 (roster binding): an obsolete cold handover barrier is settled without
+// a claim session advance (the live successor admission still holds the
+// claim), under the host lock, only for a prior with a completed receipt.
+// Settlement undoes BeginColdHandover (the deny slot back to the prior's
+// completed fence), retires the successor's stamp so it is never installed,
+// runs record after the guard write, and is idempotent.
+func TestSettleObsoleteColdHandover(t *testing.T) {
+ f, prior, captured := fenceFixture(t)
+ f.obs.Claim.Holder.Account, f.obs.Claim.Holder.App = "bab", "console"
+ store := &rootTestStore{dir: t.TempDir()}
+ f.g.Root = NewRootAuthority(store)
+ in := RootInstallation{Host: prior.Host, Incarnation: captured.Incarnation, Stamp: captured.Stamp, Account: "bab", App: "console", Record: "record", Box: prior.Box, Enrollment: prior.Enrollment, Migration: 1}
+ if err := f.g.EstablishRoot(t.Context(), in, allow); err != nil {
+ t.Fatal(err)
+ }
+ f.obs.Claim.Op.Kind = hostclaim.KindMoving
+ if _, err := f.g.BeginFence(t.Context(), prior); err != nil {
+ t.Fatal(err)
+ }
+ if err := f.g.CompleteFence(t.Context(), prior, []byte("receipt"), time.Now(), func(context.Context, FenceTarget, []byte, time.Time) error { return nil }); err != nil {
+ t.Fatal(err)
+ }
+ barrier := prior
+ barrier.FenceID, barrier.Stamp, barrier.Session, barrier.DirectoryRevision = "barrier", 17, 17, "obsolete-binding"
+ f.obs.Claim.Holder.Stamp, f.obs.Claim.Holder.Session = 17, 17
+ if err := f.g.BeginColdHandover(t.Context(), prior, barrier, allow); err != nil {
+ t.Fatal(err)
+ }
+ if err := f.g.AbandonColdHandover(t.Context(), barrier); !errors.Is(err, ErrFenced) {
+ t.Fatal("the session-advance abandonment applies here:", err)
+ }
+ records := 0
+ record := func() error { records++; return nil }
+
+ other := barrier
+ other.FenceID = "other"
+ if err := f.g.SettleObsoleteColdHandover(t.Context(), prior, other, record); !errors.Is(err, ErrFenceTarget) {
+ t.Fatalf("another barrier: %v", err)
+ }
+ unfenced := prior
+ unfenced.FenceID = "never-completed"
+ if err := f.g.SettleObsoleteColdHandover(t.Context(), unfenced, barrier, record); !errors.Is(err, ErrNoFenceReceipt) {
+ t.Fatalf("a prior without a completed receipt: %v", err)
+ }
+ if records != 0 {
+ t.Fatal("a refused settlement recorded")
+ }
+
+ // A failed record leaves the guard settled; the retry only records.
+ failed := errors.New("journal write failed")
+ if err := f.g.SettleObsoleteColdHandover(t.Context(), prior, barrier, func() error { return failed }); !errors.Is(err, failed) {
+ t.Fatal(err)
+ }
+ r, err := f.g.Root.read(prior.Host)
+ if err != nil || r.barrier != nil || r.ActiveFence == nil || *r.ActiveFence != prior || r.ActiveStamp != prior.Stamp || len(r.FenceJournal) != 1 || r.FenceJournal[0].Target != prior {
+ t.Fatalf("after settlement: %+v %v", r, err)
+ }
+ if len(r.rootRetired) != 1 || r.rootRetired[0] != (Captured{Incarnation: barrier.Incarnation, Stamp: barrier.Stamp}) {
+ t.Fatalf("successor stamp not retired: %v", r.rootRetired)
+ }
+ before, _ := store.Read(prior.Host + ".json")
+ if err := f.g.SettleObsoleteColdHandover(t.Context(), prior, barrier, record); err != nil || records != 1 {
+ t.Fatalf("idempotent settlement: %v, records %d", err, records)
+ }
+ if after, _ := store.Read(prior.Host + ".json"); !bytes.Equal(before, after) {
+ t.Fatal("a repeated settlement rewrote the record")
+ }
+
+ // The successor is never installed; the prior stays cleanable.
+ successor := in
+ successor.Stamp = barrier.Stamp
+ if err := f.g.EstablishRoot(t.Context(), successor, allow); !errors.Is(err, ErrRetiredStamp) {
+ t.Fatalf("settled successor installed: %v", err)
+ }
+ if err := f.g.CleanupWith(t.Context(), prior, func(context.Context, FenceReceipt) error { return nil }, func() error { return nil }); err != nil {
+ t.Fatal("prior cleanup after settlement:", err)
+ }
+}