carlos / platform Public

rootfs apps plan 3: Task 2 fix round 1, atomic add refusal, unknown runtimes fixed and inert

carlos add writes through registry.UpsertUnlessRootfs, whose conflict arm
also requires routes.runtime = '', so a rootfs row minted between add's
read and its write is refused (ErrRootfsRow) for the same tenant and for
another. ActivatorOwned and ActivatorLeased are true for any instance row
with a runtime; Resident stays rootfs-v1. carlos route --hibernate refuses
a row with a runtime before any other rail or dry-run plan.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev 1da111ff2124f56fda70e09233a2c5ec49c22dbc parent cda4db6
7 files changed, +285 −17
  • cli.go +34 −2
  • cli_add_rootfs_test.go +114 −0
  • internal/registry/registry.go +42 −6
  • internal/registry/remote.go +1 −1
  • internal/registry/remote_dispatch.go +2 −0
  • internal/registry/runtime.go +14 −6
  • internal/registry/runtime_test.go +78 −2

CI failed — run details

Intent

Attributed to this commit: 21.3 g CO₂e (2,786,291 tokens). This is an attribution, not a measurement — usage counted from this commit's own marker forward to the next one on rootfs-apps-3-lifecycle, never backward from it. A turn that produced more than one commit books all of its tokens to the last one, and a concurrent session on this branch can add to the same figure. Some of it was priced using the shared default rate, because no model-specific factor row exists yet for at least one model involved. The Carbon view has the repo total, which is never derived from this attribution.

diff --git a/cli.go b/cli.go
index a53174ebb..573b48261 100644
--- a/cli.go
+++ b/cli.go
@@ -72,13 +72,35 @@ func reservedSlugs() map[string]bool {
// database path and flags from box defaults. Checked before
// refuseAddNested, so a rootfs row at the nested paths gets this reason.
// A diagnostic (log), not copy.
+//
+// This read is the early answer only. The write is addWrite's
+// UpsertUnlessRootfs, which refuses in the same statement, so a rootfs row
+// minted between this read and the write is refused too.
func refuseAddRootfs(host string, existing *registry.Route) error {
if existing != nil && existing.Runtime != "" {
- return fmt.Errorf("add %s: the row runs a rootfs image (runtime %q); a rootfs row comes from its record, not this verb. nothing was changed", host, existing.Runtime)
+ return addRootfsRefusal(host)
}
return nil
}
+func addRootfsRefusal(host string) error {
+ return fmt.Errorf("add %s: the row runs a rootfs image; a rootfs row comes from its record, not this verb. nothing was changed", host)
+}
+
+// addWrite is runAdd's one write: Upsert, refused atomically over a row
+// with a runtime (registry.UpsertUnlessRootfs).
+func addWrite(r *registry.Registry, host string, route registry.Route) error {
+ err := r.UpsertUnlessRootfs(route)
+ if errors.Is(err, registry.ErrRootfsRow) {
+ return addRootfsRefusal(host)
+ }
+ return err
+}
+
+// addBeforeWrite is a test seam: when set, runAdd calls it between its read
+// of the row and its write. Nil outside tests.
+var addBeforeWrite func(host string)
+
// refuseAddNested stops a re-add of a host whose row is on the nested
// layout. Upsert overwrites the socket, database path and hibernate flag
// with this verb's flat defaults, which would leave the row pointing at
@@ -346,7 +368,10 @@ func runAdd(args []string) {
// annotation, not a loss of state.
route.Replicas = existing.Replicas
}
- if err := r.Upsert(route); err != nil {
+ if addBeforeWrite != nil {
+ addBeforeWrite(host)
+ }
+ if err := addWrite(r, host, route); err != nil {
log.Fatal(err)
}
if existing != nil {
@@ -1527,6 +1552,13 @@ func refuseUnflagNested(rt registry.Route, dataDir string) error {
// always proceeds: stopping a route from hibernating can never contradict a
// declaration.
func runRouteHibernate(r *registry.Registry, rt registry.Route, on, dryRun bool) {
+ // A row with a runtime has its hibernation fixed at mint
+ // (registry.SetHibernate refuses it with ErrRuntimeFixed). Refused first,
+ // before any dry-run plan or other rail, the way refuseAddRootfs refuses
+ // `carlos add`. A diagnostic (log), not copy.
+ if rt.Runtime != "" {
+ log.Fatalf("route: %s: the row runs a rootfs image; its hibernation is fixed when it is minted and comes from its record, not this verb. nothing was changed", rt.Host)
+ }
if platformCanaryOwnedRow(rt) {
// mintedRoute (internal/domains/reconcile.go) never sets Hibernate,
// and Upsert does not preserve it, so a flip here is reverted to
diff --git a/cli_add_rootfs_test.go b/cli_add_rootfs_test.go
index 2f7d9a958..b4eb1d852 100644
--- a/cli_add_rootfs_test.go
+++ b/cli_add_rootfs_test.go
@@ -1,6 +1,7 @@
package main
import (
+ "os"
"os/exec"
"path/filepath"
"strings"
@@ -78,3 +79,116 @@ func TestAddRefusesAnExistingRootfsHost(t *testing.T) {
t.Fatalf("binary row after a re-add = %+v, %v, want it hibernating and binary", got, err)
}
}
+
+// The rootfs refusal is atomic with add's write: a rootfs row minted after
+// runAdd's read and before its write (the addBeforeWrite seam, in a
+// re-executed test binary because the refusal is a log.Fatal) is refused,
+// whether it is the same tenant (whose nested paths a plain Upsert would
+// overwrite) or another (whose runtime Upsert's re-tenancy arm would clear).
+func TestAddRefusesARootfsRowMintedAfterItsRead(t *testing.T) {
+ for _, tenant := range []string{"same", "other"} {
+ t.Run(tenant, func(t *testing.T) {
+ regPath := filepath.Join(t.TempDir(), "registry.db")
+ cmd := exec.Command(os.Args[0], "-test.run=^TestAddRaceHelper$")
+ cmd.Env = carlosTestEnv(t, "CARLOS_ADD_RACE_HELPER="+tenant, "CARLOS_ADD_RACE_REGISTRY="+regPath,
+ "CARLOS_DATA_DIR="+t.TempDir())
+ cmd.Dir = t.TempDir()
+ out, err := cmd.CombinedOutput()
+ if err == nil {
+ t.Fatalf("carlos add over a rootfs row minted after its read: want a refusal, got exit 0\n%s", out)
+ }
+ if !strings.Contains(string(out), "add shop.example.com: the row runs a rootfs image") {
+ t.Fatalf("the add did not fail with the rootfs refusal:\n%s", out)
+ }
+ reg, err := registry.Open(regPath)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer reg.Close()
+ got, err := reg.Get("shop.example.com")
+ if err != nil || got == nil {
+ t.Fatalf("Get = %+v, %v", got, err)
+ }
+ if want := raceMintedRow(tenant); *got != want {
+ t.Fatalf("a refused add changed the minted rootfs row:\n got %+v\n want %+v", *got, want)
+ }
+ })
+ }
+}
+
+// raceMintedRow is the rootfs row TestAddRaceHelper mints between runAdd's
+// read and its write, as Get returns it.
+func raceMintedRow(tenant string) registry.Route {
+ const host = "shop.example.com"
+ rt := registry.Route{Host: host, Kind: "instance", App: "shop", Account: "ops",
+ Socket: provision.NestedSocket(host), DBPath: "/data/instances/i/" + host + ".db",
+ Runtime: registry.RuntimeRootfsV1, Status: "ready", CreatedAt: 1700000000}
+ if tenant == "other" {
+ rt.Account, rt.App = "acctone", "blog"
+ }
+ return rt
+}
+
+// TestAddRaceHelper is the child of TestAddRefusesARootfsRowMintedAfterItsRead.
+func TestAddRaceHelper(t *testing.T) {
+ tenant, regPath := os.Getenv("CARLOS_ADD_RACE_HELPER"), os.Getenv("CARLOS_ADD_RACE_REGISTRY")
+ if tenant == "" {
+ t.Skip("the child of TestAddRefusesARootfsRowMintedAfterItsRead")
+ }
+ addBeforeWrite = func(host string) {
+ reg, err := registry.Open(regPath)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer reg.Close()
+ if err := reg.Upsert(raceMintedRow(tenant)); err != nil {
+ t.Fatal(err)
+ }
+ }
+ runAdd([]string{"-registry", regPath, "-app", "shop", "shop.example.com"})
+}
+
+// carlos route --hibernate over a row with a runtime is refused before any
+// other rail or dry-run plan, and writes nothing.
+func TestRouteHibernateRefusesARootfsRow(t *testing.T) {
+ bin := buildCarlos(t)
+ regPath := filepath.Join(t.TempDir(), "registry.db")
+ scratch := t.TempDir()
+ reg, err := registry.Open(regPath)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer reg.Close()
+ const host = "shop.example.com"
+ if err := reg.Upsert(registry.Route{Host: host, Kind: "instance", App: "shop", Account: "ops",
+ Socket: provision.NestedSocket(host), Runtime: registry.RuntimeRootfsV1, Hibernate: true, Status: "ready"}); err != nil {
+ t.Fatal(err)
+ }
+ before, err := reg.Get(host)
+ if err != nil || before == nil {
+ t.Fatalf("Get before = %+v, %v", before, err)
+ }
+ for _, args := range [][]string{
+ {"route", "-registry", regPath, "-host", host, "-hibernate=false"},
+ {"route", "-registry", regPath, "-host", host, "-hibernate=false", "-dry-run"},
+ {"route", "-registry", regPath, "-host", host, "-hibernate"},
+ } {
+ cmd := exec.Command(bin, args...)
+ cmd.Env = carlosTestEnv(t)
+ cmd.Dir = scratch
+ out, err := cmd.CombinedOutput()
+ if err == nil {
+ t.Fatalf("carlos %v over a rootfs row: want non-zero exit, got 0\n%s", args, out)
+ }
+ if !strings.Contains(string(out), "route: "+host+": the row runs a rootfs image") {
+ t.Errorf("carlos %v: not the rootfs refusal:\n%s", args, out)
+ }
+ if strings.Contains(string(out), "(dry run)") {
+ t.Errorf("carlos %v: printed a dry-run plan before refusing:\n%s", args, out)
+ }
+ after, err := reg.Get(host)
+ if err != nil || after == nil || *after != *before {
+ t.Fatalf("carlos %v changed the rootfs row: %+v, %v", args, after, err)
+ }
+ }
+}
diff --git a/internal/registry/registry.go b/internal/registry/registry.go
index 9c7ed3c96..36dbcec41 100644
--- a/internal/registry/registry.go
+++ b/internal/registry/registry.go
@@ -1155,8 +1155,9 @@ func (r *Registry) Delete(host string) error {
// `excluded.hibernate = 0` arm is that same rule reaching the full-row
// callers. See SetHibernate for the whole of it. Both clear only a binary
// row's rung, keyed on the row's effective runtime (the incoming one on a
-// re-tenanted host, else the stored one): a rootfs row's database is the
-// activator's to replicate awake or asleep.
+// re-tenanted host, else the stored one): the database of a row with any
+// runtime is the activator's to replicate awake or asleep
+// (Route.ActivatorLeased).
//
// `hibernate` is a plain overwrite except on a rootfs row (stored runtime
// not ""), whose hibernation is fixed at mint like its runtime: the stored
@@ -1266,7 +1267,41 @@ func (r *Registry) Upsert(t Route) error {
_, err := r.remote.call(nil, remoteRequest{Method: "Upsert", TValue: t}, nil)
return err
}
+ return r.upsert(t, "")
+}
+
+// UpsertUnlessRootfs is Upsert for `carlos add`, refusing in the same
+// statement when the stored row's runtime is not "": the conflict arm's
+// WHERE also requires routes.runtime = ”, so a rootfs row minted after the
+// caller's own read is never overwritten, and a re-tenanted host never
+// loses its runtime through this door. It returns ErrRootfsRow then. A
+// missing host is inserted as Upsert inserts it. Ordinary Upsert, and its
+// re-tenancy rule, is unchanged.
+func (r *Registry) UpsertUnlessRootfs(t Route) error {
+ if r.remote != nil {
+ _, err := r.remote.call(nil, remoteRequest{Method: "UpsertUnlessRootfs", TValue: t}, nil)
+ return err
+ }
+ err := r.upsert(t, " AND routes.runtime = ''")
+ if !errors.Is(err, ErrClaimOwnership) {
+ return err
+ }
+ // Nothing was written. Tell a rootfs row from a claim mismatch; a row
+ // that changed again since only changes the error, never the write.
+ rt, gerr := r.Get(t.Host)
+ if gerr != nil {
+ return gerr
+ }
+ if rt != nil && rt.Runtime != "" {
+ return ErrRootfsRow
+ }
+ return err
+}
+// upsert is Upsert's statement. guard, when not "", is ANDed onto the
+// conflict arm's WHERE; a conflict it refuses writes nothing and reads as
+// ErrClaimOwnership here.
+func (r *Registry) upsert(t Route, guard string) error {
res, err := r.sql.Exec(`
INSERT INTO routes (`+routeCols+`)
VALUES (`+placeholders(routeColCount)+`)
@@ -1313,7 +1348,7 @@ ON CONFLICT(host) DO UPDATE SET
WHEN excluded.asset_gen = '' THEN routes.asset_gen ELSE excluded.asset_gen END,
incarnation=routes.incarnation, serving_seq=routes.serving_seq
WHERE routes.claim_incarnation=excluded.claim_incarnation AND routes.claim_stamp=excluded.claim_stamp
-AND routes.claim_owner=excluded.claim_owner AND routes.claim_row_id=excluded.claim_row_id`,
+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
@@ -1346,9 +1381,10 @@ func normalizeRoute(t Route) Route {
// interval — so a stored `daily` would be reported by `carlos routes`
// while the database was streamed every second. See SetHibernate. That
// holds for a binary row only. A rung means the activator replicates,
- // and a rootfs row (any non-empty Runtime) keeps its rung awake or
- // asleep: the activator holds a resident's lease and replication
- // (Route.Resident).
+ // and a row with any runtime keeps its rung awake or asleep: the
+ // activator holds its lease and replication (Route.ActivatorLeased),
+ // a resident's and an unknown runtime's alike (fixed and inert: owned,
+ // never started, never claimed by box-wide litestream).
if !t.Hibernate && t.Runtime == "" {
t.Replication = ""
}
diff --git a/internal/registry/remote.go b/internal/registry/remote.go
index 1c6c7b81e..14e64a400 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}
+var remoteErrors = []error{os.ErrNotExist, os.ErrPermission, sql.ErrNoRows, ErrClaimOwnership, ErrTimerChanged, ErrTimerKind, ErrPathsChanged, ErrFleetBoxActive, context.Canceled, context.DeadlineExceeded, ErrGoodBuildChanged, ErrRuntimeFixed, ErrRootfsRow}
func responseError(out remoteResponse) error {
if !out.Failed {
diff --git a/internal/registry/remote_dispatch.go b/internal/registry/remote_dispatch.go
index d4e9530e9..67f3af1b9 100644
--- a/internal/registry/remote_dispatch.go
+++ b/internal/registry/remote_dispatch.go
@@ -208,6 +208,8 @@ func (r *Registry) dispatchRemote(ctx context.Context, q remoteRequest, callback
err = r.Delete(q.Host)
case "Upsert":
err = r.Upsert(q.TValue)
+ case "UpsertUnlessRootfs":
+ err = r.UpsertUnlessRootfs(q.TValue)
case "SetHold":
err = r.SetHold(q.Host, q.Status, q.Op)
case "SetHoldIf":
diff --git a/internal/registry/runtime.go b/internal/registry/runtime.go
index c6bc39bc7..388263332 100644
--- a/internal/registry/runtime.go
+++ b/internal/registry/runtime.go
@@ -12,11 +12,18 @@ var ErrRuntimeFixed = errors.New("registry: a rootfs row's hibernation is fixed
// An unknown runtime is not rootfs: it refuses before any start (Plan 2).
func (t Route) Rootfs() bool { return t.Runtime == RuntimeRootfsV1 }
+// ErrRootfsRow is UpsertUnlessRootfs's refusal: the host's row has a
+// runtime, so it comes from its record and `carlos add` may not rewrite it.
+// One of remoteErrors.
+var ErrRootfsRow = errors.New("registry: the host's row runs a rootfs image, which only its record writes")
+
// ActivatorOwned reports whether the activator starts and stops t's
-// process: a hibernating instance, or any rootfs instance, resident or not.
-// A sidecar is never owned here; its worker path is separate.
+// process: a hibernating instance, or any instance with a runtime, resident
+// or not. An unknown runtime is fixed and inert: the activator owns the row
+// (and refuses to start it, Plan 2), so nothing else ever runs it. A sidecar
+// is never owned here; its worker path is separate.
func (t Route) ActivatorOwned() bool {
- return t.Kind == "instance" && (t.Hibernate || t.Rootfs())
+ return t.Kind == "instance" && (t.Hibernate || t.Runtime != "")
}
// Resident reports whether t is an always-awake rootfs instance: the
@@ -27,8 +34,9 @@ func (t Route) Resident() bool {
// ActivatorLeased reports whether the activator holds t's lease and
// replication: every hibernating row, binary sidecars included (they
-// hibernate: provision's sidecarRouteFor), and every resident. Box-wide
-// litestream covers the rest.
+// hibernate: provision's sidecarRouteFor), and every instance with a
+// runtime, residents and unknown runtimes alike, so box-wide litestream
+// never claims a rootfs row's database. Box-wide litestream covers the rest.
func (t Route) ActivatorLeased() bool {
- return t.Hibernate || t.Resident()
+ return t.Hibernate || (t.Kind == "instance" && t.Runtime != "")
}
diff --git a/internal/registry/runtime_test.go b/internal/registry/runtime_test.go
index 7ee35bfd8..0297f6fe2 100644
--- a/internal/registry/runtime_test.go
+++ b/internal/registry/runtime_test.go
@@ -51,7 +51,11 @@ func TestRoutePredicates(t *testing.T) {
rootfs: true},
{name: "unknown runtime hibernating", rt: Route{Kind: "instance", Runtime: "rootfs-v2", Hibernate: true},
owned: true, leased: true},
- {name: "unknown runtime awake", rt: Route{Kind: "instance", Runtime: "rootfs-v2"}},
+ {name: "unknown runtime awake", rt: Route{Kind: "instance", Runtime: "rootfs-v2"},
+ owned: true, leased: true},
+ {name: "unknown runtime awake sidecar", rt: Route{Kind: "sidecar", Runtime: "rootfs-v2"}},
+ {name: "rootfs awake sidecar", rt: Route{Kind: "sidecar", Runtime: RuntimeRootfsV1},
+ rootfs: true},
}
for i, c := range cases {
c.rt.Host = "p" + string(rune('a'+i)) + ".example.com"
@@ -107,6 +111,17 @@ func TestResidentKeepsItsReplicationRung(t *testing.T) {
got.Runtime, got.Replication, RuntimeRootfsV1, ReplicationDaily)
}
+ // An unknown runtime is fixed and inert, and leased like a resident:
+ // its rung stays too.
+ unknown := Route{Host: "bab.example.com", Kind: "instance", Socket: sockFor("bab.example.com"),
+ Runtime: "rootfs-v2", Replication: ReplicationDaily}
+ if err := reg.Upsert(unknown); err != nil {
+ t.Fatal(err)
+ }
+ if got := mustGet(t, reg, unknown.Host); got.Replication != ReplicationDaily || !got.ActivatorLeased() {
+ t.Fatalf("unknown runtime awake: Replication = %q, leased %v, want %q and leased", got.Replication, got.ActivatorLeased(), ReplicationDaily)
+ }
+
bin := Route{Host: "blog.example.com", Kind: "instance", Socket: sockFor("blog.example.com"), Replication: ReplicationDaily}
if err := reg.Upsert(bin); err != nil {
t.Fatal(err)
@@ -302,7 +317,9 @@ func TestResidentInstancesSelects(t *testing.T) {
nosock.Socket, nosock.Addr = "", "127.0.0.1:9001"
tunnelled := resident("tunnel.example.com")
tunnelled.Tunnel = "bab"
- out := []Route{hib, resident("held.example.com"), failed, gated, sidecar, unit, nosock, tunnelled,
+ unknown := resident("unknown.example.com")
+ unknown.Runtime = "rootfs-v2"
+ out := []Route{hib, resident("held.example.com"), failed, gated, sidecar, unit, nosock, tunnelled, unknown,
{Host: "binary.example.com", Kind: "instance", Socket: sockFor("binary.example.com")}}
for _, rt := range append(append([]Route{}, in...), out...) {
if err := reg.Upsert(rt); err != nil {
@@ -334,3 +351,62 @@ func TestResidentInstancesSelects(t *testing.T) {
t.Fatalf("ResidentInstances = %v, want %v (ordered by host)", hosts, want)
}
}
+
+// carlos add's write refuses a row with a runtime in the same statement, so
+// a rootfs row minted after add's own read is never overwritten: neither
+// its paths (same tenant) nor its runtime (another tenant, where ordinary
+// Upsert's re-tenancy arm would take the incoming "").
+func TestUpsertUnlessRootfs(t *testing.T) {
+ reg := openRuntimeTestRegistry(t)
+ assertUpsertUnlessRootfs(t, reg)
+}
+
+func TestRemoteUpsertUnlessRootfs(t *testing.T) {
+ reg, _ := remoteTestRegistry(t)
+ assertUpsertUnlessRootfs(t, reg)
+}
+
+func assertUpsertUnlessRootfs(t *testing.T, reg *Registry) {
+ t.Helper()
+ add := func(host, account, app string) Route {
+ return Route{Host: host, Kind: "instance", Socket: "/run/carlos/" + host + ".sock",
+ DBPath: "/data/" + host + ".db", Account: account, App: app, Status: "ready"}
+ }
+ // A missing host is inserted, a binary row is rewritten: today's add.
+ if err := reg.UpsertUnlessRootfs(add("blog.example.com", "acctone", "blog")); err != nil {
+ t.Fatalf("insert: %v", err)
+ }
+ next := add("blog.example.com", "acctone", "blog")
+ next.Hibernate = true
+ if err := reg.UpsertUnlessRootfs(next); err != nil {
+ t.Fatalf("rewrite a binary row: %v", err)
+ }
+ if got := mustGet(t, reg, next.Host); !got.Hibernate || got.Socket != next.Socket {
+ t.Fatalf("binary row after UpsertUnlessRootfs = %+v", got)
+ }
+
+ for _, c := range []struct {
+ name, runtime, account, app string
+ }{
+ {"same tenant", RuntimeRootfsV1, "acctone", "shop"},
+ {"another account", RuntimeRootfsV1, "accttwo", "shop"},
+ {"another app", RuntimeRootfsV1, "acctone", "blog"},
+ {"unknown runtime", "rootfs-v2", "acctone", "shop"},
+ } {
+ host := "shop.example.com"
+ if err := reg.Delete(host); err != nil {
+ t.Fatal(err)
+ }
+ if err := reg.Upsert(Route{Host: host, Kind: "instance", Socket: sockFor(host), DBPath: "/data/instances/i/" + host + ".db",
+ Account: "acctone", App: "shop", Runtime: c.runtime, Replication: ReplicationDaily}); err != nil {
+ t.Fatal(err)
+ }
+ before := mustGet(t, reg, host)
+ if err := reg.UpsertUnlessRootfs(add(host, c.account, c.app)); !errors.Is(err, ErrRootfsRow) {
+ t.Errorf("%s: UpsertUnlessRootfs over a row with runtime %q = %v, want ErrRootfsRow", c.name, c.runtime, err)
+ }
+ if after := mustGet(t, reg, host); !reflect.DeepEqual(after, before) {
+ t.Errorf("%s: a refused UpsertUnlessRootfs changed the row:\n before %+v\n after %+v", c.name, before, after)
+ }
+ }
+}