carlos / platform Public

instances: stop-policy gate across installs and rollbacks (#528 ruling A)

A running instance keeps the stop policy it started with: before the
reload, the installer pins each running unit whose template policy
changes (runtime drop-in), instance-control clears the pin at the unit's
next start, and one lock spans binary swap to reload. Root runner
20261108T171416-57ae01 PASS incl. the gate on real systemd.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 7fd56cc56827f04b28565badc603cfa6d83b2ca2 parent eb0e152
11 files changed, +679 −9
  • docs/superpowers/specs/2026-11-08-instance-stop-privatepids-528-design.md +34 −5
  • internal/host/bootstrap.go +14 −0
  • internal/host/instancestop_rootrunner_linux_test.go +78 −0
  • internal/host/stoppolicy.go +78 −0
  • internal/host/stoppolicy_test.go +160 −0
  • internal/host/systemapply.go +50 −2
  • internal/instancectl/server.go +4 −2
  • internal/instancectl/stoppolicy.go +67 −0
  • internal/instancectl/stoppolicy_linux.go +77 −0
  • internal/instancectl/stoppolicy_linux_test.go +104 −0
  • internal/instancectl/stoppolicy_other.go +13 −0

Intent

Human

<task-notification> <task-id>aa4f6b09d00fff073</task-id> <tool-use-id>toolu_014To2FB414Ys8eDtqpjtmCz</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/57f7b202-ce27-4792-9462-b99ef5f502c4/tasks/aa4f6b09d00fff073.output</output-file> <status>completed</status> <summary>Agent "Fix 2: #528 PrivatePIDs stop" finished</summary> <note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note> <result>I fixed both and pushed. The new tip is `eb0e15281b33a505ad4d6053d7c47b14c72511ee`; CI is queued on it. I haven't merged or started R3. - **9B8 re-pin:** I updated only the `claimBoundTemplate` row in `internal/provision/plan14_e_write_census_test.go`. Its digest moves from `9ff0f840…` to `f27e8b84…`; the row's kinds (`lit:instances`) are unchanged. I computed the new value the way `plan9_b8_census_test.go:189` does: sha256 of the whole `const claimBoundTemplate` declaration. The same calculation on origin/main gives the old pinned `9ff0f840…`, so the method matches the test. Locally, `TestPlan9B8RecordWriteCensus` and `TestPlan14RootReadCensus` both pass. - **R2 P2:** the witness now fails if none of the 40 fast-exit cycles had an alien start. That is a test-only change, so I didn't re-run the root runner; the last run (20261108T160744-e76dbf) had 4 of 40 fast-exit starts alien, so it would have passed. I've noted both items for the R3 brief in `~/.cache/tmp/f528/R3-NOTES.md`, including asking Astra to review the re-pin and citing 7d0f26c as the precedent. I'll start R3 once you relay 55f1f6a's ruling on the roll-mixing P1. If that fix touches the templates or the envelopes again, I'll re-run census-propose first.</result> <usage><subagent_tokens>374375</subagent_tokens><tool_uses>6</tool_uses><duration_ms>86179</duration_ms></usage> </task-notification>

Human

<paseo-system version="1" kind="agent-message" source-agent-id="55f1f6a4-252a-4d89-af7b-a8a460b2b81d" message-id="e77693ce-a608-40b7-a96e-ebd9137b997b"> Coordinator 55f1f6a: Paul RULED (A) refuse up front for #528: the new stop policy (unit install and rollback) only takes effect for an instance after it has stopped under the policy it started with; running instances never see a mixed old/new trampoline and unit. Fix the P2 (witness requires an alien fast-exit start), re-run census-propose, Astra R3 (the last allowed; brief it with rounds 1-2 and Paul&apos;s ruling), green CI, squash-merge, then give 8a3d302 the SHA for v0.34.29. If R3 finds another P1 in the same family, stop and report to me rather than fixing. </paseo-system>

Human

Check the Fix 2 fork (branch instance-stop-528, worktree .claude/worktrees/instance-stop-528); when it reports a merged SHA, verify it on origin/main, send it to 8a3d302 (paseo send 8a3d302a-eac7-407c-b61c-f5ccc66b5544) and report to 55f1f6a; continue the brief ~/.cache/start-hardening/BRIEF.md.

diff --git a/docs/superpowers/specs/2026-11-08-instance-stop-privatepids-528-design.md b/docs/superpowers/specs/2026-11-08-instance-stop-privatepids-528-design.md
index 215b7728d..68ff10122 100644
--- a/docs/superpowers/specs/2026-11-08-instance-stop-privatepids-528-design.md
+++ b/docs/superpowers/specs/2026-11-08-instance-stop-privatepids-528-design.md
@@ -108,11 +108,40 @@ It now sends `instancectl.RetireSignal` (SIGPWR), which the trampoline turns
into one SIGTERM for the app in either mode. A launch the agent holds itself
still gets SIGTERM.
-Rolls mix versions for a moment. A trampoline from before this change in a
-new unit forwards as before (two SIGTERMs, today's mixed-era behaviour); a
-new trampoline under an old `mixed` unit has no `CARLOS_INIT_STOP` and
-forwards as before; an old trampoline drops SIGPWR (no handler, PID 1), so a
-`Retire` falls back to the unit stop's SIGTERM after its grace.
+### The stop-policy gate (Paul's ruling A, 2026-11-08)
+
+Astra R2 found that rolls and rollbacks mix versions: systemd reads
+`KillMode=` at stop time from the unit as last reloaded, so a running
+instance started under one policy could be stopped under the other (an old
+forwarding trampoline under `control-group`: two SIGTERMs; a new direct
+trampoline under a rolled-back `mixed`: none). Paul ruled "refuse up front":
+the new stop policy takes effect for an instance only after it has stopped
+under the policy it started with; a running instance never sees a mixed
+old/new trampoline and unit.
+
+- **Pins.** Before the reload that loads new templates, the installer
+ (`installUnits`, which both apply and rollback use, and a live
+ `carlos bootstrap`) lists running `carlos-instance*@` units. For each whose
+ template's policy (`KillMode=` plus `CARLOS_INIT_STOP`) is about to change,
+ it writes `/run/systemd/system/<unit>.d/99-carlos-stop-pin.conf` with the
+ policy the unit is running under, as loaded now. A unit whose policy does not
+ change gets no pin, so an ordinary roll costs nothing. An existing pin is
+ kept. Anything it cannot read refuses the install.
+- **Clearing.** instance-control's systemctl (`PinAwareSystemctl`) removes a
+ unit's pin, and reloads, just before it starts that unit. So the pin lasts
+ exactly as long as the invocation it protects; it is under `/run`, so a
+ reboot (which stops everything) clears it too.
+- **One window.** An exclusive lock
+ (`/opt/carlos/system/stop-policy.lock`) spans the installer's binary swap
+ to its reload; every instance-control start takes it shared. No unit starts
+ between the swap and the reload, and none between the pins and the reload.
+ The apply releases it before a rollback, which takes it again.
+- **Upgrading from a build without the gate.** The installer is the new build
+ (apply) or the build that ships the gate (rollback from it), so the pins
+ exist whenever the transition happens. The old instance-control does not
+ take the lock, but in the upgrade window its starts run the new trampoline
+ under the old `mixed` units with no `CARLOS_INIT_STOP`, which forwards: one
+ SIGTERM, consistent.
The stop then ends as designed: the app drains and exits; the trampoline
exits with the app's status, or 143, which `SuccessExitStatus=` counts as
diff --git a/internal/host/bootstrap.go b/internal/host/bootstrap.go
index 0d766dd73..684f21aa0 100644
--- a/internal/host/bootstrap.go
+++ b/internal/host/bootstrap.go
@@ -13,6 +13,7 @@ import (
"github.com/carlosframework/platform/internal/cliflag"
"github.com/carlosframework/platform/internal/demo"
"github.com/carlosframework/platform/internal/hostenv"
+ "github.com/carlosframework/platform/internal/instancectl"
"bytes"
"embed"
@@ -552,6 +553,16 @@ func bootstrapWithGroup(root string, consumers []string, planJSON, group bool) e
if err != nil {
return err
}
+ // A live bootstrap rewrites the instance templates under running
+ // instances: hold the stop-policy window from the first write to the
+ // reload, and pin before it (#528, ruling A; stoppolicy.go).
+ if live {
+ releaseStop, err := instancectl.LockStopPolicy(instancectl.StopPolicyLockPath(filepath.Join(root, "opt", "carlos")), true)
+ if err != nil {
+ return fmt.Errorf("stop-policy lock: %w", err)
+ }
+ defer releaseStop()
+ }
for _, name := range names {
if group && groupAutomaticUnit(name) {
continue
@@ -676,6 +687,9 @@ func bootstrapWithGroup(root string, consumers []string, planJSON, group bool) e
if out, err := exec.Command(tmpfilesApply[0], tmpfilesApply[1:]...).CombinedOutput(); err != nil {
return fmt.Errorf("%s: %v: %s", strings.Join(tmpfilesApply, " "), err, strings.TrimSpace(string(out)))
}
+ if err := pinStopPolicies(productionSysOps().systemctl, unitDir, "/run/systemd/system"); err != nil {
+ return err
+ }
for _, args := range launchPlan {
if err := systemctl(args...); err != nil {
return err
diff --git a/internal/host/instancestop_rootrunner_linux_test.go b/internal/host/instancestop_rootrunner_linux_test.go
index 3524179c9..15e44db68 100644
--- a/internal/host/instancestop_rootrunner_linux_test.go
+++ b/internal/host/instancestop_rootrunner_linux_test.go
@@ -3,6 +3,7 @@
package host
import (
+ "context"
"encoding/json"
"errors"
"io/fs"
@@ -428,6 +429,83 @@ func TestRootInstanceStopUnderPrivatePIDs(t *testing.T) {
t.Errorf("retire signal did not drain the tenant on one SIGTERM: %+v", o)
}
+ // 2d. The stop-policy gate (#528, ruling A), on real systemd: a unit
+ // running the old policy is pinned to it across the install's reload,
+ // and its next start through instance-control's systemctl clears the
+ // pin and runs the shipped policy.
+ shipped := t.TempDir()
+ if err := os.WriteFile(filepath.Join(shipped, template), []byte(strings.Join(lines, "\n")), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ pinPath := filepath.Join("/run/systemd/system", unit+".d", instancectl.StopPolicyPinName)
+ t.Cleanup(func() { _ = os.RemoveAll(filepath.Dir(pinPath)) })
+ dropIn("50-mixed.conf", "KillMode=mixed\nUnsetEnvironment="+instancectl.InitStopEnv)
+ launch("drain")
+ _, _ = ctl("reset-failed", unit)
+ for _, f := range []string{"up", "terms", "drained"} {
+ _ = os.Remove(filepath.Join(data, f))
+ }
+ must("start", unit)
+ for deadline := time.Now().Add(15 * time.Second); ; {
+ if _, err := os.Stat(filepath.Join(data, "up")); err == nil {
+ break
+ }
+ if time.Now().After(deadline) {
+ t.Fatal("tenant never came up under the old policy")
+ }
+ time.Sleep(20 * time.Millisecond)
+ }
+ // The install: new templates on disk, pins, then the reload.
+ if err := os.Remove(filepath.Join(dropDir, "50-mixed.conf")); err != nil {
+ t.Fatal(err)
+ }
+ if err := pinStopPoliciesOf(productionSysOps().systemctl, "carlos-stopwit@*.service", shipped, "/run/systemd/system"); err != nil {
+ t.Fatal(err)
+ }
+ must("daemon-reload")
+ if km := must("show", "-p", "KillMode", "--value", unit); km != "mixed" {
+ t.Fatalf("running unit's KillMode after the install's reload: %s, want its own mixed", km)
+ }
+ must("stop", unit)
+ b, _ := os.ReadFile(filepath.Join(data, "terms"))
+ t.Logf("verdict: gate: pinned stop under the old policy: %s, %d SIGTERM(s)", must("show", "-p", "Result", "--value", unit), strings.Count(string(b), "term\n"))
+ if n := strings.Count(string(b), "term\n"); n > 1 {
+ t.Errorf("pinned stop gave the tenant %d SIGTERMs", n)
+ }
+ gated := instancectl.PinAwareSystemctl(filepath.Join(t.TempDir(), "stop-policy.lock"), "/run/systemd/system", func(ctx context.Context, args ...string) (string, error) {
+ out, err := exec.CommandContext(ctx, "systemctl", args...).CombinedOutput()
+ return string(out), err
+ })
+ _, _ = ctl("reset-failed", unit)
+ for _, f := range []string{"up", "terms", "drained"} {
+ _ = os.Remove(filepath.Join(data, f))
+ }
+ if out, err := gated(t.Context(), "start", unit); err != nil {
+ t.Fatalf("gated start: %v %s", err, out)
+ }
+ if _, err := os.Stat(pinPath); !errors.Is(err, fs.ErrNotExist) {
+ t.Fatalf("the gated start left the pin: %v", err)
+ }
+ if km := must("show", "-p", "KillMode", "--value", unit); km != "control-group" {
+ t.Fatalf("next start's KillMode %s, want the shipped control-group", km)
+ }
+ for deadline := time.Now().Add(15 * time.Second); ; {
+ if _, err := os.Stat(filepath.Join(data, "up")); err == nil {
+ break
+ }
+ if time.Now().After(deadline) {
+ t.Fatal("tenant never came up after the gated start")
+ }
+ time.Sleep(20 * time.Millisecond)
+ }
+ must("stop", unit)
+ b, _ = os.ReadFile(filepath.Join(data, "terms"))
+ res := must("show", "-p", "Result", "--value", unit)
+ t.Logf("verdict: gate: next start under the shipped policy: %s, %d SIGTERM(s)", res, strings.Count(string(b), "term\n"))
+ if res != "success" || strings.Count(string(b), "term\n") != 1 {
+ t.Errorf("stop after the gated start: %s, %d SIGTERMs", res, strings.Count(string(b), "term\n"))
+ }
+
// 3. A tenant that ignores SIGTERM is still killed within the bound.
launch("ignore")
dropIn("50-short.conf", "TimeoutStopSec=3")
diff --git a/internal/host/stoppolicy.go b/internal/host/stoppolicy.go
new file mode 100644
index 000000000..1b27819f6
--- /dev/null
+++ b/internal/host/stoppolicy.go
@@ -0,0 +1,78 @@
+package host
+
+import (
+ "errors"
+ "fmt"
+ "io/fs"
+ "os"
+ "path/filepath"
+ "strings"
+
+ "github.com/carlosframework/platform/internal/instancectl"
+)
+
+// runningUnitStates are the ActiveStates of a unit with a process whose
+// stop is still to come.
+const runningUnitStates = "--state=active,activating,deactivating,reloading,refreshing"
+
+// pinStopPolicies is the installer's half of the stop-policy gate (#528,
+// Paul's ruling A; instancectl/stoppolicy.go). Run after the new
+// templates are in templateDir and before the reload that loads them, it
+// pins every running instance unit whose template's stop policy is about
+// to change to the policy it is running under, as loaded now: a runtime
+// drop-in in pinDir that instance-control removes at the unit's next
+// start. A unit whose policy does not change gets no pin, so an ordinary
+// roll costs no extra reload. A pin already there is kept: it holds the
+// policy the unit started with. Anything it cannot read refuses the
+// install rather than reload under a running unit.
+func pinStopPolicies(systemctl func(args ...string) (string, error), templateDir, pinDir string) error {
+ return pinStopPoliciesOf(systemctl, "carlos-instance*@*.service", templateDir, pinDir)
+}
+
+// pinStopPoliciesOf is pinStopPolicies over the units pattern names (the
+// root-runner witness's own template).
+func pinStopPoliciesOf(systemctl func(args ...string) (string, error), pattern, templateDir, pinDir string) error {
+ out, err := systemctl("list-units", "--plain", "--no-legend", "--type=service", runningUnitStates, pattern)
+ if err != nil {
+ return fmt.Errorf("stop-policy gate: list running instance units: %w", err)
+ }
+ for _, line := range strings.Split(out, "\n") {
+ fields := strings.Fields(line)
+ if len(fields) == 0 {
+ continue
+ }
+ unit := fields[0]
+ at := strings.Index(unit, "@")
+ if at < 0 || !strings.HasSuffix(unit, ".service") || strings.ContainsAny(unit, "/\x00") {
+ continue
+ }
+ template := unit[:at+1] + ".service"
+ pin := filepath.Join(pinDir, unit+".d", instancectl.StopPolicyPinName)
+ if _, err := os.Lstat(pin); err == nil {
+ continue
+ } else if !errors.Is(err, fs.ErrNotExist) {
+ return fmt.Errorf("stop-policy gate: %s: %w", pin, err)
+ }
+ shown, err := systemctl("show", "-p", "KillMode", "-p", "Environment", unit)
+ if err != nil {
+ return fmt.Errorf("stop-policy gate: read %s: %w", unit, err)
+ }
+ mode, initStop := instancectl.StopPolicyOf(shown)
+ next, err := os.ReadFile(filepath.Join(templateDir, template))
+ switch {
+ case err == nil:
+ if nm, ni := instancectl.StopPolicyOf(string(next)); nm == mode && ni == initStop {
+ continue
+ }
+ case !errors.Is(err, fs.ErrNotExist):
+ return fmt.Errorf("stop-policy gate: read %s: %w", template, err)
+ }
+ if err := os.MkdirAll(filepath.Dir(pin), 0o755); err != nil {
+ return fmt.Errorf("stop-policy gate: %w", err)
+ }
+ if err := writeFileDurable(pin, instancectl.StopPolicyPin(mode, initStop), 0o644); err != nil {
+ return fmt.Errorf("stop-policy gate: pin %s: %w", unit, err)
+ }
+ }
+ return nil
+}
diff --git a/internal/host/stoppolicy_test.go b/internal/host/stoppolicy_test.go
new file mode 100644
index 000000000..3fcff3c9c
--- /dev/null
+++ b/internal/host/stoppolicy_test.go
@@ -0,0 +1,160 @@
+package host
+
+import (
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+
+ "github.com/carlosframework/platform/internal/instancectl"
+)
+
+// An install that changes a template's stop policy pins each RUNNING unit
+// of that template to the policy it started with, before the reload; a
+// unit whose policy does not change, and a stopped unit, get no pin; an
+// existing pin is never replaced (#528, ruling A).
+func TestPinStopPoliciesPinsOnlyRunningUnitsWhosePolicyChanges(t *testing.T) {
+ templates, pins := t.TempDir(), t.TempDir()
+ write := func(name, body string) {
+ if err := os.WriteFile(filepath.Join(templates, name), []byte(body), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ }
+ // The new build's templates.
+ write("carlos-instance@.service", "[Service]\nKillMode=control-group\nEnvironment=CARLOS_INIT_STOP=cgroup\n")
+ write("carlos-instance-gen@.service", "[Service]\nKillMode=control-group\nEnvironment=CARLOS_INIT_STOP=cgroup\n")
+ write("carlos-instance-seed@.service", "[Service]\nKillMode=mixed\n")
+ loaded := map[string]string{
+ "carlos-instance@shop.service": "KillMode=mixed\nEnvironment=\n",
+ "carlos-instance-gen@shop:3.service": "KillMode=mixed\nEnvironment=PATH=/bin\n",
+ "carlos-instance-seed@shop.service": "KillMode=mixed\nEnvironment=\n",
+ "carlos-instance@kept.service": "KillMode=mixed\nEnvironment=\n",
+ "carlos-instance@same.service": "KillMode=control-group\nEnvironment=CARLOS_INIT_STOP=cgroup\n",
+ }
+ kept := filepath.Join(pins, "carlos-instance@kept.service.d", instancectl.StopPolicyPinName)
+ if err := os.MkdirAll(filepath.Dir(kept), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(kept, []byte("original"), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ var listArgs string
+ systemctl := func(args ...string) (string, error) {
+ switch args[0] {
+ case "list-units":
+ listArgs = strings.Join(args, " ")
+ return "carlos-instance@shop.service loaded active running x\ncarlos-instance-gen@shop:3.service loaded deactivating stop-sigterm x\ncarlos-instance-seed@shop.service loaded active exited x\ncarlos-instance@kept.service loaded active running x\ncarlos-instance@same.service loaded active running x\n", nil
+ case "show":
+ return loaded[args[len(args)-1]], nil
+ }
+ t.Fatalf("unexpected systemctl %v", args)
+ return "", nil
+ }
+ if err := pinStopPolicies(systemctl, templates, pins); err != nil {
+ t.Fatal(err)
+ }
+ if !strings.Contains(listArgs, "--state=") || strings.Contains(listArgs, "--all") {
+ t.Errorf("list-units must ask for running units only: %q", listArgs)
+ }
+ pinOf := func(unit string) string {
+ b, err := os.ReadFile(filepath.Join(pins, unit+".d", instancectl.StopPolicyPinName))
+ if err != nil {
+ return ""
+ }
+ return string(b)
+ }
+ old := string(instancectl.StopPolicyPin("mixed", false))
+ if got := pinOf("carlos-instance@shop.service"); got != old {
+ t.Errorf("run unit pin %q, want %q", got, old)
+ }
+ if got := pinOf("carlos-instance-gen@shop:3.service"); got != old {
+ t.Errorf("stopping gen unit pin %q, want %q", got, old)
+ }
+ for _, u := range []string{"carlos-instance-seed@shop.service", "carlos-instance@same.service"} {
+ if got := pinOf(u); got != "" {
+ t.Errorf("%s pinned though its policy does not change: %q", u, got)
+ }
+ }
+ if got := pinOf("carlos-instance@kept.service"); got != "original" {
+ t.Errorf("an existing pin was replaced: %q", got)
+ }
+}
+
+// The rollback direction: a unit running the new policy keeps it when the
+// old templates come back.
+func TestPinStopPoliciesPinsTheNewPolicyOnRollback(t *testing.T) {
+ templates, pins := t.TempDir(), t.TempDir()
+ if err := os.WriteFile(filepath.Join(templates, "carlos-instance@.service"), []byte("[Service]\nKillMode=mixed\n"), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ systemctl := func(args ...string) (string, error) {
+ if args[0] == "list-units" {
+ return "carlos-instance@shop.service loaded active running x\n", nil
+ }
+ return "KillMode=control-group\nEnvironment=CARLOS_INIT_STOP=cgroup\n", nil
+ }
+ if err := pinStopPolicies(systemctl, templates, pins); err != nil {
+ t.Fatal(err)
+ }
+ b, _ := os.ReadFile(filepath.Join(pins, "carlos-instance@shop.service.d", instancectl.StopPolicyPinName))
+ if string(b) != string(instancectl.StopPolicyPin("control-group", true)) {
+ t.Errorf("rollback pin %q", b)
+ }
+}
+
+// A failure to read a running unit's policy refuses the install.
+func TestPinStopPoliciesRefusesWhatItCannotRead(t *testing.T) {
+ templates, pins := t.TempDir(), t.TempDir()
+ if err := os.WriteFile(filepath.Join(templates, "carlos-instance@.service"), []byte("[Service]\nKillMode=mixed\n"), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ systemctl := func(args ...string) (string, error) {
+ if args[0] == "list-units" {
+ return "carlos-instance@shop.service loaded active running x\n", nil
+ }
+ return "", os.ErrPermission
+ }
+ if err := pinStopPolicies(systemctl, templates, pins); err == nil {
+ t.Fatal("an unreadable running unit did not refuse the install")
+ }
+}
+
+// installUnits, the apply's and the rollback's unit step, pins a running
+// unit whose policy the new templates change, and pins it before the
+// reload that would change it.
+func TestInstallUnitsPinsBeforeTheReload(t *testing.T) {
+ stage := t.TempDir()
+ if err := bootstrap(stage, nil); err != nil {
+ t.Fatal(err)
+ }
+ f := newApplyFixture(t, "stable", "v1.0.0")
+ var order []string
+ pin := filepath.Join(f.a.runtimeUnitDir(), "carlos-instance@shop.service.d", instancectl.StopPolicyPinName)
+ f.a.ops.systemctl = func(args ...string) (string, error) {
+ switch args[0] {
+ case "list-units":
+ return "carlos-instance@shop.service loaded active running x\n", nil
+ case "show":
+ if len(args) > 2 && args[1] == "-p" && args[2] == "KillMode" {
+ return "KillMode=mixed\nEnvironment=\n", nil
+ }
+ case "daemon-reload":
+ if _, err := os.Stat(pin); err != nil {
+ order = append(order, "reload before pin")
+ } else {
+ order = append(order, "reload after pin")
+ }
+ }
+ return "", nil
+ }
+ if err := f.a.installUnits(t.Context(), stage, nil); err != nil {
+ t.Fatal(err)
+ }
+ if len(order) == 0 || order[0] != "reload after pin" {
+ t.Fatalf("reloads: %v", order)
+ }
+ b, _ := os.ReadFile(pin)
+ if string(b) != string(instancectl.StopPolicyPin("mixed", false)) {
+ t.Fatalf("pin %q", b)
+ }
+}
diff --git a/internal/host/systemapply.go b/internal/host/systemapply.go
index 9ccb2d87e..bec31e501 100644
--- a/internal/host/systemapply.go
+++ b/internal/host/systemapply.go
@@ -19,6 +19,7 @@ import (
"runtime"
"slices"
"strings"
+ "sync"
"time"
"github.com/carlosframework/platform/internal/activator"
@@ -26,6 +27,7 @@ import (
"github.com/carlosframework/platform/internal/demo"
"github.com/carlosframework/platform/internal/hostfloor"
"github.com/carlosframework/platform/internal/hostwrite"
+ "github.com/carlosframework/platform/internal/instancectl"
"github.com/carlosframework/platform/internal/layout"
"github.com/carlosframework/platform/internal/moves"
"github.com/carlosframework/platform/internal/provision"
@@ -295,7 +297,28 @@ type systemApplier struct {
beforeSwap func()
}
-func (a *systemApplier) rootDir() string { return systemRootDir(a.optDir) }
+func (a *systemApplier) rootDir() string { return systemRootDir(a.optDir) }
+
+// runtimeUnitDir is systemd's runtime unit directory, where the stop-policy
+// pins go: /run/systemd/system on a box, a sibling of a test's etc dir.
+func (a *systemApplier) runtimeUnitDir() string {
+ if a.etcDir == "/etc" {
+ return "/run/systemd/system"
+ }
+ return filepath.Join(filepath.Dir(a.etcDir), "run", "systemd", "system")
+}
+
+// holdStopPolicy takes the stop-policy lock for an install's window, from
+// its binary swap to its reload (#528, ruling A): instance-control starts
+// nothing meanwhile. The release is idempotent.
+func (a *systemApplier) holdStopPolicy() (func(), error) {
+ unlock, err := instancectl.LockStopPolicy(instancectl.StopPolicyLockPath(a.optDir), true)
+ if err != nil {
+ return nil, fmt.Errorf("stop-policy lock: %w", err)
+ }
+ var once sync.Once
+ return func() { once.Do(unlock) }, nil
+}
func (a *systemApplier) stagingDir() string { return filepath.Join(a.rootDir(), "staging") }
func (a *systemApplier) lockPath() string { return filepath.Join(a.rootDir(), systemLockFile) }
func (a *systemApplier) file(name string) string { return filepath.Join(a.rootDir(), name) }
@@ -667,6 +690,14 @@ func (a *systemApplier) install(ctx context.Context, req systemRequest, p *relea
// check before staging can have gone stale, since the agent may have
// raised the floor or held a row since. activationGuard holds the floor
// and the holds still across the rename.
+ // The stop-policy window opens before the swap and closes after the
+ // reload: no instance starts between them (#528, ruling A). It is let
+ // go before any rollback, which takes it again.
+ releaseStop, err := a.holdStopPolicy()
+ if err != nil {
+ return a.abandonInstall(req, err, prior)
+ }
+ defer releaseStop()
renamed := false
if err := a.activationGuard(ctx, target, running, func(ctx context.Context) error {
if err := a.rootProtocolAllowsBinary(staged); err != nil {
@@ -675,6 +706,7 @@ func (a *systemApplier) install(ctx context.Context, req systemRequest, p *relea
renamed = true
return os.Rename(staged, systemBinaryPath(a.optDir))
}); err != nil {
+ releaseStop()
if !renamed {
return a.abandonInstall(req, err, prior)
}
@@ -685,9 +717,12 @@ func (a *systemApplier) install(ctx context.Context, req systemRequest, p *relea
}
j.Phase = systemPhaseInstalled
if err := a.journal(j); err != nil {
+ releaseStop()
return fail("journal", err)
}
- if err := a.installUnits(ctx, newDir, j.UnitsRemoved); err != nil {
+ err = a.installUnits(ctx, newDir, j.UnitsRemoved)
+ releaseStop()
+ if err != nil {
return fail("units", err)
}
j.Phase = systemPhaseUnits
@@ -1560,6 +1595,12 @@ func (a *systemApplier) installUnits(ctx context.Context, stagedRoot string, rem
if _, err := a.ops.run(ctx, systemVersionWait, "systemd-tmpfiles", "--create", dst); err != nil {
a.ops.logf("system apply: systemd-tmpfiles: %v (continuing, as the script does)", err)
}
+ // Before the reload: a running instance keeps the stop policy it
+ // started with (#528, ruling A; stoppolicy.go). The caller holds the
+ // stop-policy lock, so nothing starts between these pins and the reload.
+ if err := pinStopPolicies(a.ops.systemctl, unitDir, a.runtimeUnitDir()); err != nil {
+ return err
+ }
if _, err = a.ops.systemctl("daemon-reload"); err != nil {
return err
}
@@ -1996,6 +2037,13 @@ func (a *systemApplier) restoreFiles(ctx context.Context, j *systemJournal) (boo
// carlos.prev is copied beside the binary first, outside any lock, and
// renamed over it under the activation guard, so the rule's inputs are
// held still for a rename rather than a whole binary copy.
+ // The stop-policy window, as the install's: from the swap back to the
+ // reload of the restored units (#528, ruling A).
+ releaseStop, err := a.holdStopPolicy()
+ if err != nil {
+ return bootstrapPlan{}, err
+ }
+ defer releaseStop()
restore := systemBinaryPath(a.optDir) + ".restore"
if err := copyFileDurable(prev, restore, 0o755); err != nil {
return bootstrapPlan{}, err
diff --git a/internal/instancectl/server.go b/internal/instancectl/server.go
index 6714a6882..6d667cb5c 100644
--- a/internal/instancectl/server.go
+++ b/internal/instancectl/server.go
@@ -283,10 +283,12 @@ func runWithClaim(args []string, claim, heldRelease http.Handler, view RegistryV
DemoBox: cfg.BoxMode(),
ClaimStop: claim,
ClaimHeldRelease: heldRelease,
- Systemctl: func(ctx context.Context, args ...string) (string, error) {
+ // Every start clears its unit's stop-policy pin first and waits
+ // out an install's window (#528, ruling A; stoppolicy.go).
+ Systemctl: PinAwareSystemctl(StopPolicyLockPath("/opt/carlos"), "/run/systemd/system", func(ctx context.Context, args ...string) (string, error) {
out, err := exec.CommandContext(ctx, "systemctl", args...).CombinedOutput()
return string(out), err
- },
+ }),
Run: func(ctx context.Context, args ...string) (string, error) {
out, err := exec.CommandContext(ctx, args[0], args[1:]...).CombinedOutput()
return string(out), err
diff --git a/internal/instancectl/stoppolicy.go b/internal/instancectl/stoppolicy.go
new file mode 100644
index 000000000..a01d074d0
--- /dev/null
+++ b/internal/instancectl/stoppolicy.go
@@ -0,0 +1,67 @@
+package instancectl
+
+import (
+ "path/filepath"
+ "strings"
+)
+
+// The stop-policy gate (#528, Paul's ruling A: refuse up front). A unit's
+// stop policy is its KillMode= plus the trampoline's InitStopEnv, and the
+// two must match the trampoline that started it: a forwarding trampoline
+// under control-group gives the tenant two SIGTERMs, a direct one under
+// mixed gives it none. systemd reads KillMode= at stop time from the unit
+// as last reloaded, so an install that changes a template's policy pins,
+// before its reload, each running unit of that template to the policy it
+// started with: a runtime drop-in named StopPolicyPinName. The pin goes
+// only when instance-control next starts that unit (PinAwareSystemctl),
+// so the new policy takes effect for an instance only after it has
+// stopped under the one it started with. One lock (LockStopPolicy) keeps
+// every start out of the installer's window, from its binary swap to its
+// reload.
+
+// StopPolicyPinName is the pin's file name in a unit's runtime drop-in
+// directory. It sorts after every other drop-in, so it wins.
+const StopPolicyPinName = "99-carlos-stop-pin.conf"
+
+// StopPolicyLockPath is the gate's lock under the platform's opt dir.
+func StopPolicyLockPath(optDir string) string {
+ return filepath.Join(optDir, "system", "stop-policy.lock")
+}
+
+// StopPolicyPin is a pin's text: the KillMode= a unit started under and
+// whether its trampoline was told the stop reaches the tenant directly.
+func StopPolicyPin(killMode string, initStop bool) []byte {
+ env := "UnsetEnvironment=" + InitStopEnv
+ if initStop {
+ env = "Environment=" + InitStopEnv + "=" + InitStopCgroup
+ }
+ return []byte("[Service]\nKillMode=" + killMode + "\n" + env + "\n")
+}
+
+// StopPolicyOf reads a stop policy from unit text or from `systemctl show
+// -p KillMode -p Environment` output: the last KillMode= (systemd's
+// default, control-group, when there is none) and whether InitStopEnv is
+// set to InitStopCgroup.
+func StopPolicyOf(text string) (killMode string, initStop bool) {
+ killMode = "control-group"
+ for _, line := range strings.Split(text, "\n") {
+ line = strings.TrimSpace(line)
+ switch {
+ case strings.HasPrefix(line, "KillMode="):
+ killMode = strings.TrimPrefix(line, "KillMode=")
+ case strings.HasPrefix(line, "Environment="):
+ for _, kv := range strings.Fields(strings.TrimPrefix(line, "Environment=")) {
+ if kv == InitStopEnv+"="+InitStopCgroup {
+ initStop = true
+ }
+ }
+ case strings.HasPrefix(line, "UnsetEnvironment="):
+ for _, k := range strings.Fields(strings.TrimPrefix(line, "UnsetEnvironment=")) {
+ if k == InitStopEnv || strings.HasPrefix(k, InitStopEnv+"=") {
+ initStop = false
+ }
+ }
+ }
+ }
+ return killMode, initStop
+}
diff --git a/internal/instancectl/stoppolicy_linux.go b/internal/instancectl/stoppolicy_linux.go
new file mode 100644
index 000000000..37fc82e20
--- /dev/null
+++ b/internal/instancectl/stoppolicy_linux.go
@@ -0,0 +1,77 @@
+//go:build linux
+
+package instancectl
+
+import (
+ "context"
+ "errors"
+ "io/fs"
+ "os"
+ "path/filepath"
+ "strings"
+
+ "golang.org/x/sys/unix"
+)
+
+// LockStopPolicy takes the stop-policy lock, exclusive for an installer
+// and shared for a start, and returns its release. It blocks.
+func LockStopPolicy(path string, exclusive bool) (func(), error) {
+ if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
+ return nil, err
+ }
+ f, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|unix.O_CLOEXEC|unix.O_NOFOLLOW, 0o600)
+ if err != nil {
+ return nil, err
+ }
+ how := unix.LOCK_SH
+ if exclusive {
+ how = unix.LOCK_EX
+ }
+ for {
+ err = unix.Flock(int(f.Fd()), how)
+ if !errors.Is(err, unix.EINTR) {
+ break
+ }
+ }
+ if err != nil {
+ _ = f.Close()
+ return nil, err
+ }
+ return func() { _ = unix.Flock(int(f.Fd()), unix.LOCK_UN); _ = f.Close() }, nil
+}
+
+// PinAwareSystemctl wraps instance-control's systemctl. A start holds the
+// shared stop-policy lock, removes the named units' pins from pinDir and,
+// if it removed any, reloads before it starts; every other verb passes
+// straight through.
+func PinAwareSystemctl(lockPath, pinDir string, run func(context.Context, ...string) (string, error)) func(context.Context, ...string) (string, error) {
+ return func(ctx context.Context, args ...string) (string, error) {
+ if len(args) == 0 || args[0] != "start" {
+ return run(ctx, args...)
+ }
+ unlock, err := LockStopPolicy(lockPath, false)
+ if err != nil {
+ return "", err
+ }
+ defer unlock()
+ removed := false
+ for _, unit := range args[1:] {
+ if strings.HasPrefix(unit, "-") || strings.ContainsAny(unit, "/\x00") || !strings.HasSuffix(unit, ".service") {
+ continue
+ }
+ err := os.Remove(filepath.Join(pinDir, unit+".d", StopPolicyPinName))
+ switch {
+ case err == nil:
+ removed = true
+ case !errors.Is(err, fs.ErrNotExist):
+ return "", err
+ }
+ }
+ if removed {
+ if out, err := run(ctx, "daemon-reload"); err != nil {
+ return out, err
+ }
+ }
+ return run(ctx, args...)
+ }
+}
diff --git a/internal/instancectl/stoppolicy_linux_test.go b/internal/instancectl/stoppolicy_linux_test.go
new file mode 100644
index 000000000..36a9834fe
--- /dev/null
+++ b/internal/instancectl/stoppolicy_linux_test.go
@@ -0,0 +1,104 @@
+//go:build linux
+
+package instancectl
+
+import (
+ "context"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+ "time"
+)
+
+// A start clears its own unit's stop-policy pin and reloads before it
+// starts, so the unit runs the template's policy; a start with no pin
+// costs no reload (#528, ruling A).
+func TestPinAwareStartClearsItsPin(t *testing.T) {
+ dir := t.TempDir()
+ lock := filepath.Join(dir, "lock")
+ unit := "carlos-instance@shop.service"
+ pin := filepath.Join(dir, unit+".d", StopPolicyPinName)
+ if err := os.MkdirAll(filepath.Dir(pin), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ other := filepath.Join(dir, "carlos-instance@other.service.d", StopPolicyPinName)
+ if err := os.MkdirAll(filepath.Dir(other), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ for _, p := range []string{pin, other} {
+ if err := os.WriteFile(p, StopPolicyPin("mixed", false), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ }
+ var calls []string
+ run := PinAwareSystemctl(lock, dir, func(_ context.Context, args ...string) (string, error) {
+ if args[0] == "start" {
+ if _, err := os.Stat(pin); !os.IsNotExist(err) {
+ t.Errorf("start ran with the pin still there: %v", err)
+ }
+ }
+ calls = append(calls, strings.Join(args, " "))
+ return "", nil
+ })
+ if _, err := run(t.Context(), "start", unit); err != nil {
+ t.Fatal(err)
+ }
+ if got := strings.Join(calls, "; "); got != "daemon-reload; start "+unit {
+ t.Fatalf("calls %q", got)
+ }
+ if _, err := os.Stat(other); err != nil {
+ t.Fatalf("another unit's pin went: %v", err)
+ }
+ calls = nil
+ if _, err := run(t.Context(), "start", "--no-block", unit); err != nil {
+ t.Fatal(err)
+ }
+ if got := strings.Join(calls, "; "); got != "start --no-block "+unit {
+ t.Fatalf("a start with no pin: calls %q", got)
+ }
+ calls = nil
+ if _, err := run(t.Context(), "stop", "carlos-instance@other.service"); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := os.Stat(other); err != nil || len(calls) != 1 {
+ t.Fatalf("a stop touched the pin or reloaded: %v %q", err, calls)
+ }
+}
+
+// A start waits while an installer holds the stop-policy lock: no unit
+// starts between an install's pins and its reload (#528, ruling A).
+func TestPinAwareStartWaitsForTheInstaller(t *testing.T) {
+ dir := t.TempDir()
+ lock := filepath.Join(dir, "sub", "lock")
+ unlock, err := LockStopPolicy(lock, true)
+ if err != nil {
+ t.Fatal(err)
+ }
+ started := make(chan struct{})
+ run := PinAwareSystemctl(lock, dir, func(_ context.Context, args ...string) (string, error) {
+ close(started)
+ return "", nil
+ })
+ go func() { _, _ = run(context.Background(), "start", "carlos-instance@shop.service") }()
+ select {
+ case <-started:
+ t.Fatal("start ran while the installer held the lock")
+ case <-time.After(200 * time.Millisecond):
+ }
+ unlock()
+ select {
+ case <-started:
+ case <-time.After(5 * time.Second):
+ t.Fatal("start never ran after the installer let go")
+ }
+}
+
+func TestStopPolicyPinText(t *testing.T) {
+ if got := string(StopPolicyPin("mixed", false)); got != "[Service]\nKillMode=mixed\nUnsetEnvironment="+InitStopEnv+"\n" {
+ t.Errorf("old policy pin %q", got)
+ }
+ if got := string(StopPolicyPin("control-group", true)); got != "[Service]\nKillMode=control-group\nEnvironment="+InitStopEnv+"="+InitStopCgroup+"\n" {
+ t.Errorf("new policy pin %q", got)
+ }
+}
diff --git a/internal/instancectl/stoppolicy_other.go b/internal/instancectl/stoppolicy_other.go
new file mode 100644
index 000000000..6bae212ba
--- /dev/null
+++ b/internal/instancectl/stoppolicy_other.go
@@ -0,0 +1,13 @@
+//go:build !linux
+
+package instancectl
+
+import "context"
+
+// LockStopPolicy holds nothing off Linux, where no instance unit runs.
+func LockStopPolicy(string, bool) (func(), error) { return func() {}, nil }
+
+// PinAwareSystemctl is run itself off Linux.
+func PinAwareSystemctl(_, _ string, run func(context.Context, ...string) (string, error)) func(context.Context, ...string) (string, error) {
+ return run
+}