carlos / platform Public

Named-unit delivery: the declaration file is serialised with the config pass (one snapshot under the flock, one root installer verb, one tripwire), and a retained drop-in protects the env file it loads

Paul's ruling (2026-10-28, amadan #114): refuse up front by serialising.

1. SyncUnits reads named-units.json once, under the config-sync flock it
already holds, and that snapshot serves the whole pass. Main had no writer
of the file (searched host, cmd, infra, scripts: proofnamed.go only reads
it), so the smallest root verb is added: carlos system named-units
install <file> (host.RunSystemNamedUnits, root only), which validates the
file with the pass's own decoder (appconfig.ValidateDeclarations), takes
the same flock (host.InstallNamedUnits), and replaces the file atomically:
temp file beside it, 0644, fsync, rename, fsync of the directory. The
per-mutation declGuard re-reads of round 4 are removed; one tripwire
remains, just before the pass's first mutation, comparing the file's
presence and sha256 with the snapshot and abandoning the pass on a
difference. Kept rather than dropped because it costs one read and
catches the one thing the lock cannot, a hand edit, which the docs now
call unsupported.

2. Census R3-E1: a surviving carlos drop-in keeps loading the env file it
names (its EnvironmentFile line, parsed from the trusted read). Such a
host is refused to every row that is not that drop-in's own current
declaration (declaredHostRefusal), and the env reaper keeps it until the
drop-in is reaped; a re-stamp therefore reaps the old unit's drop-in on
one pass and delivers on the next.

3. Round 4 P2: absent and empty are distinct. An absent file declares
nothing; an empty or invalid file delivers and reaps nothing; the
tripwire compares presence as well as bytes.

4. Round 4 item 4: the ordinary writer stays refused for any host the
snapshot's declarations name.

Witnesses through the real SyncUnits:
TestSyncUnitsAbortsWhenTheDeclarationChangesBeforeMutation (the
tripwire), TestSyncUnitsKeepsAFormerHostsEnvFileWhileItsDropInLoadsIt
(declaration moved H1 to H2 for one unit: H1's row rewritten for another
app is refused with the file intact; H1's row deleted with an unrelated
row present keeps the file and the drop-in; undeclared, drop-in then
file go), TestSyncUnitsAbsentThenEmptyDeclarationStopsCleanup,
TestSyncUnitsRefusesAnOrdinaryRowWhoseHostIsDeclared, the empty case in
TestSyncUnitsUnreadableDeclarationsReapNothing; and in internal/host
TestInstallNamedUnitsWaitsForTheConfigSyncLock (the install blocks while
the pass holds the flock, proceeds when released, refuses an invalid
file, lands at 0644 with no temp file). docs/site/cli.md documents the
verb under its own heading; spec §12 states the serialisation rule.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

Summary

Serialises named-units.json with the config pass: one snapshot per pass under the config-sync flock, a root-only carlos system named-units install verb that writes the file atomically under the same lock, one tripwire before the first mutation; a retained carlos drop-in protects the env file it loads from rewrite and reaping.
claude agent, operated by paul@keymail.dev b1238deabc413e2e346396259f71e7a6b77281ca parent 7e2320a
11 files changed, +498 −139
  • docs/site/cli.md +16 −0
  • docs/superpowers/specs/2026-09-07-named-unit-config-delivery-design.md +18 −0
  • internal/appconfig/declarations.go +55 −48
  • internal/appconfig/dropin.go +36 −0
  • internal/appconfig/rootread.go +3 −0
  • internal/appconfig/sync.go +20 −7
  • internal/appconfig/unitsync.go +12 −34
  • internal/appconfig/unitsync_test.go +206 −49
  • internal/host/unitops.go +75 −0
  • internal/host/unitops_test.go +53 −0
  • system.go +4 −1

CI cancelled — superseded by a newer push — run details

diff --git a/docs/site/cli.md b/docs/site/cli.md
index d2990059f..9c3a8d692 100644
--- a/docs/site/cli.md
+++ b/docs/site/cli.md
@@ -2510,6 +2510,22 @@ image before starting `apply`, `recover`, `edge` or `console`. Once armed,
the local floor remains enforced independently of `CARLOS_HOST_CLAIM`.
The member command remains `carlos ops host resolve`.
+#### carlos system named-units
+
+`carlos system named-units install <file>` installs the box's declaration
+of named units, `/etc/carlos/named-units.json`, from `<file>`. It runs as
+root only. It checks the file first (schema 1, one JSON document, one line
+per host and per unit, as shown under `carlos route`), then replaces the
+live file in one step while holding the lock the config pass holds, so a
+pass never sees half a change. Provisioning writes the file before the
+agent starts, or runs this command; editing the file by hand while carlos
+runs is not supported, and a pass that sees the file change under it does
+nothing and says so.
+
+```sh
+carlos system named-units install /root/named-units.json
+```
+
#### carlos system db-worker
`carlos system db-worker` runs on platform boxes only. systemd starts it for each forwarded database query. You never run it yourself.
diff --git a/docs/superpowers/specs/2026-09-07-named-unit-config-delivery-design.md b/docs/superpowers/specs/2026-09-07-named-unit-config-delivery-design.md
index e674c4842..00fdb6be8 100644
--- a/docs/superpowers/specs/2026-09-07-named-unit-config-delivery-design.md
+++ b/docs/superpowers/specs/2026-09-07-named-unit-config-delivery-design.md
@@ -930,6 +930,24 @@ other-writable, no symlink), so a writable parent, a symlinked ancestor or
a writable drop-in directory blocks the unit; and the declaration must be
one JSON document with nothing after it, as the release path reads it.
+**Serialisation (Paul's ruling, 2026-10-28, amadan #114; no fifth review
+round).** `SyncUnits` reads `named-units.json` once, under the config-sync
+flock it already holds (`lockConfigSync`), and that snapshot serves the
+whole pass. Every change carlos makes to the file takes the same flock,
+validates with the same decoder (`appconfig.ValidateDeclarations`) and
+writes atomically (`host.InstallNamedUnits`: temp file beside it, 0644,
+fsync, rename, fsync of the directory), through the one root verb
+`carlos system named-units install <file>`; main had no writer of the
+file. Provisioning writes the file before the agent starts, or runs the
+verb; a hand edit while carlos runs is unsupported. The per-mutation
+re-reads of round 4 are gone; one tripwire remains, just before the
+pass's first mutation, comparing the file's presence and digest with the
+snapshot (an absent file declares nothing; an empty or invalid one
+delivers and reaps nothing), and a difference abandons the pass. Cleanup
+keeps the env file of any host a surviving carlos drop-in still names
+(the drop-in's `EnvironmentFile` line, read through the trusted reader),
+and no row may rewrite such a file until that drop-in is reaped.
+
Tests (console config design §11, first three bullets) run through the
real `SyncUnits` with the faked `UnitOps`:
`TestSyncUnitsRefusesToResetAnUnmanagedEnvFileAway`,
diff --git a/internal/appconfig/declarations.go b/internal/appconfig/declarations.go
index 5719d1b17..540cf3cfc 100644
--- a/internal/appconfig/declarations.go
+++ b/internal/appconfig/declarations.go
@@ -55,9 +55,10 @@ type declarations struct {
path string
byUnit map[string]Declaration
byHost map[string]Declaration
- // digest is sha256 of the bytes the file held when it was read; the
- // guard re-reads and compares before every mutation (declGuard).
- digest [32]byte
+ // present and digest are the snapshot the tripwire compares against:
+ // whether the file existed, and sha256 of its bytes.
+ present bool
+ digest [32]byte
}
// readDeclarationBytes is the one read of the file: absent is no bytes.
@@ -75,17 +76,44 @@ func readDeclarationBytes(ops *UnitOps) ([]byte, error) {
return raw, nil
}
-// loadDeclarations reads the file through rootRead (invariant C). An
-// absent file declares nothing. An unreadable or invalid file is an error:
-// the caller delivers nothing and reaps nothing, since what is declared is
-// then unknown.
+// loadDeclarations reads the file ONCE per pass, under the config-sync
+// flock SyncUnits holds (Paul's ruling of 2026-10-28, serialisation: every
+// carlos writer of the file takes the same lock, InstallNamedUnits in
+// internal/host), and the snapshot serves the whole pass. An absent file
+// declares nothing; an empty or invalid file is an error, and the pass
+// then delivers nothing and reaps nothing (round 4 P2: absent and empty
+// are distinct states).
func loadDeclarations(ops *UnitOps) (*declarations, error) {
- d := &declarations{path: ops.NamedUnitsPath, byUnit: map[string]Declaration{}, byHost: map[string]Declaration{}}
raw, err := readDeclarationBytes(ops)
if err != nil {
return nil, err
}
+ d, err := parseDeclarations(ops.NamedUnitsPath, raw)
+ if err != nil {
+ return nil, err
+ }
+ d.present = raw != nil
d.digest = sha256.Sum256(raw)
+ return d, nil
+}
+
+// ValidateDeclarations is the decoder the installer runs on a file before
+// it replaces the live one: the same grammar loadDeclarations reads, so a
+// file the installer accepts is one the pass accepts.
+func ValidateDeclarations(raw []byte) error {
+ if raw == nil {
+ raw = []byte{}
+ }
+ _, err := parseDeclarations("declarations", raw)
+ return err
+}
+
+// parseDeclarations is the one decoder: schema 1, one JSON document with
+// nothing after it (as the release path reads the file), valid names,
+// one entry per host and one per unit. raw nil is an absent file and
+// declares nothing; raw empty is an invalid file.
+func parseDeclarations(path string, raw []byte) (*declarations, error) {
+ d := &declarations{path: path, byUnit: map[string]Declaration{}, byHost: map[string]Declaration{}}
if raw == nil {
return d, nil
}
@@ -95,33 +123,30 @@ func loadDeclarations(ops *UnitOps) (*declarations, error) {
}
dec := json.NewDecoder(bytes.NewReader(raw))
if err := dec.Decode(&file); err != nil {
- return nil, fmt.Errorf("declarations: %s: %w", ops.NamedUnitsPath, err)
+ return nil, fmt.Errorf("declarations: %s: %w", path, err)
}
- // One document and nothing after it, as the release path reads the
- // file (round 3 P2-6): trailing bytes make the file invalid, and an
- // invalid file authorises nothing, reaping included.
if dec.Decode(new(any)) != io.EOF {
- return nil, fmt.Errorf("declarations: %s: bytes after the JSON document", ops.NamedUnitsPath)
+ return nil, fmt.Errorf("declarations: %s: bytes after the JSON document", path)
}
if file.Schema != 1 {
- return nil, fmt.Errorf("declarations: %s: schema %d, want 1", ops.NamedUnitsPath, file.Schema)
+ return nil, fmt.Errorf("declarations: %s: schema %d, want 1", path, file.Schema)
}
byHost := map[string]bool{}
for _, u := range file.Units {
switch {
case !controlname.ValidHostShape(u.Host):
- return nil, fmt.Errorf("declarations: %s: %q is not a hostname", ops.NamedUnitsPath, u.Host)
+ return nil, fmt.Errorf("declarations: %s: %q is not a hostname", path, u.Host)
case !release.ValidApp(u.App):
- return nil, fmt.Errorf("declarations: %s: %q is not an app name", ops.NamedUnitsPath, u.App)
+ return nil, fmt.Errorf("declarations: %s: %q is not an app name", path, u.App)
case u.Account != "" && !release.ValidAccount(u.Account):
- return nil, fmt.Errorf("declarations: %s: %q is not an account", ops.NamedUnitsPath, u.Account)
+ return nil, fmt.Errorf("declarations: %s: %q is not an account", path, u.Account)
case !registry.ValidUnitName(u.Unit):
- return nil, fmt.Errorf("declarations: %s: %q is not a unit name", ops.NamedUnitsPath, u.Unit)
+ return nil, fmt.Errorf("declarations: %s: %q is not a unit name", path, u.Unit)
case byHost[u.Host]:
- return nil, fmt.Errorf("declarations: %s: %s is declared twice", ops.NamedUnitsPath, u.Host)
+ return nil, fmt.Errorf("declarations: %s: %s is declared twice", path, u.Host)
}
if _, dup := d.byUnit[u.Unit]; dup {
- return nil, fmt.Errorf("declarations: %s: %s is declared for two hosts", ops.NamedUnitsPath, u.Unit)
+ return nil, fmt.Errorf("declarations: %s: %s is declared for two hosts", path, u.Unit)
}
byHost[u.Host] = true
d.byUnit[u.Unit] = u
@@ -130,37 +155,19 @@ func loadDeclarations(ops *UnitOps) (*declarations, error) {
return d, nil
}
-// declGuard is round 3 P1-3's refusal: authorisation must stay valid
-// through the effect it permits. Before each mutation (env-file write,
-// drop-in write or removal, daemon-reload, restart, env reap) the pass
-// re-reads the declaration file through the trusted reader and compares a
-// digest of its bytes with what planning read. A difference, or a read
-// that fails, aborts every remaining mutation of the pass; the next pass
-// plans afresh.
-type declGuard struct {
- digest [32]byte
- stale bool
- reason string
- said bool
-}
-
-// check reports nil when the file still holds the bytes planning read.
-// Once stale, every later check is stale without another read.
-func (g *declGuard) check(ops *UnitOps) error {
- if g == nil {
- return fmt.Errorf("no declaration guard on this pass")
- }
- if g.stale {
- return fmt.Errorf("%s", g.reason)
- }
+// tripwire is the one check the lock leaves worth keeping: just before the
+// pass commits its first mutation, the file is read again and its presence
+// and digest compared with the snapshot. Under the flock no carlos writer
+// can have changed it, so a difference means a hand edit while carlos
+// runs, which is unsupported; the pass reports it and abandons every
+// mutation rather than act on a snapshot that is no longer the file.
+func (d *declarations) tripwire(ops *UnitOps) error {
raw, err := readDeclarationBytes(ops)
if err != nil {
- g.stale, g.reason = true, fmt.Sprintf("the declaration file could not be re-read (%v); remaining mutations of this pass abandoned", err)
- return fmt.Errorf("%s", g.reason)
+ return fmt.Errorf("the declaration file could not be re-read (%v); this pass mutates nothing", err)
}
- if sha256.Sum256(raw) != g.digest {
- g.stale, g.reason = true, "the declaration file changed during this pass; remaining mutations of this pass abandoned, the next pass plans afresh"
- return fmt.Errorf("%s", g.reason)
+ if (raw != nil) != d.present || sha256.Sum256(raw) != d.digest {
+ return fmt.Errorf("the declaration file changed during this pass (a hand edit while carlos runs is unsupported; use carlos system named-units install); this pass mutates nothing, the next plans afresh")
}
return nil
}
diff --git a/internal/appconfig/dropin.go b/internal/appconfig/dropin.go
index 27bf48034..793f20bb8 100644
--- a/internal/appconfig/dropin.go
+++ b/internal/appconfig/dropin.go
@@ -183,6 +183,42 @@ func listMarkedDropIns(ops *UnitOps) (units, skipped []string, unreadable map[st
return units, skipped, unreadable
}
+// dropInEnvHost is the host whose env file a carlos drop-in loads: the
+// last EnvironmentFile line names <envDir>/<host>.env (renderDropIn), and a
+// unit keeps loading that file until the drop-in is reaped, whatever the
+// declaration or the registry say meanwhile (census R3-E1). "" for a
+// drop-in that names no such file.
+func dropInEnvHost(cur []byte, envDir string) string {
+ host := ""
+ for _, line := range strings.Split(string(cur), "\n") {
+ p, ok := strings.CutPrefix(line, "EnvironmentFile=-")
+ if !ok || filepath.Dir(p) != envDir || !strings.HasSuffix(p, ".env") {
+ continue
+ }
+ host = strings.TrimSuffix(filepath.Base(p), ".env")
+ }
+ return host
+}
+
+// referencedEnvHosts: for every marker-bearing drop-in that still exists,
+// the host whose env file it loads, keyed to its unit. Read through the
+// trusted reader; a drop-in that cannot be read references nothing here,
+// and its unit is not reaped either (listMarkedDropIns).
+func referencedEnvHosts(ops *UnitOps, envDir string) map[string]string {
+ out := map[string]string{}
+ units, _, _ := listMarkedDropIns(ops)
+ for _, unit := range units {
+ cur, _, _, err := readDropIn(ops, unit)
+ if err != nil {
+ continue
+ }
+ if host := dropInEnvHost(cur, envDir); host != "" {
+ out[host] = unit
+ }
+ }
+ return out
+}
+
// listPending: units whose plain <unit>.d holds a pending marker.
func listPending(root string) []string {
dirs, _ := unitDirs(root)
diff --git a/internal/appconfig/rootread.go b/internal/appconfig/rootread.go
index 2ab145af5..c47584a62 100644
--- a/internal/appconfig/rootread.go
+++ b/internal/appconfig/rootread.go
@@ -66,6 +66,9 @@ func rootRead(ops *UnitOps, path string) ([]byte, error) {
if len(raw) > rootReadLimit {
return nil, fmt.Errorf("%s is larger than %d bytes", path, rootReadLimit)
}
+ if raw == nil {
+ raw = []byte{} // an empty file is a file, never "absent"
+ }
return raw, nil
}
diff --git a/internal/appconfig/sync.go b/internal/appconfig/sync.go
index c9fec22b2..95fe2e997 100644
--- a/internal/appconfig/sync.go
+++ b/internal/appconfig/sync.go
@@ -222,6 +222,17 @@ func SyncWithCallbacks(ctx context.Context, reg *registry.Registry, s release.St
}
resolved[k] = resolution{m: m, defaultMissing: !def.found}
}
+ // The one tripwire (Paul's ruling, serialisation): every carlos writer
+ // of the declaration file takes the config-sync flock this pass holds,
+ // so the snapshot cannot have changed under it; before the first
+ // mutation the file is read once more all the same, and a hand edit
+ // (unsupported) abandons the pass.
+ if ops != nil && plan.decls != nil {
+ if err := plan.decls.tripwire(ops); err != nil {
+ fmt.Printf(" config sync: %v\n", err)
+ return nil
+ }
+ }
// The instance layer (senders design §6.2), resolved per route AFTER the
// group base above. The group is still (Account, App, Environment) and
// the default bundle is still read once per app: only the third layer is
@@ -391,19 +402,20 @@ func SyncWithCallbacks(ctx context.Context, reg *registry.Registry, s release.St
// Invariant A, env files (round 3 P1-2, census E2): a declared
// host's env file is kept whatever the registry says, and with the
// declarations unknown or changed nothing is reaped.
+ // Kept: every declared host, and every host whose env file a
+ // drop-in surviving reapDropIns still loads (census R3-E1).
var keep map[string]bool
if ops != nil {
if plan.decls == nil {
return nil
}
- if err := plan.guard.check(ops); err != nil {
- fmt.Printf(" env files: not reaped: %v\n", err)
- return nil
- }
keep = map[string]bool{}
for host := range plan.decls.byHost {
keep[host] = true
}
+ for host := range referencedEnvHosts(ops, envDir) {
+ keep[host] = true
+ }
}
reap(routes, envDir, keep)
} else {
@@ -449,9 +461,10 @@ func reapSelectedEnvTemps(ctx context.Context, envDir string, selected map[strin
// environment bundle must never delete a live route's env file — that route
// keeps its last-good file and Sync logs the unresolved binding instead.
//
-// declared are the hosts the named-units declaration names (invariant A):
-// their files are kept whether or not a row names them, since a declared
-// unit's drop-in loads the file on its next start.
+// declared are the hosts the named-units declaration names, and the hosts
+// whose env file a surviving carlos drop-in still loads (invariant A):
+// their files are kept whether or not a row names them, since a unit's
+// drop-in loads the file on its next start.
func reap(routes []registry.Route, envDir string, declared map[string]bool) {
ents, err := os.ReadDir(envDir)
if err != nil {
diff --git a/internal/appconfig/unitsync.go b/internal/appconfig/unitsync.go
index 8dcc70f10..7d0ba0b23 100644
--- a/internal/appconfig/unitsync.go
+++ b/internal/appconfig/unitsync.go
@@ -80,9 +80,10 @@ type stampedPlan struct {
// idle are the declared units no delivering route names this pass: their
// drop-ins stay, and the pass says so.
idle []string
- // guard re-reads the declaration file before each mutation (round 3
- // P1-3); nil when the file could not be read, which mutates nothing.
- guard *declGuard
+ // referenced maps a host to the unit whose surviving carlos drop-in
+ // still loads that host's env file (census R3-E1): such a file is
+ // neither rewritten by another row nor reaped while the drop-in stands.
+ referenced map[string]string
}
// declaredHostRefusal is invariant A at the dispatch (round 3 P1-1, census
@@ -96,6 +97,11 @@ func (p stampedPlan) declaredHostRefusal(rt registry.Route) string {
return ""
}
d, declared := p.decls.byHost[rt.Host]
+ if loader, loaded := p.referenced[rt.Host]; loaded && (!declared || d.Unit != loader) {
+ // A former binding's drop-in still loads this file (census
+ // R3-E1): no row may rewrite it until that drop-in is reaped.
+ return fmt.Sprintf("%s's env file is still loaded by %s's drop-in, which no current declaration retires; nothing may rewrite it until that drop-in is reaped; env file left untouched", rt.Host, loader)
+ }
if !declared {
return ""
}
@@ -122,7 +128,7 @@ func planStamped(routes []registry.Route, envDir string, ops *UnitOps) stampedPl
decls, declErr := loadDeclarations(ops)
p.decls = decls
if decls != nil {
- p.guard = &declGuard{digest: decls.digest}
+ p.referenced = referencedEnvHosts(ops, envDir)
}
byUnit := map[string][]string{}
rowOf := map[string]registry.Route{}
@@ -305,30 +311,14 @@ func prepareStamped(rt registry.Route, unit string, m *Manifest, defaultMissing
w.ok = true
return w
}
- // Before each mutation: the declaration file still holds what planning
- // read (round 3 P1-3).
- if err := plan.guard.check(ops); err != nil {
- fmt.Printf(" %s: delivery blocked: %v\n", rt.Host, err)
- return w
- }
if err := writePending(ops.DropInRoot, unit); err != nil {
fmt.Printf(" %s: record pending restart for %s: %v (nothing written)\n", rt.Host, unit, err)
return w
}
- if envChanged {
- if err := plan.guard.check(ops); err != nil {
- fmt.Printf(" %s: delivery blocked: %v\n", rt.Host, err)
- return w
- }
- if !commitHost(rt.Host, path, rendered) {
- return w
- }
+ if envChanged && !commitHost(rt.Host, path, rendered) {
+ return w
}
if dropChanged {
- if err := plan.guard.check(ops); err != nil {
- fmt.Printf(" %s: delivery blocked: %v\n", rt.Host, err)
- return w
- }
if err := writeDropIn(ops.DropInRoot, unit, wantDrop); err != nil {
fmt.Printf(" %s: write drop-in for %s: %v\n", rt.Host, unit, err)
return w
@@ -375,10 +365,6 @@ func reapDropIns(plan stampedPlan, ops *UnitOps) {
if plan.decls.declares(unit) {
continue
}
- if err := plan.guard.check(ops); err != nil {
- fmt.Printf(" %s: not reaped: %v\n", unit, err)
- return
- }
if err := writePending(ops.DropInRoot, unit); err != nil {
fmt.Printf(" %s: record reload owed: %v (drop-in kept)\n", unit, err)
continue
@@ -413,10 +399,6 @@ func applyStamped(envDir string, ops *UnitOps, plan stampedPlan, work map[string
}
pending := listPending(ops.DropInRoot)
if len(pending) > 0 {
- if err := plan.guard.check(ops); err != nil {
- fmt.Printf(" daemon-reload not run: %v\n", err)
- return
- }
if err := ops.Reload(); err != nil {
for _, unit := range pending {
fmt.Printf(" %s: daemon-reload failed (%v); reload and restart still owed\n", unit, err)
@@ -474,10 +456,6 @@ func applyStamped(envDir string, ops *UnitOps, plan stampedPlan, work map[string
fmt.Printf(" %s: restart of %s refused: not declared: %v\n", w.host, unit, err)
continue
}
- if err := plan.guard.check(ops); err != nil {
- fmt.Printf(" %s: restart of %s not run: %v\n", w.host, unit, err)
- continue
- }
if err := ops.Restart(unit); err != nil {
fmt.Printf(" %s: config updated but restart of %s failed: %v; restart still owed\n", w.host, unit, err)
continue
diff --git a/internal/appconfig/unitsync_test.go b/internal/appconfig/unitsync_test.go
index d573b4c46..31852d045 100644
--- a/internal/appconfig/unitsync_test.go
+++ b/internal/appconfig/unitsync_test.go
@@ -633,14 +633,20 @@ func TestSyncUnitsReapsOnlyWhenTheDeclarationGoes(t *testing.T) {
// A declaration file that cannot be read is no authority to remove
// anything.
func TestSyncUnitsUnreadableDeclarationsReapNothing(t *testing.T) {
- ctx, s, reg, envDir, priv := unitKit(t)
- f := newFakeUnits(t)
- ensureDropInDir(f.ops(), "relay.service")
- writeDropIn(f.root, "relay.service", renderDropIn(envDir, f.base, "relay.service", "relay.example.com"))
- f.declRaw(t, "not json")
- out := syncOnce(t, ctx, reg, s, priv, envDir, f)
- if _, exists, _, _ := readDropIn(f.ops(), "relay.service"); !exists || !strings.Contains(out, "nothing reaped") {
- t.Fatalf("exists=%v out=%q", exists, out)
+ // An invalid file and an EMPTY file alike (round 4 P2: empty is a
+ // file, not absence; absence alone declares nothing).
+ for name, body := range map[string]string{"not json": "not json", "empty": ""} {
+ t.Run(name, func(t *testing.T) {
+ ctx, s, reg, envDir, priv := unitKit(t)
+ f := newFakeUnits(t)
+ ensureDropInDir(f.ops(), "relay.service")
+ writeDropIn(f.root, "relay.service", renderDropIn(envDir, f.base, "relay.service", "relay.example.com"))
+ f.declRaw(t, body)
+ out := syncOnce(t, ctx, reg, s, priv, envDir, f)
+ if _, exists, _, _ := readDropIn(f.ops(), "relay.service"); !exists || !strings.Contains(out, "nothing reaped") {
+ t.Fatalf("exists=%v out=%q", exists, out)
+ }
+ })
}
}
@@ -711,11 +717,20 @@ func TestSyncUnitsReStampMovesTheDropIn(t *testing.T) {
t.Fatalf("a refused re-stamp reloaded: reloads=%d pending=%v", f.reloads, hasPending(f.root, "a.service"))
}
f.declare(t, Declaration{Host: "relay.example.com", Account: "bab", App: "relay", Unit: "b.service"})
- f.restarted = nil
- syncOnce(t, ctx, reg, s, priv, envDir, f)
+ f.restarted, f.reloads = nil, 0
+ // Declared for b.service now: the pass reaps a.service's drop-in (no
+ // declaration names it) and, because that drop-in still named the
+ // host's env file when the pass planned, refuses to rewrite the file
+ // this pass (census R3-E1); the next pass delivers.
+ out = syncOnce(t, ctx, reg, s, priv, envDir, f)
if _, exists, _, _ := readDropIn(f.ops(), "a.service"); exists {
t.Fatal("old unit's drop-in must be reaped")
}
+ if !strings.Contains(out, "still loaded by a.service's drop-in") || f.reloads != 1 || len(f.restarted) != 0 {
+ t.Fatalf("first pass after the move: reloads=%d restarted=%v out=%q", f.reloads, f.restarted, out)
+ }
+ f.restarted = nil
+ syncOnce(t, ctx, reg, s, priv, envDir, f)
if _, exists, marked, _ := readDropIn(f.ops(), "b.service"); !exists || !marked {
t.Fatal("new unit's drop-in must be written")
}
@@ -1325,45 +1340,30 @@ func TestSyncUnitsKeepsADeclaredHostsEnvFileWhenItsRowGoes(t *testing.T) {
}
}
-// Round 3 P1-3: the declaration file is re-read before each mutation.
-// Changed after the first probe, nothing is written, reloaded or
-// restarted; changed after the post-reload probe, the files and the
-// reload stand but the restart does not run and the marker stays.
-func TestSyncUnitsAbortsWhenTheDeclarationChangesMidPass(t *testing.T) {
- for _, tc := range []struct {
- name string
- probe int
- }{{"after the first probe", 1}, {"before the restart", 2}} {
- t.Run(tc.name, func(t *testing.T) {
- ctx, s, reg, envDir, priv := unitKit(t)
- f := newFakeUnits(t)
- f.loaded("relay.service", envDir, "relay.example.com")
- stampDeclared(t, f, reg, "relay.example.com", "relay.service", nil)
- f.onProbe = func(call int) {
- if call == tc.probe {
- f.declare(t, Declaration{Host: "relay.example.com", Account: "bab", App: "relay", Unit: "other.service"})
- }
- }
- out := syncOnce(t, ctx, reg, s, priv, envDir, f)
- if !strings.Contains(out, "changed during this pass") {
- t.Fatalf("expected the mid-pass abort, got %q", out)
- }
- if len(f.restarted) != 0 {
- t.Fatalf("restarted = %v", f.restarted)
- }
- _, envErr := os.Stat(filepath.Join(envDir, "relay.example.com.env"))
- _, dropExists, _, _ := readDropIn(f.ops(), "relay.service")
- switch tc.probe {
- case 1:
- if envErr == nil || dropExists || hasPending(f.root, "relay.service") || f.reloads != 0 {
- t.Fatalf("mutated after an early change: env=%v drop=%v pending=%v reloads=%d", envErr == nil, dropExists, hasPending(f.root, "relay.service"), f.reloads)
- }
- case 2:
- if envErr != nil || !dropExists || !hasPending(f.root, "relay.service") || f.reloads != 1 {
- t.Fatalf("after a change before the restart: env=%v drop=%v pending=%v reloads=%d", envErr == nil, dropExists, hasPending(f.root, "relay.service"), f.reloads)
- }
- }
- })
+// The tripwire (Paul's ruling, serialisation): the declaration file is
+// read once per pass under the config-sync flock, and read once more just
+// before the first mutation. A hand edit between the two (unsupported;
+// every carlos writer takes the lock) abandons the pass: nothing written,
+// reloaded or restarted.
+func TestSyncUnitsAbortsWhenTheDeclarationChangesBeforeMutation(t *testing.T) {
+ ctx, s, reg, envDir, priv := unitKit(t)
+ f := newFakeUnits(t)
+ f.loaded("relay.service", envDir, "relay.example.com")
+ stampDeclared(t, f, reg, "relay.example.com", "relay.service", nil)
+ f.onProbe = func(call int) {
+ if call == 1 {
+ f.declare(t, Declaration{Host: "relay.example.com", Account: "bab", App: "relay", Unit: "other.service"})
+ }
+ }
+ out := syncOnce(t, ctx, reg, s, priv, envDir, f)
+ if !strings.Contains(out, "changed during this pass") {
+ t.Fatalf("expected the tripwire, got %q", out)
+ }
+ if _, err := os.Stat(filepath.Join(envDir, "relay.example.com.env")); err == nil {
+ t.Fatal("env file written after the tripwire")
+ }
+ if _, exists, _, _ := readDropIn(f.ops(), "relay.service"); exists || hasPending(f.root, "relay.service") || f.reloads != 0 || len(f.restarted) != 0 {
+ t.Fatalf("mutated after the tripwire: drop=%v pending=%v reloads=%d restarted=%v", exists, hasPending(f.root, "relay.service"), f.reloads, f.restarted)
}
}
@@ -1469,3 +1469,160 @@ func TestSyncUnitsRefusesTrailingBytesInTheDeclaration(t *testing.T) {
})
}
}
+
+// hookStore runs onGet before each Get: the hook a witness changes the
+// filesystem from between planning and the first mutation.
+type hookStore struct {
+ release.Store
+ onGet func(key string)
+}
+
+func (h *hookStore) Get(ctx context.Context, key string) ([]byte, string, error) {
+ if h.onGet != nil {
+ h.onGet(key)
+ }
+ return h.Store.Get(ctx, key)
+}
+
+// Census R3-E1: a unit's drop-in keeps loading the env file it names until
+// the drop-in is reaped. With the declaration moved from H1 to H2 for the
+// same unit (H2's route absent), H1's env file is neither rewritten by a
+// row for H1 (unit backing plus another app) nor reaped when H1's row
+// goes; once the declaration is gone and the drop-in reaped, the file goes.
+func TestSyncUnitsKeepsAFormerHostsEnvFileWhileItsDropInLoadsIt(t *testing.T) {
+ ctx, s, reg, envDir, priv := unitKit(t)
+ if err := SetEnv(ctx, s, "bab", "shop", map[string]string{"STOLEN": "x"}); err != nil {
+ t.Fatal(err)
+ }
+ f := newFakeUnits(t)
+ f.loaded("relay.service", envDir, "old.example.com")
+ stampDeclared(t, f, reg, "old.example.com", "relay.service", nil)
+ hostRestarts := 0
+ hostRestart := func(string) error { hostRestarts++; return nil }
+ if err := SyncUnits(ctx, reg, s, priv, envDir, hostRestart, nil, f.ops()); err != nil {
+ t.Fatal(err)
+ }
+ before, err := os.ReadFile(filepath.Join(envDir, "old.example.com.env"))
+ if err != nil || len(f.restarted) != 1 {
+ t.Fatalf("precondition: %v %v", err, f.restarted)
+ }
+ // The declaration moves to H2 for the same unit; H2 has no route.
+ f.declare(t, Declaration{Host: "new.example.com", Account: "bab", App: "relay", Unit: "relay.service"})
+ f.reloads, f.restarted = 0, nil
+
+ // (1) H1's row becomes unit-backed for another app: refused, file intact.
+ upsertStamped(t, reg, "old.example.com", "relay.service", func(r *registry.Route) { r.Backing = registry.BackingUnit; r.Unit = ""; r.App = "shop" })
+ out := captureStdout(t, func() {
+ if err := SyncUnits(ctx, reg, s, priv, envDir, hostRestart, nil, f.ops()); err != nil {
+ t.Fatal(err)
+ }
+ })
+ if !strings.Contains(out, "still loaded by relay.service's drop-in") {
+ t.Fatalf("expected the retained-reference refusal, got %q", out)
+ }
+ if after, _ := os.ReadFile(filepath.Join(envDir, "old.example.com.env")); string(after) != string(before) {
+ t.Fatalf("H1's env file was rewritten: %q", after)
+ }
+ if hostRestarts != 0 || f.reloads != 0 || len(f.restarted) != 0 {
+ t.Fatalf("host restarts=%d reloads=%d restarted=%v", hostRestarts, f.reloads, f.restarted)
+ }
+ // (2) H1's row deleted, an unrelated row present: file and drop-in survive.
+ if err := reg.Delete("old.example.com"); err != nil {
+ t.Fatal(err)
+ }
+ if err := reg.Upsert(registry.Route{Host: "km.example.com", Kind: "instance", App: "relay", Account: "bab", Status: "ready", Backing: registry.BackingUnit}); err != nil {
+ t.Fatal(err)
+ }
+ if err := SyncUnits(ctx, reg, s, priv, envDir, hostRestart, nil, f.ops()); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := os.Stat(filepath.Join(envDir, "old.example.com.env")); err != nil {
+ t.Fatalf("H1's env file was reaped while its drop-in loads it: %v", err)
+ }
+ if _, exists, marked, _ := readDropIn(f.ops(), "relay.service"); !exists || !marked {
+ t.Fatal("the drop-in must survive while the unit is declared")
+ }
+ // (3) The declaration removed: the drop-in is reaped, and with nothing
+ // loading it any more, so is the file.
+ f.undeclare(t)
+ if err := SyncUnits(ctx, reg, s, priv, envDir, hostRestart, nil, f.ops()); err != nil {
+ t.Fatal(err)
+ }
+ if _, exists, _, _ := readDropIn(f.ops(), "relay.service"); exists {
+ t.Fatal("drop-in not reaped once undeclared")
+ }
+ if _, err := os.Stat(filepath.Join(envDir, "old.example.com.env")); !os.IsNotExist(err) {
+ t.Fatalf("H1's env file must go once nothing loads it: %v", err)
+ }
+}
+
+// Round 4 P2: absent and empty are distinct. Planning sees no file (no
+// declarations); an empty file appears before the first mutation; the
+// tripwire stops the pass and a reapable drop-in survives.
+func TestSyncUnitsAbsentThenEmptyDeclarationStopsCleanup(t *testing.T) {
+ ctx, base, reg, envDir, priv := unitKit(t)
+ f := newFakeUnits(t)
+ ensureDropInDir(f.ops(), "old.service")
+ writeDropIn(f.root, "old.service", renderDropIn(envDir, f.base, "old.service", "old.example.com"))
+ // A carlos-app@ row so the pass reads a bundle between planning and
+ // its first mutation.
+ if err := reg.Upsert(registry.Route{Host: "km.example.com", Kind: "instance", App: "relay", Account: "bab", Status: "ready", Backing: registry.BackingUnit}); err != nil {
+ t.Fatal(err)
+ }
+ created := false
+ s := &hookStore{Store: base, onGet: func(string) {
+ if !created {
+ created = true
+ f.declRaw(t, "")
+ }
+ }}
+ hostRestarts := 0
+ out := captureStdout(t, func() {
+ if err := SyncUnits(ctx, reg, s, priv, envDir, func(string) error { hostRestarts++; return nil }, nil, f.ops()); err != nil {
+ t.Fatal(err)
+ }
+ })
+ if !strings.Contains(out, "changed during this pass") {
+ t.Fatalf("expected the tripwire, got %q", out)
+ }
+ if _, exists, _, _ := readDropIn(f.ops(), "old.service"); !exists {
+ t.Fatal("clean-up ran after an absent file became an empty one")
+ }
+ if _, err := os.Stat(filepath.Join(envDir, "km.example.com.env")); err == nil || hostRestarts != 0 {
+ t.Fatal("the ordinary writer ran after the tripwire")
+ }
+ // Absent alone declares nothing and does not trip: the next pass, with
+ // the empty file still there, delivers nothing and reaps nothing.
+ out = captureStdout(t, func() {
+ if err := SyncUnits(ctx, reg, s, priv, envDir, func(string) error { hostRestarts++; return nil }, nil, f.ops()); err != nil {
+ t.Fatal(err)
+ }
+ })
+ if !strings.Contains(out, "nothing delivered and nothing reaped") || hostRestarts != 0 {
+ t.Fatalf("an empty file must deliver and reap nothing, got %q", out)
+ }
+}
+
+// Round 4, item 4: a declaration naming an ordinary (unit-backed) row's
+// host, present in the pass's snapshot, refuses that row before the
+// ordinary writer.
+func TestSyncUnitsRefusesAnOrdinaryRowWhoseHostIsDeclared(t *testing.T) {
+ ctx, s, reg, envDir, priv := unitKit(t)
+ f := newFakeUnits(t)
+ if err := reg.Upsert(registry.Route{Host: "km.example.com", Kind: "instance", App: "relay", Account: "bab", Status: "ready", Backing: registry.BackingUnit}); err != nil {
+ t.Fatal(err)
+ }
+ f.declare(t, Declaration{Host: "km.example.com", Account: "bab", App: "shop", Unit: "km.service"})
+ hostRestarts := 0
+ out := captureStdout(t, func() {
+ if err := SyncUnits(ctx, reg, s, priv, envDir, func(string) error { hostRestarts++; return nil }, nil, f.ops()); err != nil {
+ t.Fatal(err)
+ }
+ })
+ if !strings.Contains(out, "written only through that declaration") {
+ t.Fatalf("expected the declared-host refusal, got %q", out)
+ }
+ if _, err := os.Stat(filepath.Join(envDir, "km.example.com.env")); err == nil || hostRestarts != 0 {
+ t.Fatalf("the ordinary writer wrote a declared host: restarts=%d", hostRestarts)
+ }
+}
diff --git a/internal/host/unitops.go b/internal/host/unitops.go
index c892ea0a6..1e8cf7200 100644
--- a/internal/host/unitops.go
+++ b/internal/host/unitops.go
@@ -10,6 +10,7 @@ import (
"log"
"os"
"os/exec"
+ "path/filepath"
"strings"
"github.com/carlosframework/platform/internal/appconfig"
@@ -35,6 +36,80 @@ func productionUnitOps(envDir string) *appconfig.UnitOps {
}
}
+// InstallNamedUnits is the one carlos writer of the declaration file
+// (Paul's ruling of 2026-10-28, serialisation): it validates raw with the
+// decoder the pass reads with, takes the same config-sync flock SyncUnits
+// holds for a whole pass, and replaces the file atomically: a temp file
+// in the same directory, mode 0644 (root-owned, since the verb runs as
+// root), fsync, rename, fsync of the directory. A pass and an install
+// therefore never interleave: the pass's snapshot is the file for the
+// whole pass. envDir is where the lock lives (appconfig.DefaultEnvDir in
+// production); dst is the declaration path.
+func InstallNamedUnits(envDir, dst string, raw []byte) error {
+ if err := appconfig.ValidateDeclarations(raw); err != nil {
+ return err
+ }
+ unlock, err := lockConfigSync(envDir + "/.sync")
+ if err != nil {
+ return fmt.Errorf("config-sync lock: %w", err)
+ }
+ defer unlock()
+ tmp := dst + ".tmp"
+ f, err := os.OpenFile(tmp, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0o644)
+ if err != nil {
+ return err
+ }
+ write := func() error {
+ if _, err := f.Write(raw); err != nil {
+ return err
+ }
+ if err := f.Sync(); err != nil {
+ return err
+ }
+ return f.Chmod(0o644)
+ }
+ if err := write(); err != nil {
+ f.Close()
+ os.Remove(tmp)
+ return err
+ }
+ if err := f.Close(); err != nil {
+ os.Remove(tmp)
+ return err
+ }
+ if err := os.Rename(tmp, dst); err != nil {
+ os.Remove(tmp)
+ return err
+ }
+ dir, err := os.Open(filepath.Dir(dst))
+ if err != nil {
+ return err
+ }
+ defer dir.Close()
+ return dir.Sync()
+}
+
+// RunSystemNamedUnits is `carlos system named-units install <file>`: the
+// root-only verb that installs a validated declaration file under the
+// config-sync lock. Provisioning writes the file before the agent starts,
+// or runs this verb; a hand edit while carlos runs is unsupported.
+func RunSystemNamedUnits(args []string) {
+ if len(args) != 2 || args[0] != "install" {
+ log.Fatal("usage: carlos system named-units install <file>")
+ }
+ if os.Geteuid() != 0 {
+ log.Fatal("carlos system named-units install: must run as root")
+ }
+ raw, err := os.ReadFile(args[1])
+ if err != nil {
+ log.Fatalf("carlos system named-units install: %v", err)
+ }
+ if err := InstallNamedUnits(appconfig.DefaultEnvDir, appconfig.DefaultNamedUnitsPath, raw); err != nil {
+ log.Fatalf("carlos system named-units install: %v", err)
+ }
+ fmt.Printf("installed %s\n", appconfig.DefaultNamedUnitsPath)
+}
+
// lockConfigSync is lockRestartMarks's shape for the config pass: an
// exclusive flock on <path>.lock held for the whole of one SyncUnits, so
// carlos-adopt.service and carlos-config-sync.service queue rather than
diff --git a/internal/host/unitops_test.go b/internal/host/unitops_test.go
index 27c6452c1..03fe5fa1d 100644
--- a/internal/host/unitops_test.go
+++ b/internal/host/unitops_test.go
@@ -1,8 +1,13 @@
package host
import (
+ "os"
+ "path/filepath"
"strings"
"testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/appconfig"
)
func TestParseSystemctlShowBatched(t *testing.T) {
@@ -64,3 +69,51 @@ func TestProductionUnitOpsDeclarationIsTheReleasePathsFile(t *testing.T) {
t.Fatalf("NamedUnitsPath = %q, want %q", ops.NamedUnitsPath, rootNamedUnits)
}
}
+
+// The declaration installer takes the config-sync flock a pass holds, so
+// an install blocks until the pass releases it; it validates before it
+// takes the lock, and the file lands atomically at 0644.
+func TestInstallNamedUnitsWaitsForTheConfigSyncLock(t *testing.T) {
+ dir := t.TempDir()
+ dst := filepath.Join(dir, "named-units.json")
+ body := []byte(`{"schema":1,"units":[{"host":"relay.example.com","account":"bab","app":"relay","unit":"relay.service","addr":"127.0.0.1:8451","health":{"path":"/ready"}}]}`)
+ if err := InstallNamedUnits(dir, dst, []byte(`{"schema":1,"units":[]}garbage`)); err == nil {
+ t.Fatal("an invalid file was installed")
+ }
+ if err := appconfig.ValidateDeclarations(body); err != nil {
+ t.Fatal(err)
+ }
+ unlock, err := lockConfigSync(dir + "/.sync")
+ if err != nil {
+ t.Fatal(err)
+ }
+ done := make(chan error, 1)
+ go func() { done <- InstallNamedUnits(dir, dst, body) }()
+ select {
+ case err := <-done:
+ t.Fatalf("install finished while the pass held the lock: %v", err)
+ case <-time.After(300 * time.Millisecond):
+ }
+ if _, err := os.Stat(dst); err == nil {
+ t.Fatal("the file appeared while the lock was held")
+ }
+ unlock()
+ select {
+ case err := <-done:
+ if err != nil {
+ t.Fatal(err)
+ }
+ case <-time.After(5 * time.Second):
+ t.Fatal("install did not proceed once the lock was released")
+ }
+ got, err := os.ReadFile(dst)
+ if err != nil || string(got) != string(body) {
+ t.Fatalf("installed = %q, %v", got, err)
+ }
+ if st, _ := os.Stat(dst); st.Mode().Perm() != 0o644 {
+ t.Fatalf("mode = %o, want 0644", st.Mode().Perm())
+ }
+ if _, err := os.Stat(dst + ".tmp"); !os.IsNotExist(err) {
+ t.Fatal("temp file left behind")
+ }
+}
diff --git a/system.go b/system.go
index 2fd4cc2a6..d7fbb06b8 100644
--- a/system.go
+++ b/system.go
@@ -52,7 +52,7 @@ func systemVerb(args []string) (verb string, rest []string, component string) {
// untouched in rest for runSystemAntivirusVerb to read.
// layout is a family too: migrate|revert|status stay in rest for
// runSystemLayout.
- case "files", "guard-arm", "guard-exec", "journal-migrate", "floor-allows-prev", "update", "status", "rollback", "cancel-activation", "apply", "antivirus", "layout", "geoip", "seeds-floor", "legacy-routes", "lifetimes", "hosts-used", "box", "group", "install-channel", "host-env", "db-worker", "help", "-h", "--help":
+ case "files", "guard-arm", "guard-exec", "journal-migrate", "floor-allows-prev", "update", "status", "rollback", "cancel-activation", "apply", "antivirus", "layout", "geoip", "seeds-floor", "legacy-routes", "lifetimes", "hosts-used", "box", "group", "install-channel", "host-env", "db-worker", "named-units", "help", "-h", "--help":
return args[0], args[1:], component
}
return "", args, component
@@ -107,6 +107,8 @@ func runSystem(args []string) {
case "host-env":
// host.env from and into the deployment's parameters (§5 step 2).
hostenv.RunSystemHostEnv(rest)
+ case "named-units":
+ host.RunSystemNamedUnits(rest)
case "db-worker":
// The db-read worker (db region forward spec §8.3): systemd starts
// it per connection to carlos-dbread.socket. Never run by hand.
@@ -147,6 +149,7 @@ func systemUsage() {
carlos system legacy-routes assign --name <name> --to <account>/<app>
carlos system lifetimes cutover [--no-wait]
carlos system hosts-used status
+ carlos system named-units install <file>
carlos system box role <box> <default|legacy|platform>
carlos system box publish-record
carlos system group role <region> <default|legacy>