carlos / platform Public

system apply: the rootfs floor checks under a runtime fence and defers on an unreadable registry

Task 15 review round 1:
- The floor raises a registry runtime fence before its check and lifts it
  when the install returns (after the gate or the rollback). SQLite
  triggers refuse every write that would add a row with a runtime while
  it is up, so a mint between the check and the handover is refused
  (ErrRuntimeFenced). Root's marker file lets the next run lift a fence a
  stopped run left.
- A registry that will not open or list defers the apply
  (errSystemDeferred) instead of refusing it; confirmed rows still refuse.
- StartStaged marks the HA containment refusal of a rootfs row as a
  rootfs refusal, so a swap abandons it rather than failing the build.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev 08b5716a91e69e33a729372e3db89ef0dd356740 parent 8f05007
11 files changed, +496 −31
  • internal/activator/genbackend.go +9 −3
  • internal/activator/rootfs_invariants_test.go +3 −0
  • internal/activator/rootfs_staged_test.go +38 −0
  • internal/host/systemapply.go +71 −15
  • internal/host/systemapply_rootfs_test.go +157 −11
  • internal/registry/registry.go +6 −1
  • internal/registry/registry_test.go +12 −0
  • internal/registry/remote.go +1 −1
  • internal/registry/remote_dispatch.go +4 −0
  • internal/registry/runtimefence.go +76 −0
  • internal/registry/runtimefence_test.go +119 −0
diff --git a/internal/activator/genbackend.go b/internal/activator/genbackend.go
index 0819d3098..c210bccc5 100644
--- a/internal/activator/genbackend.go
+++ b/internal/activator/genbackend.go
@@ -237,12 +237,18 @@ func (b *ExecBackend) StartStaged(ctx context.Context, rt registry.Route, g Gen)
if err := refuseUnknownRuntime(rt); err != nil {
return g, nil, err
}
- if err := b.haSpawnGate(rt); err != nil {
- return g, nil, err
- }
if rt.Runtime == registry.RuntimeRootfsV1 {
+ // The HA containment check runs for a rootfs row too, and its
+ // refusal is a rootfs refusal (INV-4): nothing launched, so the
+ // swap abandons the attempt and the build is not counted failed.
+ if err := b.haSpawnGate(rt); err != nil {
+ return g, nil, refuseRootfs(err)
+ }
return b.startStagedRootfs(ctx, rt, g)
}
+ if err := b.haSpawnGate(rt); err != nil {
+ return g, nil, err
+ }
if g.Tier == (cgroup.Limit{}) {
g.Tier = b.GenTier(rt, g.Build)
}
diff --git a/internal/activator/rootfs_invariants_test.go b/internal/activator/rootfs_invariants_test.go
index 43c85ef1a..1be36acba 100644
--- a/internal/activator/rootfs_invariants_test.go
+++ b/internal/activator/rootfs_invariants_test.go
@@ -888,6 +888,9 @@ var rootfsRefusals = []struct {
{"a backend gate's refusal, as the early gate marks it", notAdmitted(refuseRootfs(errors.New("x")))},
{"a served row with no replica (errRootfsReplicaMissing, marked)", refuseRootfs(fmt.Errorf("x: %w", errRootfsReplicaMissing))},
{"no placeholder placer (errNoRootfsDB, marked)", refuseRootfs(fmt.Errorf("x: %w", errNoRootfsDB))},
+ // Task 15 round 1: the HA containment refusal of a rootfs row, as
+ // StartStaged marks it.
+ {"an HA containment refusal of a rootfs row (marked)", refuseRootfs(refusedUncontained(errors.New("x")))},
}
func TestRootfsRefusalsAreNotBuildFailures(t *testing.T) {
diff --git a/internal/activator/rootfs_staged_test.go b/internal/activator/rootfs_staged_test.go
index c809f214f..25c0962a0 100644
--- a/internal/activator/rootfs_staged_test.go
+++ b/internal/activator/rootfs_staged_test.go
@@ -313,6 +313,44 @@ func TestStartStagedRefusesARootfsLiveLink(t *testing.T) {
}
}
+// [Task 15 R1 3, INV-4] An HA-acquired rootfs row whose containment check
+// refuses is a rootfs refusal: the swap abandons the attempt and nothing
+// counts it against the build. A binary row keeps main's lease refusal.
+func TestStartStagedHARefusalOfARootfsRowIsARootfsRefusal(t *testing.T) {
+ t.Parallel()
+ eb, ctl, rt := newStagedRootfsRig(t)
+ id := stagedRootfsIdentity(t, eb, "v2")
+ rt.Backing = registry.BackingUnit // haContained refuses a unit-backed row
+ eb.haWakes.set(rt.Host, haWake{ha: true})
+ _, p, err := eb.StartStaged(context.Background(), rt, Gen{N: 7, Build: "v2", StagedPath: id.StagedPath, Digest: id.Digest})
+ if err == nil || p != nil {
+ t.Fatalf("StartStaged = %v, %v; want a refusal and no process", p, err)
+ }
+ if !errors.Is(err, errRootfsRefused) {
+ t.Fatalf("the HA refusal of a rootfs row is not a rootfs refusal: %v", err)
+ }
+ if v := verdictOf(err); v != gateNoOwnership {
+ t.Errorf("verdictOf = %d, want gateNoOwnership", v)
+ }
+ if s := classifyStep(nil, err); s != stepStale {
+ t.Errorf("classifyStep = %d, want stepStale (abandoned, never a build failure)", s)
+ }
+ if residentFailure(err) {
+ t.Error("residentFailure = true: the refusal counted against the resident")
+ }
+ if calls := ctl.callList(); len(calls) != 0 {
+ t.Fatalf("root was asked %v for a start the HA gate refused", calls)
+ }
+
+ bin := rt
+ bin.Runtime = ""
+ _, _, err = eb.StartStaged(context.Background(), bin, Gen{N: 8, Build: "v2", StagedPath: id.StagedPath, Digest: id.Digest})
+ var leaseRefused *errLeaseRefused
+ if !errors.As(err, &leaseRefused) || errors.Is(err, errRootfsRefused) {
+ t.Fatalf("a binary row's HA refusal = %v, want main's lease refusal, unmarked", err)
+ }
+}
+
func TestStartStagedKeepsTheGenerationsTier(t *testing.T) {
t.Parallel()
eb, ctl, rt := newStagedRootfsRig(t)
diff --git a/internal/host/systemapply.go b/internal/host/systemapply.go
index e2697a2f0..b0b80a4b2 100644
--- a/internal/host/systemapply.go
+++ b/internal/host/systemapply.go
@@ -44,8 +44,9 @@ import (
// grants no new privilege. Root's adopt, stage and restart passes already
// open the same registry, the listing and the Lstats follow no symlink
// and read no journal's contents, and all the guard can do with what it
-// finds is refuse the install. The rootfs floor (rootfsRollbackReasons)
-// opens the same registry, through the same seam, and only lists it.
+// finds is refuse the install. The rootfs floor (fenceRootfsAdmission)
+// opens the same registry, through the same seam: it raises the runtime
+// fence, lists the rows, and lifts the fence when the install is over.
const (
systemEdgeUnit = "carlos-edge"
@@ -247,8 +248,9 @@ type systemApplier struct {
openStore func(ctx context.Context) (release.Store, ed25519.PublicKey, error)
// openRegistry is called only when the candidate predates the instance
// layout, to see whether anything on the box is still nested, or cannot
- // run rootfs instances, to see whether any row has a runtime (and by the
- // moves floor's hold check). Nil means openSystemRegistry over dataDir.
+ // run rootfs instances, to raise the runtime fence, see whether any row
+ // has a runtime and lift the fence again (and by the moves floor's hold
+ // check). Nil means openSystemRegistry over dataDir.
openRegistry func() (*registry.Registry, error)
channel string
optDir string
@@ -376,6 +378,12 @@ func (a *systemApplier) Run(ctx context.Context, recover bool) (retErr error) {
}
deferred = true
}
+ // A runtime fence an earlier run raised and did not lift (it stopped
+ // mid-install) comes down once no install is open: this run holds the
+ // apply lock and recovery has closed the journal.
+ if j, err := readSystemJournal(a.optDir); err == nil && j == nil {
+ a.liftRootfsFence()
+ }
if recover {
return nil
}
@@ -531,10 +539,24 @@ func (a *systemApplier) install(ctx context.Context, req systemRequest, p *relea
// and release.RootfsLifecycleFloor the other half. Unlike the layout
// floor, a version that does not parse is refused too: its unit set
// says nothing about the lifecycle.
+ //
+ // The check runs under the runtime fence (fenceRootfsAdmission), which
+ // stays up until this install returns: after the gate, when the
+ // installed release's agent has taken over, or after the rollback. So
+ // no row with a runtime is admitted between the check and the handover.
+ // Rows confirmed in the way refuse the install; a registry that cannot
+ // answer defers it, and the agent's backoff asks again (INV-6).
if !rootfsLifecycleCandidate(target, newUnits) {
- if reasons := a.rootfsRollbackReasons(); len(reasons) > 0 {
- return a.record(req, fmt.Errorf("%w: "+systemApplyRootfsRefusal, errSystemRefused, target, strings.Join(reasons, ", ")))
+ hosts, err := a.fenceRootfsAdmission()
+ if err != nil {
+ a.liftRootfsFence()
+ return a.record(req, fmt.Errorf("%w: %v", errSystemDeferred, err))
+ }
+ if len(hosts) > 0 {
+ a.liftRootfsFence()
+ return a.record(req, fmt.Errorf("%w: "+systemApplyRootfsRefusal, errSystemRefused, target, strings.Join(hosts, ", ")))
}
+ defer a.liftRootfsFence()
}
// Only the unit set is taken from the return: a rollback picks this
// staging up as it stands, plan.json and all, rather than exec'ing the
@@ -1281,25 +1303,59 @@ func rootfsLifecycleCandidate(version string, units []string) bool {
return ok && v.Compare(release.RootfsLifecycleFloor) >= 0 && slices.Contains(units, rootfsInstanceUnit)
}
-// rootfsRollbackReasons opens the registry through the openRegistry seam
-// and names the rows a release that cannot run rootfs instances would
-// strand. A registry that will not open or list cannot vouch that no row
-// has a runtime, so its error is itself a reason.
-func (a *systemApplier) rootfsRollbackReasons() []string {
+// rootfsFenceMarker is root's own record that it raised the runtime fence
+// (registry.FenceRuntimeAdmission), in root's directory: written before the
+// fence goes up and removed once it is down, so a run that stopped between
+// the two lifts it at the next run's start (liftStaleRootfsFence).
+const rootfsFenceMarker = "rootfs-fence"
+
+// fenceRootfsAdmission raises the runtime fence through the openRegistry
+// seam and then names, through rootfsRowsPresent, every row with a runtime.
+// The fence is committed before the read starts, so a row with a runtime
+// is either in the answer or refused until liftRootfsFence. An error means
+// the registry could not answer; it is never read as an empty box.
+func (a *systemApplier) fenceRootfsAdmission() ([]string, error) {
+ if err := writeJSONDurable(a.file(rootfsFenceMarker), a.ops.now().UTC(), 0o644); err != nil {
+ return nil, err
+ }
open := a.openRegistry
if open == nil {
open = func() (*registry.Registry, error) { return openSystemRegistry(a.dataDir) }
}
reg, err := open()
if err != nil {
- return []string{err.Error()}
+ return nil, err
}
defer reg.Close()
- hosts, err := rootfsRowsPresent(reg)
+ if err := reg.FenceRuntimeAdmission(); err != nil {
+ return nil, err
+ }
+ return rootfsRowsPresent(reg)
+}
+
+// liftRootfsFence lowers the runtime fence this applier raised, then
+// removes its marker. With no marker there is nothing to lift. A lift that
+// fails keeps the marker, and the next run's start tries again.
+func (a *systemApplier) liftRootfsFence() {
+ if _, err := os.Lstat(a.file(rootfsFenceMarker)); err != nil {
+ return
+ }
+ open := a.openRegistry
+ if open == nil {
+ open = func() (*registry.Registry, error) { return openSystemRegistry(a.dataDir) }
+ }
+ reg, err := open()
+ if err == nil {
+ err = reg.LiftRuntimeFence()
+ reg.Close()
+ }
if err != nil {
- return []string{err.Error()}
+ a.ops.logf("system apply: runtime fence: %v (kept; the next run lifts it)", err)
+ return
+ }
+ if err := os.Remove(a.file(rootfsFenceMarker)); err != nil && !errors.Is(err, os.ErrNotExist) {
+ a.ops.logf("system apply: runtime fence marker: %v", err)
}
- return hosts
}
// layoutReversalReasons opens the registry and lists what stands in the
diff --git a/internal/host/systemapply_rootfs_test.go b/internal/host/systemapply_rootfs_test.go
index 0df9de2e5..ada654290 100644
--- a/internal/host/systemapply_rootfs_test.go
+++ b/internal/host/systemapply_rootfs_test.go
@@ -187,23 +187,169 @@ func TestApplyRefusesPlan2WithRootfsUnits(t *testing.T) {
}
}
-// A registry the floor cannot open cannot vouch that no row has a runtime,
-// so its error is the reason and nothing on the box changes.
-func TestApplyRefusesWhenTheRegistryWillNotOpen(t *testing.T) {
- f, _ := applyHappyVersion(t, "v0.29.0")
+// [Task 15 R1 2, INV-6] A registry the floor cannot read cannot vouch that
+// no row has a runtime, and it is not proof that one does either: the
+// apply is deferred, never refused, so the agent's backoff asks again. On a
+// binary-only box the same promotion then applies once the registry
+// answers. Neither a failed open nor a failed list is read as an empty box.
+func TestApplyDefersWhenTheRegistryWillNotAnswer(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ fail func(f *applyFixture) (heal func())
+ }{
+ {"open fails", func(f *applyFixture) func() {
+ open := f.a.openRegistry
+ f.a.openRegistry = func() (*registry.Registry, error) { return nil, errors.New("registry.db: disk I/O error") }
+ return func() { f.a.openRegistry = open }
+ }},
+ {"list fails", func(f *applyFixture) func() {
+ path := filepath.Join(f.a.dataDir, "registry.db")
+ good, err := os.ReadFile(path)
+ if err != nil {
+ f.t.Fatal(err)
+ }
+ open := f.a.openRegistry
+ f.a.openRegistry = func() (*registry.Registry, error) {
+ reg, err := open()
+ if err != nil {
+ return nil, err
+ }
+ // The fence lands, then the file stops being a database
+ // before the list reads it.
+ if err := reg.FenceRuntimeAdmission(); err != nil {
+ f.t.Fatal(err)
+ }
+ for _, side := range []string{path + "-wal", path + "-shm"} {
+ os.Remove(side)
+ }
+ if err := os.WriteFile(path, []byte(strings.Repeat("not a database ", 512)), 0o600); err != nil {
+ f.t.Fatal(err)
+ }
+ return reg, nil
+ }
+ return func() {
+ f.a.openRegistry = open
+ for _, side := range []string{path + "-wal", path + "-shm"} {
+ os.Remove(side)
+ }
+ if err := os.WriteFile(path, good, 0o600); err != nil {
+ f.t.Fatal(err)
+ }
+ }
+ }},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ f, req := applyHappyVersion(t, "v0.29.0")
+ f.postLayout()
+ dd := f.a.dataDir
+ f.seedRoutes(flatRow(dd, "flat.example.com"), nestedRow(dd, "acme.example.com"))
+ heal := tc.fail(f)
+ if err := f.a.Run(context.Background(), false); err != nil {
+ t.Fatal(err)
+ }
+ r := f.result()
+ if r == nil || r.Outcome != systemOutcomeDeferred || !r.matches("stable", "v0.29.0", req.PromotedAt) {
+ t.Fatalf("result = %+v, want deferred", r)
+ }
+ if r.terminal() {
+ t.Fatal("a deferred result is terminal: the agent would never ask again")
+ }
+ f.assertUntouched()
+
+ heal()
+ if err := f.a.Run(context.Background(), false); err != nil {
+ t.Fatal(err)
+ }
+ if r := f.result(); r == nil || r.Outcome != systemOutcomeApplied || !r.matches("stable", "v0.29.0", req.PromotedAt) {
+ t.Fatalf("after the registry answers: result = %+v, want applied", r)
+ }
+ assertFenceDown(t, f)
+ })
+ }
+}
+
+// assertFenceDown checks the runtime fence is down and root's marker gone:
+// the agent mints a row with a runtime again.
+func assertFenceDown(t *testing.T, f *applyFixture) {
+ t.Helper()
+ if _, err := os.Lstat(f.a.file(rootfsFenceMarker)); !errors.Is(err, os.ErrNotExist) {
+ t.Fatalf("the fence marker is still there: %v", err)
+ }
+ reg, err := registry.Open(filepath.Join(f.a.dataDir, "registry.db"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer reg.Close()
+ if err := reg.Upsert(runtimeRow(f.a.dataDir, "after.example.com", registry.RuntimeRootfsV1)); err != nil {
+ t.Fatalf("a mint after the apply: %v", err)
+ }
+}
+
+// [Task 15 R1 1] The agent mints the box's first row with a runtime
+// between the floor's check and the executable's replacement. The fence
+// is up from before the check to after the gate, so the mint is refused
+// and the installed release never meets a row it cannot run. Once the
+// install is over the fence is down and the same mint lands.
+func TestApplyFencesAMintBetweenTheCheckAndTheReplacement(t *testing.T) {
+ f, req := applyHappyVersion(t, "v0.28.25")
f.postLayout()
- f.a.openRegistry = func() (*registry.Registry, error) { return nil, errors.New("registry.db: disk I/O error") }
+ f.withRootfsUnit()
+ dd := f.a.dataDir
+ f.seedRoutes(flatRow(dd, "flat.example.com"))
+ var mintErr error
+ minted := false
+ f.a.beforeSwap = func() {
+ minted = true
+ reg, err := registry.Open(filepath.Join(dd, "registry.db"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer reg.Close()
+ mintErr = reg.Upsert(runtimeRow(dd, "shop.example.com", registry.RuntimeRootfsV1))
+ }
if err := f.a.Run(context.Background(), false); err != nil {
t.Fatal(err)
}
- r := f.result()
- if r == nil || r.Outcome != systemOutcomeRefused {
- t.Fatalf("result = %+v", r)
+ if !minted {
+ t.Fatal("the apply never reached the replacement")
}
- if want := rootfsRefusalFor("v0.29.0", "registry.db: disk I/O error"); r.Reason != want {
- t.Fatalf("reason = %q\nwant %q", r.Reason, want)
+ if !errors.Is(mintErr, registry.ErrRuntimeFenced) {
+ t.Fatalf("the mint between the check and the replacement = %v, want ErrRuntimeFenced", mintErr)
}
- f.assertUntouched()
+ if r := f.result(); r == nil || r.Outcome != systemOutcomeApplied || !r.matches("stable", "v0.28.25", req.PromotedAt) {
+ t.Fatalf("result = %+v, want applied", r)
+ }
+ reg, err := registry.Open(filepath.Join(dd, "registry.db"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if rt, err := reg.Get("shop.example.com"); err != nil || rt != nil {
+ t.Fatalf("the fenced mint left a row: %+v, %v", rt, err)
+ }
+ reg.Close()
+ assertFenceDown(t, f)
+}
+
+// A fence a run raised and never lifted (it stopped mid-install) comes
+// down at the next run's start once no journal is open.
+func TestApplyLiftsAStaleFenceAtTheNextRun(t *testing.T) {
+ f, _ := applyHappyVersion(t, "v0.29.0")
+ f.withRootfsUnit()
+ if err := writeJSONDurable(f.a.file(rootfsFenceMarker), f.now, 0o644); err != nil {
+ t.Fatal(err)
+ }
+ reg, err := registry.Open(filepath.Join(f.a.dataDir, "registry.db"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := reg.FenceRuntimeAdmission(); err != nil {
+ t.Fatal(err)
+ }
+ reg.Close()
+ if err := f.a.Run(context.Background(), false); err != nil {
+ t.Fatal(err)
+ }
+ assertFenceDown(t, f)
}
// rootfsRowsPresent names every row with any non-empty runtime, once and
diff --git a/internal/registry/registry.go b/internal/registry/registry.go
index 6a98d1a38..18e9e2e8f 100644
--- a/internal/registry/registry.go
+++ b/internal/registry/registry.go
@@ -716,6 +716,11 @@ CREATE TABLE IF NOT EXISTS routes (
return err
}
}
+ // The runtime admission fence (runtimefence.go): after the runtime
+ // column, which its triggers read.
+ if err := r.migrateRuntimeFence(); err != nil {
+ return err
+ }
// route_aliases is a derived table (a later reconcile pass owns every
// row, materializing domains.Claim records into it) — a plain CREATE
// TABLE IF NOT EXISTS, no legacy shape to carry forward.
@@ -1436,7 +1441,7 @@ WHERE routes.claim_incarnation=excluded.claim_incarnation AND routes.claim_stamp
AND routes.claim_owner=excluded.claim_owner AND routes.claim_row_id=excluded.claim_row_id`+guard,
routeArgs(normalizeRoute(t))...)
if err != nil {
- return err
+ return runtimeFenced(err)
}
n, err := res.RowsAffected()
if err == nil && n != 1 {
diff --git a/internal/registry/registry_test.go b/internal/registry/registry_test.go
index 049c2ea34..27c1767c5 100644
--- a/internal/registry/registry_test.go
+++ b/internal/registry/registry_test.go
@@ -3101,6 +3101,11 @@ func TestMigrateAddsRuntimeToTheImmediatelyPreviousSchema(t *testing.T) {
if err != nil {
t.Fatal(err)
}
+ // A pre-runtime registry has no runtime fence either: its triggers
+ // read the column, so they go first.
+ if _, err := old.Exec(`DROP TRIGGER runtime_fence_insert; DROP TRIGGER runtime_fence_update; DROP TABLE runtime_fence`); err != nil {
+ t.Fatalf("simulate a pre-runtime registry: %v", err)
+ }
if _, err := old.Exec(`ALTER TABLE routes DROP COLUMN runtime`); err != nil {
t.Fatalf("simulate a pre-runtime registry: %v", err)
}
@@ -3119,6 +3124,13 @@ func TestMigrateAddsRuntimeToTheImmediatelyPreviousSchema(t *testing.T) {
if !routesHasColumn(t, reg, "runtime") {
t.Errorf("no runtime column after Open")
}
+ // The fence's triggers come back with the column they read.
+ if err := reg.FenceRuntimeAdmission(); err != nil {
+ t.Fatal(err)
+ }
+ if err := reg.Upsert(Route{Host: "bab.example.com", Kind: "instance", App: "shop", Runtime: RuntimeRootfsV1}); !errors.Is(err, ErrRuntimeFenced) {
+ t.Errorf("a fenced mint after migration = %v, want ErrRuntimeFenced", err)
+ }
}
func routesHasColumn(t *testing.T, reg *Registry, name string) bool {
diff --git a/internal/registry/remote.go b/internal/registry/remote.go
index 0273300cb..d80ed06cb 100644
--- a/internal/registry/remote.go
+++ b/internal/registry/remote.go
@@ -14,7 +14,7 @@ import (
var errRemoteMethod = errors.New("registry: unsupported remote operation")
-var remoteErrors = []error{os.ErrNotExist, os.ErrPermission, sql.ErrNoRows, ErrClaimOwnership, ErrTimerChanged, ErrTimerKind, ErrPathsChanged, ErrFleetBoxActive, context.Canceled, context.DeadlineExceeded, ErrGoodBuildChanged, ErrRuntimeFixed, ErrRootfsRow, ErrRuntimePlacement}
+var remoteErrors = []error{os.ErrNotExist, os.ErrPermission, sql.ErrNoRows, ErrClaimOwnership, ErrTimerChanged, ErrTimerKind, ErrPathsChanged, ErrFleetBoxActive, context.Canceled, context.DeadlineExceeded, ErrGoodBuildChanged, ErrRuntimeFixed, ErrRootfsRow, ErrRuntimePlacement, ErrRuntimeFenced}
func responseError(out remoteResponse) error {
if !out.Failed {
diff --git a/internal/registry/remote_dispatch.go b/internal/registry/remote_dispatch.go
index 3a07b1c55..53577f531 100644
--- a/internal/registry/remote_dispatch.go
+++ b/internal/registry/remote_dispatch.go
@@ -235,6 +235,10 @@ func (r *Registry) dispatchRemote(ctx context.Context, q remoteRequest, callback
out.Changed, err = r.DeleteIfHoldWithTimers(q.Host, q.Op)
case "HoldRows":
out.Routes, err = r.HoldRows()
+ case "FenceRuntimeAdmission":
+ err = r.FenceRuntimeAdmission()
+ case "LiftRuntimeFence":
+ err = r.LiftRuntimeFence()
case "WithHoldsFrozen":
err = r.WithHoldsFrozen(func(held []Route) error { return callback(remoteResponse{Callback: "holds", Held: held}) })
case "SetAccount":
diff --git a/internal/registry/runtimefence.go b/internal/registry/runtimefence.go
new file mode 100644
index 000000000..f5c956f3a
--- /dev/null
+++ b/internal/registry/runtimefence.go
@@ -0,0 +1,76 @@
+package registry
+
+import (
+ "errors"
+ "strings"
+)
+
+// The runtime admission fence (rootfs apps Plan 3, Task 15 round 1). Root's
+// `carlos system apply` raises it before it checks whether the box has a
+// row with a runtime, and lifts it once the installed release's agent has
+// taken over or the apply has stopped. While it is up, SQLite itself
+// refuses every write that would give the routes table a row with a
+// runtime: an INSERT of one (an upsert over a row that already has that
+// runtime is not one: SQLite runs the INSERT trigger before it finds the
+// conflict), and an UPDATE that sets a row's runtime to another non-empty
+// value. The triggers are the one admission point, so
+// every writer (a reconcile mint, an import swap, a cold handover, an
+// upsert that re-tenants a host) is refused alike, and SQLite's single
+// writer orders each of them against the fence: one that committed before
+// the fence is in the check that follows it, and one that comes after is
+// refused.
+
+// runtimeFencedMessage is the triggers' abort text. It is spliced into
+// their SQL, so it holds no quote.
+const runtimeFencedMessage = "registry: a platform update is checking this box for rows with a runtime; a new one waits for it"
+
+// ErrRuntimeFenced is a write the runtime fence refused. One of
+// remoteErrors.
+var ErrRuntimeFenced = errors.New(runtimeFencedMessage)
+
+func (r *Registry) migrateRuntimeFence() error {
+ _, err := r.sql.Exec(`
+CREATE TABLE IF NOT EXISTS runtime_fence (
+ id INTEGER PRIMARY KEY CHECK (id = 1),
+ since INTEGER NOT NULL
+);
+CREATE TRIGGER IF NOT EXISTS runtime_fence_insert BEFORE INSERT ON routes
+WHEN NEW.runtime != '' AND EXISTS (SELECT 1 FROM runtime_fence)
+ AND NOT EXISTS (SELECT 1 FROM routes WHERE host = NEW.host AND runtime = NEW.runtime)
+BEGIN SELECT RAISE(ABORT, '` + runtimeFencedMessage + `'); END;
+CREATE TRIGGER IF NOT EXISTS runtime_fence_update BEFORE UPDATE OF runtime ON routes
+WHEN NEW.runtime != '' AND NEW.runtime != OLD.runtime AND EXISTS (SELECT 1 FROM runtime_fence)
+BEGIN SELECT RAISE(ABORT, '` + runtimeFencedMessage + `'); END;`)
+ return err
+}
+
+// runtimeFenced maps the triggers' abort to ErrRuntimeFenced.
+func runtimeFenced(err error) error {
+ if err != nil && strings.Contains(err.Error(), runtimeFencedMessage) && !errors.Is(err, ErrRuntimeFenced) {
+ return errors.Join(ErrRuntimeFenced, err)
+ }
+ return err
+}
+
+// FenceRuntimeAdmission raises the fence. It is committed when it returns,
+// so a read that starts after it sees every row with a runtime the box
+// will have until LiftRuntimeFence.
+func (r *Registry) FenceRuntimeAdmission() error {
+ if r.remote != nil {
+ _, err := r.remote.call(nil, remoteRequest{Method: "FenceRuntimeAdmission"}, nil)
+ return err
+ }
+ _, err := r.sql.Exec(`INSERT INTO runtime_fence (id, since) VALUES (1, unixepoch()) ON CONFLICT(id) DO NOTHING`)
+ return err
+}
+
+// LiftRuntimeFence lowers the fence; lifting a fence that is down is not an
+// error.
+func (r *Registry) LiftRuntimeFence() error {
+ if r.remote != nil {
+ _, err := r.remote.call(nil, remoteRequest{Method: "LiftRuntimeFence"}, nil)
+ return err
+ }
+ _, err := r.sql.Exec(`DELETE FROM runtime_fence`)
+ return err
+}
diff --git a/internal/registry/runtimefence_test.go b/internal/registry/runtimefence_test.go
new file mode 100644
index 000000000..d127bb56d
--- /dev/null
+++ b/internal/registry/runtimefence_test.go
@@ -0,0 +1,119 @@
+package registry
+
+import (
+ "errors"
+ "path/filepath"
+ "testing"
+)
+
+func fenceTestRoute(host, runtime string) Route {
+ return Route{Host: host, Kind: "instance", App: "shop", Status: "ready", Runtime: runtime}
+}
+
+// While the fence is up, no write gives the routes table a row with a
+// runtime: not an upsert's insert, not an upsert that re-tenants a binary
+// host onto a runtime, not a raw INSERT (the import swap's and the cold
+// handover's statements). Binary rows and a runtime row's other columns
+// still write. Lifted, the same mint lands.
+func TestRuntimeFenceRefusesEveryRuntimeAdmission(t *testing.T) {
+ t.Parallel()
+ reg, err := Open(filepath.Join(t.TempDir(), "registry.db"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer reg.Close()
+ if err := reg.Upsert(fenceTestRoute("old.example.com", RuntimeRootfsV1)); err != nil {
+ t.Fatal(err)
+ }
+ if err := reg.Upsert(fenceTestRoute("bin.example.com", "")); err != nil {
+ t.Fatal(err)
+ }
+ if err := reg.FenceRuntimeAdmission(); err != nil {
+ t.Fatal(err)
+ }
+ if err := reg.FenceRuntimeAdmission(); err != nil {
+ t.Fatalf("a second raise: %v", err)
+ }
+
+ if err := reg.Upsert(fenceTestRoute("shop.example.com", RuntimeRootfsV1)); !errors.Is(err, ErrRuntimeFenced) {
+ t.Fatalf("a fenced mint = %v, want ErrRuntimeFenced", err)
+ }
+ if err := reg.Upsert(fenceTestRoute("bab.example.com", "rootfs-v9")); !errors.Is(err, ErrRuntimeFenced) {
+ t.Fatalf("a fenced mint of an unknown runtime = %v, want ErrRuntimeFenced", err)
+ }
+ retenant := fenceTestRoute("bin.example.com", RuntimeRootfsV1)
+ retenant.App = "other"
+ if err := reg.Upsert(retenant); !errors.Is(err, ErrRuntimeFenced) {
+ t.Fatalf("a fenced re-tenancy onto a runtime = %v, want ErrRuntimeFenced", err)
+ }
+ if _, err := reg.sql.Exec(`INSERT INTO routes (`+routeCols+`) VALUES (`+placeholders(routeColCount)+`)`,
+ routeArgs(normalizeRoute(fenceTestRoute("raw.example.com", RuntimeRootfsV1)))...); err == nil {
+ t.Fatal("a raw INSERT of a runtime row went past the fence")
+ }
+ // An UPDATE that gives a binary row a runtime, or a row another one.
+ for _, q := range []string{
+ `UPDATE routes SET runtime = 'rootfs-v1' WHERE host = 'bin.example.com'`,
+ `UPDATE routes SET runtime = 'rootfs-v9' WHERE host = 'old.example.com'`,
+ } {
+ if _, err := reg.sql.Exec(q); err == nil {
+ t.Fatalf("%s went past the fence", q)
+ }
+ }
+ if rt, err := reg.Get("old.example.com"); err != nil || rt == nil || rt.Runtime != RuntimeRootfsV1 {
+ t.Fatalf("the runtime row changed runtime under the fence: %+v, %v", rt, err)
+ }
+ for _, h := range []string{"shop.example.com", "bab.example.com", "raw.example.com"} {
+ if rt, err := reg.Get(h); err != nil || rt != nil {
+ t.Fatalf("%s: %+v, %v; want no row", h, rt, err)
+ }
+ }
+ if rt, err := reg.Get("bin.example.com"); err != nil || rt == nil || rt.Runtime != "" || rt.App != "shop" {
+ t.Fatalf("the re-tenanted host changed under the fence: %+v, %v", rt, err)
+ }
+
+ // Binary rows and the runtime row that was already there still write.
+ if err := reg.Upsert(fenceTestRoute("new.example.com", "")); err != nil {
+ t.Fatalf("a binary mint under the fence: %v", err)
+ }
+ same := fenceTestRoute("old.example.com", RuntimeRootfsV1)
+ same.Status = "stopped"
+ if err := reg.Upsert(same); err != nil {
+ t.Fatalf("a runtime row's own upsert under the fence: %v", err)
+ }
+
+ if err := reg.LiftRuntimeFence(); err != nil {
+ t.Fatal(err)
+ }
+ if err := reg.LiftRuntimeFence(); err != nil {
+ t.Fatalf("a second lift: %v", err)
+ }
+ if err := reg.Upsert(fenceTestRoute("shop.example.com", RuntimeRootfsV1)); err != nil {
+ t.Fatalf("the mint after the lift: %v", err)
+ }
+}
+
+// Root raises and lifts the fence through the service-user child, and the
+// refusal keeps its identity across it.
+func TestRemoteRuntimeFence(t *testing.T) {
+ r, path := remoteTestRegistry(t)
+ if err := r.FenceRuntimeAdmission(); err != nil {
+ t.Fatal(err)
+ }
+ if err := r.Upsert(fenceTestRoute("shop.example.com", RuntimeRootfsV1)); !errors.Is(err, ErrRuntimeFenced) {
+ t.Fatalf("a fenced mint through the child = %v, want ErrRuntimeFenced", err)
+ }
+ local, err := Open(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer local.Close()
+ if err := local.Upsert(fenceTestRoute("shop.example.com", RuntimeRootfsV1)); !errors.Is(err, ErrRuntimeFenced) {
+ t.Fatalf("the agent's own fenced mint = %v, want ErrRuntimeFenced", err)
+ }
+ if err := r.LiftRuntimeFence(); err != nil {
+ t.Fatal(err)
+ }
+ if err := local.Upsert(fenceTestRoute("shop.example.com", RuntimeRootfsV1)); err != nil {
+ t.Fatalf("the mint after the lift: %v", err)
+ }
+}