carlos / platform Public

Merge remote-tracking branch 'origin/main' into cli-registry-words

claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 8596404c3e8f97a0c45a1ae2e9213f579bfad2e8 parent 7ef0157parent 197cc40
43 files changed, +1,914 −74
  • docs/superpowers/notes/census-proposal-demo-slice-adopt.md +26 −0
  • docs/superpowers/notes/census-proposal-deploy-edge-718.md +11 −0
  • docs/superpowers/notes/census-proposal-security-review-mitigations.md +28 −0
  • docs/superpowers/reviews/CODEX-REVIEW-BRIEF-deploy-edge-718.md +56 −0
  • docs/superpowers/reviews/REVIEW-BRIEF-security-review-mitigations.md +45 −0
  • go.mod +7 −7
  • go.sum +14 −0
  • internal/activator/backend_exec.go +40 −0
  • internal/activator/hawake_test.go +28 −1
  • internal/activator/resident_layout_converge_linux_test.go +95 −0
  • internal/activator/resident_layout_test.go +318 −0
  • internal/activator/stateless_test.go +1 −0
  • internal/console/apicli.go +5 −5
  • internal/console/apigatepass.go +1 −1
  • internal/console/deployscope.go +3 −2
  • internal/console/deployscope_test.go +84 −1
  • internal/console/securityheaders.go +13 −0
  • internal/console/securityheaders_test.go +55 −0
  • internal/console/server.go +1 −0
  • internal/demobuild/budget.go +143 −0
  • internal/demobuild/budget_rootrunner_linux_test.go +146 −0
  • internal/demobuild/budget_test.go +190 −0
  • internal/demobuild/worker.go +34 −8
  • internal/demobuild/worker_test.go +2 −2
  • internal/host/agent.go +3 −0
  • internal/host/agent_layout_test.go +59 −11
  • internal/host/demo_slice_adopt_linux_test.go +172 −0
  • internal/host/group_names_test.go +7 −6
  • internal/host/layoutleg.go +41 −13
  • internal/host/rootfs_advice_test.go +6 −4
  • internal/host/runsc_update_dirs_linux_test.go +4 −0
  • internal/host/systemunits.go +58 −2
  • internal/host/systemunits_test.go +5 −3
  • internal/moves/archive/zstd_malformed_test.go +57 −0
  • internal/provision/reconcile.go +6 −2
  • internal/provision/replicas_test.go +33 −0
  • internal/provision/testdata/plan14-root-reads-chain.tsv +3 −0
  • internal/provision/testdata/plan14-root-reads-demo-slice-adopt.tsv +13 −0
  • internal/provision/testdata/plan14-root-reads-deploy-edge-718.tsv +3 −0
  • internal/provision/testdata/plan14-root-reads-security-review-mitigations.tsv +15 −0
  • internal/rootfsimage/zstd_malformed_test.go +42 −0
  • pipeline.go +1 −6
  • pipeline_test.go +40 −0
diff --git a/docs/superpowers/notes/census-proposal-demo-slice-adopt.md b/docs/superpowers/notes/census-proposal-demo-slice-adopt.md
new file mode 100644
index 000000000..479b6729c
--- /dev/null
+++ b/docs/superpowers/notes/census-proposal-demo-slice-adopt.md
@@ -0,0 +1,26 @@
+# Census approval: demo-slice-adopt
+
+Ruling `census-ruling-demo-slice-adopt`. The independent reviewer approves or rejects every change below, 2 with a new disposition; nothing goes to the census owner (Paul, #280, 2026-10-26).
+
+| unit | change | read sites | what changed |
+|---|---|---|---|
+| `internal/demobuild/worker.go` `Worker.Build` | body | unchanged (1) | Before admission, call the admit hook (nil = reconcileBudget); a pending budget change (errBudgetPending) is retried every 2 s until the job deadline, any other error fails at once. reconcileBudget reads the fixed build slice's systemctl show budget, its cgroup limit files and cgroup.events under the fixed root cgroup path, and list-jobs (a listing at the capture limit defers); only with buildPurge held exclusively, the slice empty and no build or slice job queued does it run systemctl stop on the fixed slice name. No tenant, app or agent input names a path or unit. |
+| `internal/host/systemunits.go` `ensureSystemUnitsWithGuard` | sites | +file:ReadFile ×2 | Compare the installed carlos-demo-builds.slice (fixed root unit path, embedded unit) with its host.env rendering, and ask systemd for the slice's loaded MemoryMax/TasksMax (systemctl show on the fixed name). A definite difference is a reinstall (existing write loop + daemon-reload). No live budget change, no new path, input or write target. |
+
+Envelopes re-pinned: `internal/demobuild`, `internal/host`.
+
+Review: a model from the other family than the author reads the branch's diff against main on the amadan.net remote (`origin` or `amadan`, whichever points at amadan.net) and gives a verdict for every unit and every re-pinned envelope above. For a unit, compare the change with its recorded disposition and basis below; for an envelope, read every changed function in the package and what it reaches. Reject if the change lets root open, run, query or follow anything it did not before from a path or input a tenant, an app or a box agent can create, write or name; if it weakens a check, refusal, validation, argument or environment the basis relies on; or if the diff cannot settle either. Otherwise approve. Record each verdict on #280 with the tip. A rejected unit goes back to the author to correct; nothing escalates to the census owner.
+
+Recorded dispositions, which each change must still satisfy:
+
+- `internal/demobuild/worker.go` `Worker.Build`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-agent-start-demo-1;basis=Holds the build/purge read lock through cleanup; existing bounded source read remains.
+- `internal/host/systemunits.go` `ensureSystemUnitsWithGuard`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-region-ha-p3b;basis=Move unit-repair body here with existing lock/unit/host.env reads; under lock require operator repair permit on groups before writes and each systemctl effect, preserve root masks/drop-in and omit automatic update/recovery units. New indirect protected marker/permit reads, never agent receipt; fixed repair unchanged.;rev3=census-ruling-gvisor-demos;basis=Create runtime/rootfs directories and repair installer plus three measured workload templates without arming them. Existing unit/host.env reads unchanged.;rev3=census-ruling-gvisor-update-dirs;basis=Create the two live sandbox directories (the same fixed ensureSandboxDirectories paths) before the apply lock and the early returns on non-group boxes; group members still create them only after the maintenance permit. A creation error still ends the pass at the original point. Then call refreshControlSandboxRootfs. No new path, input or systemctl verb beyond the try-restart below.
+
+New dispositions, which census-propose wrote and the reviewer checks against the unit's reads and the diff:
+
+- new `internal/demobuild/budget.go:budgetSlicePopulated`: reads +file:ReadFile; written legacy, accepted-legacy, frozen
+- new `internal/demobuild/budget.go:kernelBudgetMatches`: reads +file:Lstat, +file:ReadFile; written legacy, accepted-legacy, frozen
+
+Seal: `250e3ba91e1bc5fcd6be5cc2bafce4c7d6645d2d2f0c080913b99f01b1d19129` → `707018faaa1fee3b47abb78389ae7854264e76621cc316889061adb69bf13e10`.
+
+Overlay: `internal/provision/testdata/plan14-root-reads-demo-slice-adopt.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`.
diff --git a/docs/superpowers/notes/census-proposal-deploy-edge-718.md b/docs/superpowers/notes/census-proposal-deploy-edge-718.md
new file mode 100644
index 000000000..41f341bbf
--- /dev/null
+++ b/docs/superpowers/notes/census-proposal-deploy-edge-718.md
@@ -0,0 +1,11 @@
+# Census approval: deploy-edge-718
+
+Ruling `census-ruling-deploy-edge-718`. The independent reviewer approves or rejects every change below, 0 with a new disposition; nothing goes to the census owner (Paul, #280, 2026-10-26).
+
+Envelopes re-pinned: `.`.
+
+Review: a model from the other family than the author reads the branch's diff against main on the amadan.net remote (`origin` or `amadan`, whichever points at amadan.net) and gives a verdict for every unit and every re-pinned envelope above. For a unit, compare the change with its recorded disposition and basis below; for an envelope, read every changed function in the package and what it reaches. Reject if the change lets root open, run, query or follow anything it did not before from a path or input a tenant, an app or a box agent can create, write or name; if it weakens a check, refusal, validation, argument or environment the basis relies on; or if the diff cannot settle either. Otherwise approve. Record each verdict on #280 with the tip. A rejected unit goes back to the author to correct; nothing escalates to the census owner.
+
+Seal: `250e3ba91e1bc5fcd6be5cc2bafce4c7d6645d2d2f0c080913b99f01b1d19129` → `250e3ba91e1bc5fcd6be5cc2bafce4c7d6645d2d2f0c080913b99f01b1d19129`.
+
+Overlay: `internal/provision/testdata/plan14-root-reads-deploy-edge-718.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`.
diff --git a/docs/superpowers/notes/census-proposal-security-review-mitigations.md b/docs/superpowers/notes/census-proposal-security-review-mitigations.md
new file mode 100644
index 000000000..4dc8d1814
--- /dev/null
+++ b/docs/superpowers/notes/census-proposal-security-review-mitigations.md
@@ -0,0 +1,28 @@
+# Census approval: security-review-mitigations
+
+Ruling `census-ruling-security-review-mitigations`. The independent reviewer approves or rejects every change below, 2 with a new disposition; nothing goes to the census owner (Paul, #280, 2026-10-26).
+
+| unit | change | read sites | what changed |
+|---|---|---|---|
+| `internal/host/agent.go` `runAgent` | body | unchanged (9) | Wire the cached operator flat-layout choice into the exec backend's new-resident refusal; no read source added, existing authority retained. |
+| `internal/host/layoutleg.go` `mintLayoutIntentWith` | body | unchanged (1) | Mint nested on nested-default, activator-armed, floor-capable boxes while isolation readiness is pending; wake still gates on readiness. Explicit flat and incapable-box compatibility unchanged; same intent/env/registry sources. |
+| `internal/activator/backend_exec.go` `ExecBackend.spawnChildFrom` | sites | +whole:Route | Enforce the unchanged never-served resident refusal once at the shared flat/foreign primary binary spawn sink, before placement, live-link/token/env/control preparation or execution. Covers plain, generation and staged Service wakes; existing served/explicit-flat exemptions and other gates retained. No new filesystem/store source. |
+
+Envelopes re-pinned: `.`, `internal/activator`, `internal/host`, `internal/provision`.
+
+Review: a model from the other family than the author reads the branch's diff against main on the amadan.net remote (`origin` or `amadan`, whichever points at amadan.net) and gives a verdict for every unit and every re-pinned envelope above. For a unit, compare the change with its recorded disposition and basis below; for an envelope, read every changed function in the package and what it reaches. Reject if the change lets root open, run, query or follow anything it did not before from a path or input a tenant, an app or a box agent can create, write or name; if it weakens a check, refusal, validation, argument or environment the basis relies on; or if the diff cannot settle either. Otherwise approve. Record each verdict on #280 with the tip. A rejected unit goes back to the author to correct; nothing escalates to the census owner.
+
+Recorded dispositions, which each change must still satisfy:
+
+- `internal/host/agent.go` `runAgent`: authority, task B,C,D,F. Basis: rev3=census-ruling-self-serve-moves-1;basis=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): builds the box's lifetime judge once (newBoxJudge, nil with host claims on) and hands it to the seed placement, the moves and runs workers and every loop it starts; read sites unchanged, offsets moved; B,C,D,F authority retained; self-serve moves 1 Task 8: derives the box's lifetimes switch from the judge once (lifetimes := boxJudge != nil) and hands it to the edges file loop; read sites unchanged, offsets moved;rev3=census-ruling-plans-4d-lapse;basis=arms two more plans hooks from the same snapshot: e.SetPlanDisabledFor(planDisabledFor) beside SetPlanGovernedFor, and svc.SetDisabledFor(planDisabledRoute) beside SetMaxRunFor (plans 4d); the reads live in those units (plans-4d-units decision); read sites unchanged, offsets moved;rev3=census-ruling-rootfs-apps-2;basis=main's body as of the merge of origin/main 9b81d97b (with main's plan rate ceiling, edge request records, regional box names, self-serve moves plan 1, plans 4d-1 lapse and its other later changes under main's own census rulings) plus the rootfs placement wiring in the activator start: an agentRootfs built from eb.NestedOK, CARLOS_DEPLOYMENT_SINGLE_TENANT, CARLOS_POOLS, the claim flag, swapArming's answer, the control client's /ready/rootfs and, on a fleet box whose identity resolved, fleetOwnerCheck over the deploy store main already opens for the fleet label (fleetStore), then arm and armedRootfs.Store; this body reads nothing new itself; the closures it wires read later, at a rootfs wake and each status tick: GET /ready/rootfs over the control socket, NestedOK's checks, and release.FleetOwnerKey for the judged row's own account and this box's fleet from the deploy store;rev3=census-ruling-instance-egress-sizes-328-329;basis=#328 plan 2 Tasks 7 and 11, #329 plan 3 Task 7 and plan 1 Task 7's policy cache: the control client is built once and handed to eb.Control, to the status tick (egressStatus) and to a new egressNudgeLoop goroutine; armSizeSource(svc, "/sys/fs/cgroup") after the activator Service; armPolicyCache() after armChangeIndex; statusLoop takes egressStatus. The reads are those units' own (decision rows); this body reads nothing new: the same five sites, offsets moved, in the agent; B,C,D,F authority retained.;rev3=census-ruling-remote-instance-metrics;basis=builds the metrics loop's owners closure (metricsOwners over the agent's registry, the activator and cgm.Leftover) when an activator exists and hands it to metricsLoop; reads nothing new itself;rev3=census-ruling-edge-asset-cache-3;basis=adds file:Statfs. runAgent keeps its authority (B,C,D,F). The new site is assetcache.Statfs, an exported assetcache.FS interface value (var Statfs FS = statfsFS{}), not a function value and not a call in runAgent: the ready hook passes it to armEdgeAssetCache as the store's filesystem, and armEdgeAssetCache calls its Space method on the configured data directory (dataDir(): $CARLOS_DATA_DIR, else /data), which calls unix.Statfs there (statfsFS.Space, accepted legacy at census-ruling-edge-asset-cache-2). No request-supplied pathname reaches it.;rev3=census-ruling-remote-metrics-nested;basis=main's body (merged origin/main acfa4f80, under main's own census rulings) plus: snapshots the nested layout (snapshotNestedUnits over /sys/fs/cgroup/carlos.slice/carlos-instances.slice) once at start, before the activator, and hands the metrics loop a unitSources struct (stamped units, routeHostNames, that root and the snapshot); reads nothing new itself;rev3=census-ruling-region-ha-p1a;basis=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): wires region HA P1a into the activator: cfg.Record = haRecordFacts(openDeployStore, boxJudge) (the box's lifetime judge this body already builds with newBoxJudge, nil with host claims on; CI fix) and cfg.Self = lease.CurrentSelf; eb.Lifetimes (the process's lifetime index), eb.Registry, eb.StartupSwept (seedSweptAtStart.Load), eb.FilesStore from newProductionFilesStore (now lease.NewFilesStore, rootaws-loaded, a log line on failure) and lease.SetObligationDir(<data>/.ha-owed) (logged on failure; HA acquires then refuse); this body reads nothing new itself, the same five sites; the reads are those units' own (haRecordFacts and lease's SetObligationDir are new rows on this card); merge of origin/main d7ae1d76: main's own later changes to this body are kept as main has them, under main's rulings (census-ruling-remote-instance-metrics: the metricsOwners closure for metricsLoop; census-ruling-edge-asset-cache-3: the +file:Statfs site, assetcache.Statfs handed to the asset ready hook); this branch's change is the same as above;rev3=census-ruling-region-ha-p1b1;basis=region HA P1b-1: builds one termfence.Confirmer (Self from lease.CurrentSelf at each call, EC2 DescribeInstances method only, client from rootaws.LoadDefaultConfig with retries off, built lazily on first use) and sets eb.OwnerTerminated; this body reads nothing new itself, the same six sites;rev3=census-ruling-rootfs-apps-3;basis=rootfs Plan 3 Task 7: the startup Sweep literal hands its answer to startupSwept, which logs as before and, only on a clean sweep, marks rootfs admission swept (MarkRootfsSwept); same Sweep call, no read added;rev3=census-ruling-managed-fleets-1b;basis=managed fleets 1b (controller ruling after branch review R1, and Paul's R2 ruling): sets svc.Fleet = fleetWakeFor(os.Getenv, identity, identErr, fleetStore) from the identity it already resolves once and the deployment store the fleet loops already opened, and logs an ERROR naming the identity error when the box is on a fleet with an invalid identity. fleetWakeFor reads CARLOS_REGION and CARLOS_FLEET from the same environment. Read sites unchanged (6). Agent, not root; a platform box is unchanged.;rev3=census-ruling-rootfs-apps-6;basis=rootfs Plan 6 Task 12: one call more beside armRunsPass, armInteractivePass(svc, reg, rolloutSink, boxJudge), in the same activator Configure hook, handing it the same box judge; fix round 1 (Astra P2, shutdown): after svc.Shutdown(ctx), shutdownInteractive(ctx) ends and joins every interactive session under the same shutdown budget; the worker's own reads are its units' (interactive.go); this body reads nothing new, the same six sites; merge of origin/main 6f1f6ca6: main's svc.Fleet = fleetWakeFor(...) and its invalid-identity ERROR line are kept as main has them (census-ruling-managed-fleets-1b); this branch's change is the same as above; read sites unchanged (6);rev3=census-ruling-fix-set-aside-exdev;basis=set-aside EXDEV fix: one field more on the agent ExecBackend literal, RawInstanceDir: layout.RawInstanceDir (a pure path join: <dataDir>/.instances/<InstanceID(host)>), so the start rule set-aside moves a copy out through the raw directory instead of through the nosymfollow bind; this body reads nothing new, the same six sites;rev3=census-ruling-durability-3a-escrow;basis=durability 3a Task 3: one more assignment beside eb.FilesStore: eb.EscrowKey = haEscrowKey(os.Getenv("CARLOS_SECRETS_KEY")), the agent's own environment parsed by appconfig.ParsePrivateKey as the moves pass parses it (unset or unparseable: a log line and nil, and HA publication refuses on the box). No path is opened or read, no read site added; the same six sites, offsets moved; B,C,D,F authority retained. Durability 3a Task 4: one more goroutine beside configSyncLoop: go escrowLoop(agentCtx, reg, svc), the escrow sweep every 30 s over the same registry and Service. This body reads nothing new itself; the same six sites, offsets moved; B,C,D,F authority retained. Durability 3a Task 5: one more call beside eb.EscrowKey: wireRawSecretPages(eb, PageOperator, metricsBoxLabel(os.Getenv, readMachineID())), which sets eb.OnRawSecret to page an operator (alerting.Page through PageOperator, LevelIncident) on its own goroutine with a 20 s timeout; metricsBoxLabel and readMachineID are the reads this body already makes for the moves refusal log; no new read site; the same six sites, offsets moved; B,C,D,F authority retained. Merge of origin/main 90c4d3aa: main's own later changes to this body are kept as main has them, under main's rulings; this branch's change is the same as above. Merge of origin/main 00bf5b8c (fleet set-aside EXDEV fix): main's change to this body is kept as main has it, under its own census ruling; this branch's change is unchanged.;rev3=census-ruling-probe-burst-limit;basis=two more sink wirings beside setAnalyticsSink: setProtectionSink(e.SetProtectionRecordOnly) and setAssetOwnersSource(e.AssetOwners), function values the telemetry pass calls; this body reads nothing new, the same six sites; authority B,C,D,F retained; no new root read or write kind;rev3=census-ruling-region-ha-p1b3a;basis=Arm HA placement exactly once on the existing Service before activatorStart and edges publication, wiring AwakeApps and the PageOperator callback; existing six read sites unchanged, no new root authority.;rev3=census-ruling-stateless-replicas-1;basis=Final review I3: start the concrete coordinator's renewal worker with agent setup; existing closeReplicaCoordinator shutdown cancels and joins it before release. No new read sites or credentials. Merge origin/main c59715e7: retain main's armHAPlacement(svc, PageOperator) wiring beside the existing activator setup; stateless coordinator and shutdown wiring remain. Same read sites; no new root read or credential.;rev3=census-ruling-edge-held-streams;basis=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): in the edge-ready callback, calls act.SetHeldWakeHook(e.HeldWake) when act is non-nil (installing the non-blocking wake callback) and stores e.HeldStreamsForStatus in heldStreamsSource. Wiring of in-memory callbacks only; no read added.;rev3=census-ruling-region-ha-p1b3b-t;basis=Wire Service.SetDutyView to the live edge DutySnapshot in the ready callback. No new read; no new loop or cloud operation. B2 wires the registry as the persistent DutyStore before service startup; no new cloud or filesystem path. B3b: arm one journal-backed termination consumer before service startup using agentCtx and the shared confirmer; expose edge tick and join at edge shutdown. No new direct read sites.;rev3=census-ruling-agent-start-demo-1;basis=Passes the existing registry, data store and hibernation prefix into the demo worker, and the existing instance-control client into the demo before-exec hook. No alternate data store or polling loop. Merge resolution against origin/main 9bd45488 retains main's HA departure controller, lifecycle and duty wiring alongside the demo data store and worker; no read site added by the resolution.;rev3=census-ruling-region-ha-p3a;basis=P3a Task 3: install closed fixed admission before every launch source, bind activator/backend and edge, wire the real termination Started lifecycle and role reader after the change index; close before cancellation/child shutdown. No new external reads or cloud authority. Fix R1: move bind/lifecycle/edge-option wiring into wireAgentAdmission and worker listing into runWorkerBootPassAfterAdmission. Worker boot waits for admission before listing then uses unchanged bounded wakes and per-host serialization; whole Route read moves to the helper. No new storage, cloud, or root execution authority. Preserve merged main's agent wiring and census basis; the branch removes one whole Route use by moving worker iteration to the helper, with no added read kind.;rev3=census-ruling-stateless-replicas-2;basis=Slice 3b: arms a fleet-only worker using the existing registry, activator, backend and authenticated console transport. Owned worker stops and joins at shutdown. No new bucket reader. merge of origin/main 9b8b2c50: retain HA duty/departure lifecycle, wake-slot and existing agent wiring alongside the replica placement worker; no new read introduced by resolution. merge of origin/main 6be08467: Retain main demo configuration, admission, build and expiry wiring alongside the replica worker; merge-only body change, no additional read. merge of origin/main 7920cccf: Retain main box-role/group admission wiring and boot publication beside the owned replica worker and shutdown; main moves the boot registry List into runWorkerBootPassAfterAdmission, removing its inline whole Route site. No new read introduced by conflict resolution.;rev3=census-ruling-stateless-replicas-3;basis=Task 1 fix round 1 M3: retain the private snapshot source and cancel/join ownership, but use the replica-health-specific retry loop. It logs its first failure only and retains the existing exponential backoff capped at 30 seconds; unsupported builds return nil. Existing five direct read sites unchanged; no new credentials, bucket reader or app lifecycle action. Fix round 1 Q20: publish Edge.ReplicaSnapshots as a separate in-memory status source, leaving the tenant-visible Upstreams source unchanged. No new external reader or authority.;rev3=census-ruling-region-ha-p3b;basis=Load root-written group marker/configuration, configure signed boot binding and agent receipt completer, wire cancellable admission into departure work and expose cached GroupReaderSnapshot. New indirect boot reads use protected root files; agent-owned receipt controls duplicate initial completion only, never root restart permission. Same five direct sites. Merge 45cebde4 retains the replica health socket lifecycle and setReplicaSource beside GroupReaderSnapshot; no extra read beyond main.;rev3=census-ruling-agent-start-demo-2;basis=agent.go:309-329 opens demo-traffic.db beside the operator-configured registry when a demo domain exists, closes it at shutdown and wires drain-before-purge; :1010-1019 shares the worker and write gate; :1164-1177 installs the fleet identity and closed-until-worker serving callback. One added whole Route pass; the new indirect filesystem/SQL reads are claimed in openDemoTraffic and worker/store units. No request chooses the database pathname.;rev3=census-ruling-region-ha-p1b3b-s;basis=Wire the service duty view to authoritative cached sidecar manifest placement in LifetimeIndex and the edge sidecar projection; missing policy denies duty. Existing instance duty wiring remains.;rev3=census-ruling-region-ha-g2-t3;basis=T3a: wire eb.Page = PageOperator beside OwnerTerminated before departures arm, so suspect-holder pages work if departure setup fails; no new read; existing nine sites and authority unchanged; pages through the existing sink. T3b: publish the same backend through an atomic pointer for the metrics observer, and clear it on return; no new external read or authority.;rev3=census-ruling-agent-start-demo-3;basis=Wire the claim activator and root snapshot client into the demo worker; pass moved readiness to status reporting. Census read-site delta: unchanged (9).;rev3=census-ruling-region-ha-g2-fixes;basis=Wire local pool evidence, live withdrawal activator, startup ingress scan and alias publication, and edge lookup; no new direct sites; new indirect record/claim reads use existing store/judge paths described in ingress helpers.;rev3=census-ruling-region-ha-g2r-fixes;basis=W3: starts the existing record-view backstop loop with a departure-inventory listener (non-blocking, coalesced signal) even without an armed RecordView; it requests the existing full pass (backstopFullDue) there. Same nine read sites; no new read or authority.;rev3=census-ruling-region-ha-graceful-terminate-t2;basis=Derive one signal-time deadline with a 90-second budget; cap departure stop and startup/seed/service shutdown joins by it. No read added.;rev3=census-ruling-static-sweep-periodic;basis=in the edge-ready callback, publishes e.LargestStaticTree in staticTreeSource for the disk alert line (diskAlertFrac in the metrics loop); in-memory wiring only, no read added; read sites unchanged (9);rev3=census-ruling-edge-page-cache-1;basis=wires the exec backend's CurrentInputs into the edge cache (wireCurrentInputs) and, in the ready hook after armEdgeAssetCache (whose returned store it now keeps), calls armEdgePageCache, which does nothing unless CARLOS_PAGE_CACHE=1; read sites unchanged (9); no read added;rev3=census-ruling-gvisor-demos;basis=Capture sandbox resolution and refusal once; log errors once; gate route admission and BeforeExec before process launch. No new root read. Task 5: pass the once-captured sandbox effective mode/config error into ExecBackend, UnitBackend and the immutable Client expectation. Same startup environment/registry reads; swapArming declines gVisor before placement. Task 8: arm read-only status projection with the existing Client.SandboxStatus callback. Agent status now queries the existing root /ready endpoint; no new root authority or guest-file input. Merge2 e8a1ddde: retain main wireCurrentInputs and armEdgePageCache through the existing asset-store ready hook alongside branch once-captured sandbox mode, wake gates and root status wiring. No new direct read; main page-cache helpers retain their own census overlays.;rev3=census-ruling-region-ha-held-build;basis=wires the drain state: svc.SetDrainingSource(boxDrain.IsDraining), svc.SetPeerDrainView(e.PeerDraining), e.SetPeerDrainedHook(svc.DropHoldersNaming); in-memory only; no read added; region HA held-requests Task 5: on group members, starts the drain driver over the activator, the edge and boxDrain, and serves its root-only drain socket; no read added beyond the socket's own Branch review r1: the drain state follows the root start fence on group members (the fence reader is the existing fenceLocation.read, a root-owned fixed path); e.SetPeerUndrainedHook(svc.AllowHoldersNaming) beside the drained hook (memory only); the drain socket serves only the agent's own user. No read added.
+- `internal/host/layoutleg.go` `mintLayoutIntentWith`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=J1;basis=root-route
+- `internal/activator/backend_exec.go` `ExecBackend.spawnChildFrom`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-zddr3;basis=Census ruling zddr3: changed legacy row (comment-only change describing the shim placement); the same class as the accepted-legacy Manager.startIn and placementLive under fix1-merge-review (existing agent delegated-cgroup management remains legacy); no root decision; no registry, /data, release or claim reads. Boundary: the agent's own delegated cgroup subtree (including its scratch probe child), /proc/self, and pipes to and from its own parent, running as carlos.;rev3=census-ruling-region-ha-p1a;basis=the agent as carlos (the flat start body): the same change as seedChild: ensureAdminTokenFor(ctx, rt, paths) for the token (the same flat path), the key's producer carrying the HA mint decision, and launchEnvLayer(ctx, rt) for the env and key layer the replica gate reads; a non-HA host's token, key and env are produced and read as before; +whole:Route; only adds refusals for HA hosts;rev3=census-ruling-stateless-replicas-1;basis=Task 3a: Use the verified generation/launch mode to remove CARLOS_DB after environment merges and omit the binary --db argument where applicable. Existing runtime, layout, secrets and exec gates remain; route reads are mode projection only.;rev3=census-ruling-edge-page-cache-1;basis=the control listener is now built with the whole route (edge.ListenControl(controlSocket, rt, ...)), the +whole:Route site; it computes the launch inputs once from the build it execs by path (a staged exe's caller-named build, or the gate-resolved pinned version; "" for an unpinned live link) and fileEnv it already read, keeps them on the childProc, and for a live-link spawn publishes them to the in-memory cache (NoteProcessInputs) beside the existing purge; no new file read;rev3=census-ruling-gvisor-demos;basis=Task 5: gate launch using startup-captured mode and existing route/role/layout before preparation or execution; migrate structured root start identity and reject mismatches. Unsupported gVisor paths refuse; native behavior and existing root authority checks retained. No new root read source. Merge2 e8a1ddde: retain main build parameter, pinned live identity, launchInputs from captured build/environment, and current-process input publication. edge.ListenControl now receives the whole Route as main requires (+whole:Route); no new filesystem or storage input. Branch sandboxLaunch remains before preparation and spawn; existing direct primitive gate unchanged.
+
+New dispositions, which census-propose wrote and the reviewer checks against the unit's reads and the diff:
+
+- new `internal/activator/backend_exec.go:ExecBackend.residentLayoutRefusal`: reads +registry:GoodVersion, +registry:ServingVersion, +whole:Route; written legacy, accepted-legacy, frozen
+- reads `internal/provision/reconcile.go:RouteFor`: +registry:Stateless; keeps authority, task C,E3
+
+Seal: `707018faaa1fee3b47abb78389ae7854264e76621cc316889061adb69bf13e10` → `a6f3f9eec4aac5ea88f20d0e52eaa0651fce80c0d49b60883ff61ceade33d288`.
+
+Overlay: `internal/provision/testdata/plan14-root-reads-security-review-mitigations.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`.
diff --git a/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-deploy-edge-718.md b/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-deploy-edge-718.md
new file mode 100644
index 000000000..3f1e4f8cf
--- /dev/null
+++ b/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-deploy-edge-718.md
@@ -0,0 +1,56 @@
+# Review brief: deploy edge default, round 1 of 3
+
+Repo carlos/platform, branch `fix/deploy-edge-718`.
+Under review: the full diff from origin/main to the branch tip containing this brief.
+Authorities: discussion #718; merged specs
+`docs/superpowers/specs/2026-10-05-deploy-credential-design.md` (especially R2, R5 and section 7);
+release pipelines v2 design in platform-infrastructure at
+`platform-design/superpowers/specs/2026-08-20-release-pipelines-v2-design.md`.
+The issue's option 1 narrows the meaning of pipelined for deploy scope: the
+exact default single edge channel with no bake or rules is exempt. Everything
+else remains restricted. Explicit bake strings, including 0s, remain restricted.
+
+You are an independent Opus reviewer. Read the diff and verify against code.
+No completed review rounds yet. Sonnet investigation and Opus availability
+attempts were rejected by the provider's weekly usage limit; neither produced
+findings or constitutes a completed review. Maximum three rounds. Stop at the
+first round with no P1. Fix P2s without reopening, subject to census and review
+of newly changed security behavior. P3s are follow-ups only. Two consecutive
+rounds finding the same invariant broken require stopping for the owner's choice.
+
+## Fixed: do not re-argue
+
+- Keep apps create's signed pipeline file; absence retains the legacy ladder.
+- Keep rung scope, hotfix refusal, stable refusal and scoped signing.
+- No new CLI command, production change or new user-facing wording.
+
+## What to check
+
+1. Every early and primitive callback scope check receives the actual pipeline.
+2. Only the exact single unrestricted edge channel is exempt, including gate
+ passes. All approval rules, bake strings, other single channels, empty and
+ multiple channel configurations remain restricted. Unreadable pipeline
+ handling and rechecks before writes remain intact.
+3. The CLI uses the existing table for every nondefault configuration and
+ preserves the existing missing-pipeline display.
+4. Read the census card `docs/superpowers/notes/census-proposal-deploy-edge-718.md`
+ and approve or reject every entry and envelope with file:line evidence.
+ No new root reads are intended. The root package envelope changes because
+ runPipelineShow's display condition changes.
+5. Tests cover grant scope, protected configurations, promote, rollback and
+ signed grants. Consider authorization races and the accepted R5 gap.
+
+## Severity
+
+- P1: unsafe, would not compile, a test fails, or would not work. Blocks merge.
+- P2: wrong or missing. Fix without another round; census and newly changed
+ security behavior still need checking.
+- P3: clarity or polish. Record as follow-up, never start another round.
+
+Each finding states scenario, verified file:line evidence, concrete fix and
+invariant or trust boundary (fault family). Do not raise P2 to P1 to keep review open.
+End with exactly one verdict: READY (no P1/P2), READY AFTER FIXES (P2 only),
+or NOT READY (P1 present). Round 3 NOT READY also names whether a shared cause
+can be removed by refusing the case or cutting the feature.
+
+Do not edit files, spawn reviewers or subagents, or run full test suites.
diff --git a/docs/superpowers/reviews/REVIEW-BRIEF-security-review-mitigations.md b/docs/superpowers/reviews/REVIEW-BRIEF-security-review-mitigations.md
new file mode 100644
index 000000000..15f767bbf
--- /dev/null
+++ b/docs/superpowers/reviews/REVIEW-BRIEF-security-review-mitigations.md
@@ -0,0 +1,45 @@
+# Security mitigation implementation review
+
+Repo carlos/platform, branch `security-review-mitigations`. Base: fd6d39ec471637ddb460ea7b05bb971d95c476a5 (amadan main at branch creation). Review the committed branch diff against that base and the exact tip supplied by the author.
+
+Original system audit: GLM 5.3 and Mistral Large 4, round 1, no P1; no broad audit reopened. This is the first implementation/security check for the P2 fixes, inside the stopping-rule budget. No earlier implementation findings. Maximum three rounds total; stop at the first no-P1 round, apply P2 without reopening broad review, carry P3 as follow-up. The same fault family in two rounds stops fixes and requires Paul's choice.
+
+Fixed user ruling: legacy flat tenants are Paul's trusted apps. Do not demand migration or UID redesign for those tenants. New-tenant layout policy and gVisor rollout are investigated separately; this diff does not claim to enforce that policy or deploy production changes. Static-site security headers are an unsupported product capability, tracked in discussion #771; no carloku-specific edge workaround.
+
+Review:
+- go.mod/go.sum update compress to v1.20.2 and x/net to v0.62.0, including only required transitive minimums. Check compatibility with platform/root paths.
+- Malformed zstd regression tests traverse archive Extract/Verify and rootfsimage OpenLayout. The malformed frame must actually reach the decoder: tests were watched panic on v1.18.0 and pass on v1.20.2. Inspect the framing, cleanup assertions and input validation.
+- Console headers before redirect/admission: CSP frame-ancestors none, object-src none, base-uri self; XFO DENY; nosniff; strict-origin-when-cross-origin; host-only HSTS max-age 86400 only for an HTTPS configured origin. No default/script-src restriction, no includeSubDomains/preload, no tenant-edge policy, no version-header removal. Check legitimate console flows and response variants, including TLS termination and plain HTTP development. Security headers must not reorder authentication, CSRF, owner or freshness gates.
+- Scope: production edits are console-only plus dependency versions; root consumer tests added. Check root-read census output supplied by author; every newly changed root/security/storage behavior needs this independent approval.
+
+P1: unsafe/broken, with failure scenario and verified file:line. P2: wrong/missing, fix without restarting review. P3: polish, follow-up only. Name invariant/trust boundary (fault family) per finding. Do not inflate severity to keep review open.
+
+Return ranked findings with concrete fix and checked evidence, then exactly READY (no P1/P2), READY AFTER FIXES (no P1), or NOT READY (P1). This is code review, not deployment approval. Do not edit, spawn agents, access production, or run full tests. At most 35 read/search operations.
+
+## Final implementation and census check (round 3 of 3 total)
+
+History is not reset: round 1 was the coordinated GLM/Mistral system audit (no P1); round 2 comprised the bounded Opus implementation check of dependencies/console headers (READY, four P3s) and the targeted layout-policy check (P1: new binary residents start flat despite nested intent; P2: readiness implicitly downgrades new mints). This is the first layout fix. Check the new root/security behavior and complete census, without reopening the original broad audit or the already approved dependency/header scope. No fourth round without Paul. If the new layout fix produces another P1 in the same isolation fault family, stop further fixes and give the three choices in AGENTS.md.
+
+Additional changes: replica assignments projected Stateless are minted nested on nested deployments; floor-capable activator-armed nested-default boxes mint nested while readiness is pending and the existing wake gate still refuses; a never-served stateless binary resident at flat/foreign paths refuses launch unless flat was explicitly chosen. Existing served/good-version residents, hibernating rows, explicit flat choices and external routes retain their prior behavior. No gVisor rollout change. The new refusal reuses ErrFenced without new user copy.
+
+Inspect all production call paths (Start, generation/staged start, resident migration), source of ServingVersion/GoodVersion exemptions, and timing/source of FlatLayoutChosen. Validate that ordinary member-created copies cannot use an unguarded route or a premature served marker, and that explicit flat and trusted legacy remain operable. Review the full named census proposal in docs/superpowers/notes/census-proposal-security-review-mitigations.md, overlay and chain; give an explicit verdict for every changed/new unit and all four envelopes, including the helpers covered by envelopes.
+
+P3 follow-up list from round 2 (not reopened): PDF interim-response filtering can lose default headers; add route-specific header-precedence coverage; strengthen decoder-error/spool-cleanup assertions; expand ServeHTTP's doc comment. The malformed decoder tests were watched fail on old compress and pass on the update. Parent validation of the full changed set uses short disk TMPDIR to avoid fixture socket-length limits. A pre-existing rootfs-worker temp cleanup race is tracked separately; do not misreport a failed run as green.
+
+## Authorized fourth review: central guard and final census
+
+Paul explicitly selected “Central guard + one fourth review (Recommended)” after the R3 failure and budget stop were explained. This authorizes exactly one fourth Opus review, not a fifth or a new broad audit. R3 is NOT READY: the two wrapper checks missed Service.doWake -> doStatelessWake -> startPinnedAt -> SplitBackend.StartStaged -> ExecBackend.StartStaged -> spawnChildFrom. Its individual census approvals did not clear that P1. Blocker and approval are recorded in discussion #773; R3 census verdict is recorded on #280.
+
+The fix now calls the same predicate only in spawnChildFrom, after pathsFor and before placement/live-link/token/env/control preparation or exec. Start/startGenFrom duplicate checks are removed. No predicate, legacy exemption, gVisor gate or ErrFenced copy change. New regression uses real release.Pass to seed stateless on a flat row and the Service resident tick, through SplitBackend into real ExecBackend.StartStaged; it checks the captured ErrFenced, no process/entry and no launch artifacts. It was watched fail before the move and pass after. Direct staged flat/foreign, served/good-version and explicit-flat cases are also covered. An existing argument-projection test now explicitly chooses flat instead of relying on an unset callback.
+
+Merged main is b1bf1e02ba6c3071456a53912b491ab86b9a819d; final diff supplied by author is against that merged base. Root census has been regenerated over it. Name-class census fingerprint for RouteFor is updated: only local path layout changes, exact names/owners remain unchanged; no new name class.
+
+CI of the previous tip also exposed independent test-fixture state carry-over. haBackendEmptyIndex now resets the pending obligation set for its fresh fake storage endpoint (RestartObligationsForTest), preserving ProcessStateForTest cleanup. A red/green regression and existing same-store restart/owed-marker tests pass. This is test-only, not a lease runtime change. Review that it does not mask same-store persistence semantics. Full new-tip CI remains mandatory.
+
+Check the actual shared sink and all callers, unchanged source/trust of served-marker exemptions and explicit flat choice, and all named census units/envelopes at the supplied exact tip. The census question remains separate from isolation correctness. No fresh broad audit; existing P3s stay follow-ups. Return READY / READY AFTER FIXES / NOT READY with evidence. A further blocking finding stops work; no fifth review is authorized.
+
+### Fourth-review disposition and requested P2 completion
+
+Opus at 4fb2910820422cb1eec7c1669e520b7f19f8025b returned READY AFTER FIXES: R3 isolation P1 closed, every census unit/envelope approved, one availability P2. The author applied the exact requested return `launchRefused{ErrFenced}` at the pre-exec refusal, preserving predicate and user text. A real Service regression now proves StopUncertain is false; Linux external tests use the actual layout.Pass.Converge and real Service fence to verify migration when the required DB exists. Those tests failed with plain ErrFenced and passed with launchRefused. The named census is regenerated; read sources/dispositions are unchanged.
+
+No optional-database/root-storage behavior was added. A no-DB regression confirms that case still refuses safely, and the comment no longer promises automatic migration. Supported no-DB/foreign recovery is explicitly tracked as #774, the reviewer-permitted known residual. No fifth review was opened. Final-tip CI remains the merge gate.
diff --git a/go.mod b/go.mod
index e485e3252..bf65ac4ba 100644
--- a/go.mod
+++ b/go.mod
@@ -26,9 +26,9 @@ require (
github.com/pion/stun/v3 v3.1.5
github.com/pion/turn/v4 v4.1.4
github.com/superfly/ltx v0.5.1
- golang.org/x/crypto v0.57.0
- golang.org/x/net v0.60.0
- golang.org/x/sys v0.48.0
+ golang.org/x/crypto v0.58.0
+ golang.org/x/net v0.62.0
+ golang.org/x/sys v0.49.0
modernc.org/sqlite v1.55.0
)
@@ -76,8 +76,8 @@ require (
github.com/wasilibs/go-re2 v1.3.0 // indirect
github.com/wlynxg/anet v0.0.5 // indirect
golang.org/x/mod v0.41.0 // indirect
- golang.org/x/sync v0.23.0 // indirect
- golang.org/x/text v0.42.0 // indirect
+ golang.org/x/sync v0.24.0 // indirect
+ golang.org/x/text v0.43.0 // indirect
google.golang.org/protobuf v1.36.10 // indirect
modernc.org/libc v1.74.1 // indirect
modernc.org/mathutil v1.7.1 // indirect
@@ -88,9 +88,9 @@ require (
amadan.net/carlos/platform.git/launchctx v0.0.0
github.com/KarpelesLab/squashfs v1.2.0
github.com/aws/aws-sdk-go-v2/service/sns v1.43.0
- github.com/klauspost/compress v1.18.0
+ github.com/klauspost/compress v1.20.2
github.com/oschwald/maxminddb-golang v1.13.1
- golang.org/x/tools v0.49.0
+ golang.org/x/tools v0.51.0
)
replace amadan.net/carlos/platform.git/launchctx => ./launchctx
diff --git a/go.sum b/go.sum
index f90cabcb9..74537b15b 100644
--- a/go.sum
+++ b/go.sum
@@ -132,6 +132,8 @@ github.com/jalaali/go-jalaali v0.0.0-20210801064154-80525e88d958 h1:qxLoi6CAcXVz
github.com/jalaali/go-jalaali v0.0.0-20210801064154-80525e88d958/go.mod h1:Wqfu7mjUHj9WDzSSPI5KfBclTTEnLveRUFr/ujWnTgE=
github.com/klauspost/compress v1.18.0 h1:c/Cqfb0r+Yi+JtIEq73FWXVkRonBlf0CRNYc8Zttxdo=
github.com/klauspost/compress v1.18.0/go.mod h1:2Pp+KzxcywXVXMr50+X0Q/Lsb43OQHYWRCY2AiWywWQ=
+github.com/klauspost/compress v1.20.2 h1:v5tiZvm1KGLyg5d5oXdXe3lsSPrbEUiKoXGia//I7Qo=
+github.com/klauspost/compress v1.20.2/go.mod h1:LUdAzn7YLVvxLpc7y3V1m40wESHTgc1422pwwBSKYuI=
github.com/kr/fs v0.1.0 h1:Jskdu9ieNAYnjxsi0LbQp1ulIKZV1LAFgK1tWhpZgl8=
github.com/kr/fs v0.1.0/go.mod h1:FFnZGqtBN9Gxj7eW1uZ42v5BccTP0vu6NEaFoC2HwRg=
github.com/kylelemons/godebug v0.0.0-20170820004349-d65d576e9348/go.mod h1:B69LEHPfb2qLo0BaaOLcbitczOKLWTsrBG9LczfCD4k=
@@ -224,25 +226,37 @@ go.opentelemetry.io/otel/trace v1.39.0 h1:2d2vfpEDmCJ5zVYz7ijaJdOF59xLomrvj7bjt6
go.opentelemetry.io/otel/trace v1.39.0/go.mod h1:88w4/PnZSazkGzz/w84VHpQafiU4EtqqlVdxWy+rNOA=
golang.org/x/crypto v0.57.0 h1:3ZVCjf8Ggz7zneR/EHRVx68Ctf+2pmIMP2UFhh9cC6M=
golang.org/x/crypto v0.57.0/go.mod h1:Fdz0i5U6CoizGwLda9DttjSk6qlZo25zYNtR+ycvuZA=
+golang.org/x/crypto v0.58.0 h1:COkYLr4k7nDI4r6QtMML2AfzeIswWHAJthLS6K/M/54=
+golang.org/x/crypto v0.58.0/go.mod h1:Xh+kl5A+M0gMiWDytH2Hhr5Z7WbNCpv/eB/EFgfSk+w=
golang.org/x/mod v0.41.0 h1:qJmnOUb4YB+FsEuM3HcWucdZASCPGhsX6uljO6pog0c=
golang.org/x/mod v0.41.0/go.mod h1:Ek9pY8RKWXwsWvd3rQiHYtMqkjSUV+s1Rj7j4H5Ur6o=
golang.org/x/net v0.60.0 h1:79p50tfZlm0J9YfoDsSi639qSXNGVwEzOPLCxM2FsYU=
golang.org/x/net v0.60.0/go.mod h1:2DA/G1UfVbCpQPeWTmMPGY7Cs2PkBkwu743bVX5PIVg=
+golang.org/x/net v0.62.0 h1:18ELalfM5+XNRwzM2nYqXsZQ9ByS1uhj2O/U7+5jqRY=
+golang.org/x/net v0.62.0/go.mod h1:WgDCOTH8iwtB66T4/GfI94AHo/hhdb7Hah9NDseQfiI=
golang.org/x/oauth2 v0.34.0 h1:hqK/t4AKgbqWkdkcAeI8XLmbK+4m4G5YeQRrmiotGlw=
golang.org/x/oauth2 v0.34.0/go.mod h1:lzm5WQJQwKZ3nwavOZ3IS5Aulzxi68dUSgRHujetwEA=
golang.org/x/sync v0.0.0-20201207232520-09787c993a3a/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.23.0 h1:KameEIfc1IkluZyXWLn39Wd4tURc6GbCiISGiZm2bQk=
golang.org/x/sync v0.23.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0=
+golang.org/x/sync v0.24.0 h1:iqiDrGoDgyuvAKrhLQthUEzU/R378N78gXbBjxed7oA=
+golang.org/x/sync v0.24.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0=
golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.48.0 h1:bbX/i/6MgT9BVLM9RT1thmxL04yeTAhbEz4SyadbXoo=
golang.org/x/sys v0.48.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
+golang.org/x/sys v0.49.0 h1:XbzkgYJHdqh/8m2Uu0W/dQv8nktxx4BFHp1M0gROTXA=
+golang.org/x/sys v0.49.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
golang.org/x/text v0.42.0 h1:JbOZXgfeCPU9gacVtYliJqOhD+zhrEqK4LfdpmlUZqI=
golang.org/x/text v0.42.0/go.mod h1:ojzP1Z+2QtioaF8DTtO8K5q7JWVVYwZKenzujK0Zd0E=
+golang.org/x/text v0.43.0 h1:1QivrlhwAsnMOcqgOdl9my7s9OyZl8O5/UGUTJVXoWc=
+golang.org/x/text v0.43.0/go.mod h1:hbSIYA/amXcRXTFSZqh8tWHEoqRvvbKPJ2uz/KU+a+s=
golang.org/x/time v0.14.0 h1:MRx4UaLrDotUKUdCIqzPC48t1Y9hANFKIRpNx+Te8PI=
golang.org/x/time v0.14.0/go.mod h1:eL/Oa2bBBK0TkX57Fyni+NgnyQQN4LitPmob2Hjnqw4=
golang.org/x/tools v0.49.0 h1:3NI7VXzL9+1WZD52Dx2ttoPwD5DWrFGpl9mFZDlmisI=
golang.org/x/tools v0.49.0/go.mod h1:SJNXV9DBKT0UbdttsQjbfJlAE/q+y36++zo3uL3N0Oo=
+golang.org/x/tools v0.51.0 h1:k4Xc/1Om9jwkBJBo4NVLMSARBoWtK10mx+W5BnXCeAI=
+golang.org/x/tools v0.51.0/go.mod h1:9eEncMayCV6zRMGhR5eZEC2iBx98qWcF1HZ9Z7wJOoA=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
google.golang.org/api v0.155.0 h1:vBmGhCYs0djJttDNynWo44zosHlPvHmA0XiN2zP2DtA=
google.golang.org/api v0.155.0/go.mod h1:GI5qK5f40kCpHfPn6+YzGAByIKWv8ujFnmoWm7Igduk=
diff --git a/internal/activator/backend_exec.go b/internal/activator/backend_exec.go
index f6de02f2f..0fa4851f3 100644
--- a/internal/activator/backend_exec.go
+++ b/internal/activator/backend_exec.go
@@ -252,6 +252,13 @@ type ExecBackend struct {
// gate (every unit test and any box that predates the check). Wired in
// production by Task 6.
NestedOK func() error
+ // FlatLayoutChosen reports whether this box chose the flat layout on
+ // purpose (a recorded flat intent, or CARLOS_LAYOUT_DEFAULT=flat): the
+ // one case a new always-on binary row at the flat paths may start as
+ // an exec child (residentLayoutRefusal). Nil, and every box that never
+ // said flat, refuses that start; the layout pass moves the row nested
+ // and it starts there. Wired by internal/host from the box's intent.
+ FlatLayoutChosen func() bool
// RootfsOK reports whether the control service's rootfs probe passed
// on this boot (GET /ready/rootfs). RootfsPlacement is
// host.RootfsPlacementAllowed with the box's facts: every rule a
@@ -2158,6 +2165,34 @@ func (b *ExecBackend) Start(ctx context.Context, rt registry.Route) (Proc, strin
return b.startChildAt(ctx, rt, rt.Socket, 0, "", "", cgroup.Limit{})
}
+// residentLayoutRefusal refuses the flat exec child for a binary resident
+// (statelessResident: stateless, not hibernating, no runtime) that has
+// never served (no serving or good build), at the flat or foreign paths,
+// on a box that did not choose flat (FlatLayoutChosen). Such a row is a
+// new tenant whose stateless mark arrived after its mint (SeedStateless at
+// staging, or a replica assignment), so its paths were minted as an
+// unflagged socket route's; started flat it would run with the agent's
+// uid beside its nested siblings. Refused, it is asleep, so the layout pass
+// can move it nested without an awake grace, after which it starts as a
+// unit; that needs the row's database to exist on this box, so a row with
+// no database (or a foreign one) stays refused until an operator acts. A
+// resident that has served (every row that ran before this rule, and its
+// restarts) is not touched. It uses the existing maintenance-fence refusal,
+// marked launchRefused: the refusal is before any exec, so the Service
+// records "not started", not an uncertain stop that would defer the move.
+func (b *ExecBackend) residentLayoutRefusal(rt registry.Route, l Layout) error {
+ if !statelessResident(rt) || rt.ServingVersion != "" || rt.GoodVersion != "" {
+ return nil
+ }
+ if l != LayoutFlat && l != LayoutForeign {
+ return nil
+ }
+ if b.FlatLayoutChosen != nil && b.FlatLayoutChosen() {
+ return nil
+ }
+ return launchRefused{ErrFenced}
+}
+
// StartGen is Start for generation n (zero-downtime spec §7.1). perGen false
// is Start exactly: the canonical socket, the canonical control socket, the
// same argv. perGen true binds the generation's own socket: GenSocketPath
@@ -2415,6 +2450,11 @@ func (b *ExecBackend) spawnChildFrom(ctx context.Context, rt registry.Route, soc
}
host := rt.Host
paths := b.pathsFor(rt)
+ // Every flat or foreign instance start reaches this function, including
+ // StartStaged. Refuse before preparing its files or executing its binary.
+ if err := b.residentLayoutRefusal(rt, paths.layout); err != nil {
+ return nil, "", err
+ }
dbPath := paths.dbPath
child, ownTier, err := b.placeFor(spawnInstance, n)
if err != nil {
diff --git a/internal/activator/hawake_test.go b/internal/activator/hawake_test.go
index 98468785c..9e8d6b01e 100644
--- a/internal/activator/hawake_test.go
+++ b/internal/activator/hawake_test.go
@@ -72,7 +72,9 @@ func haBackendEmptyIndex(t *testing.T, host string) (*ExecBackend, registry.Rout
// obligation store) go back as they were after the test (final review
// F5).
t.Cleanup(lease.ProcessStateForTest())
- if err := lease.SetObligationDir(t.TempDir()); err != nil {
+ // Restart, not SetObligationDir (which merges): a prior fixture's
+ // pending obligation names another store and must not carry over.
+ if err := lease.RestartObligationsForTest(t.TempDir()); err != nil {
t.Fatal(err)
}
lease.SetSelf(hafresh.Self{Ref: "a", IID: "i-a", Account: "111122223333", Region: "eu-west-1"})
@@ -354,6 +356,31 @@ func publishManifest(t *testing.T, b *ExecBackend, rt registry.Route, files map[
}
}
+// A fresh HA fixture starts with no obligations: one still pending for an
+// earlier fixture's store is never retried against the new fixture's
+// independent S3 endpoint (it would fail NoSuchKey there).
+func TestHAFixtureIgnoresPriorFixtureObligation(t *testing.T) {
+ s, e := haServiceEntry(t, "shop.example.com")
+ s.unit.set(func(u *haUnit) { u.slicePop = false })
+ s.failMarkerPuts(1)
+ var oe *lease.ObligationError
+ if err := s.a.releaseHAClean(context.Background(), e); !errors.As(err, &oe) {
+ t.Fatalf("release: %v, want the persisted obligation", err)
+ }
+ if n := len(lease.PendingObligations()); n != 1 {
+ t.Fatalf("%d obligations pending, want the old store's one", n)
+ }
+ b, rt := haBackend(t, "shop.example.com")
+ if n := len(lease.PendingObligations()); n != 0 {
+ t.Fatalf("fresh fixture inherited %d obligations", n)
+ }
+ l, err := b.Acquire(context.Background(), rt)
+ if err != nil {
+ t.Fatalf("acquire against the fresh store: %v", err)
+ }
+ releaseHALease(t, l)
+}
+
func releaseHALease(t *testing.T, l Lease) {
t.Helper()
t.Cleanup(func() {
diff --git a/internal/activator/resident_layout_converge_linux_test.go b/internal/activator/resident_layout_converge_linux_test.go
new file mode 100644
index 000000000..59cf6ee0d
--- /dev/null
+++ b/internal/activator/resident_layout_converge_linux_test.go
@@ -0,0 +1,95 @@
+//go:build linux
+
+package activator_test
+
+import (
+ "context"
+ "os"
+ "path/filepath"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/activator"
+ "github.com/carlosframework/platform/internal/layout"
+)
+
+func residentPass(t *testing.T) (*layout.Pass, *activator.Service, string) {
+ t.Helper()
+ svc, reg, eb, rt := activator.ResidentRefusalFixture(t)
+ // The refusal is a start that did not happen, not an uncertain stop.
+ if svc.StopUncertain(rt.Host) {
+ t.Fatal("the refused resident wake left an uncertain stop on record")
+ }
+ p := &layout.Pass{Registry: reg, Fence: svc, DataDir: eb.DataDir, SocketDir: eb.RunDirOverride,
+ SocketsGID: -1, Now: time.Now, DeferAwake: true, Logf: t.Logf}
+ return p, svc, rt.Host
+}
+
+// The recovery the refusal promises, against the real Service and the real
+// layout pass: the refused resident is migrated nested and unfenced.
+// This is migration coverage, not a privileged unit-launch test.
+func TestConvergeMigratesARefusedNewResident(t *testing.T) {
+ p, svc, host := residentPass(t)
+ rt, err := p.Registry.Get(host)
+ if err != nil || rt == nil {
+ t.Fatal(err)
+ }
+ if err := os.MkdirAll(filepath.Dir(rt.DBPath), 0o700); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(rt.DBPath, []byte("db"), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ var res layout.Result
+ for _, r := range p.Converge(context.Background(), layout.ModeNested) {
+ if r.Host == host {
+ res = r
+ }
+ }
+ if res.Outcome != "migrated" {
+ t.Fatalf("result = %+v", res)
+ }
+ if svc.Fenced(host) || svc.StopUncertain(host) {
+ t.Fatalf("fenced %v, uncertain %v after the pass", svc.Fenced(host), svc.StopUncertain(host))
+ }
+ plan, err := layout.PlanFor(p.DataDir, p.SocketDir, host, layout.ModeNested)
+ if err != nil {
+ t.Fatal(err)
+ }
+ got, err := p.Registry.Get(host)
+ if err != nil || got == nil {
+ t.Fatal(err)
+ }
+ if got.DBPath != plan.To.DB || got.Socket != plan.To.Socket {
+ t.Fatalf("row = db %q socket %q, want %q %q", got.DBPath, got.Socket, plan.To.DB, plan.To.Socket)
+ }
+}
+
+// With no database on this box the pass refuses the row as it always has:
+// the flat paths stay and nothing launches. A known recovery limitation.
+func TestConvergeKeepsARefusedNewResidentWithoutADatabaseFlat(t *testing.T) {
+ p, svc, host := residentPass(t)
+ before, err := p.Registry.Get(host)
+ if err != nil || before == nil {
+ t.Fatal(err)
+ }
+ var res layout.Result
+ for _, r := range p.Converge(context.Background(), layout.ModeNested) {
+ if r.Host == host {
+ res = r
+ }
+ }
+ if res.Outcome != "refused" {
+ t.Fatalf("result = %+v", res)
+ }
+ got, err := p.Registry.Get(host)
+ if err != nil || got == nil {
+ t.Fatal(err)
+ }
+ if got.DBPath != before.DBPath || got.Socket != before.Socket {
+ t.Fatalf("paths moved: %+v -> %+v", before, got)
+ }
+ if svc.StopUncertain(host) {
+ t.Fatal("uncertain stop recorded")
+ }
+}
diff --git a/internal/activator/resident_layout_test.go b/internal/activator/resident_layout_test.go
new file mode 100644
index 000000000..90e9871b6
--- /dev/null
+++ b/internal/activator/resident_layout_test.go
@@ -0,0 +1,318 @@
+package activator
+
+import (
+ "context"
+ "crypto/ed25519"
+ "crypto/rand"
+ "errors"
+ "os"
+ "path/filepath"
+ "runtime"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/provision"
+ "github.com/carlosframework/platform/internal/registry"
+ "github.com/carlosframework/platform/internal/release"
+)
+
+// A new binary resident (stateless, not hibernating, never served) whose
+// row is at the flat paths is not started as an exec child on a box that
+// did not choose flat: Start and StartGen refuse it as fenced, and no
+// child runs. The same row starts once the box has chosen flat, once it
+// has served (a legacy resident's restart), or when it hibernates (not a
+// resident at all): those reach the stateless secrets gate instead. The row is the production projection
+// (provision.RouteFor on a non-hibernating record, marked stateless as
+// staging marks it), not a hand-shaped route.
+func TestExecBackendRefusesANewFlatBinaryResident(t *testing.T) {
+ b := testExecBackend(t)
+ b.RunDirOverride = shortRunDir(t)
+ host := "shop.example.com"
+ off := false
+ rec := provision.Record{Account: "bab", App: "shop", Host: host, Channel: "canary/test", Hibernate: &off, CreatedAt: time.Unix(1, 0)}
+ // Minted on a box whose intent is not nested: the flat paths, as an
+ // unflagged socket route's, with the socket under the test's run dir.
+ rt := provision.RouteFor(rec, b.DataDir, "", false, nil)
+ rt.Socket = filepath.Join(b.RunDirOverride, host+".sock")
+ rt.Stateless = true // SeedStateless at staging
+ if !statelessResident(rt) || rt.ServingVersion != "" {
+ t.Fatalf("fixture is not a never-served binary resident: %+v", rt)
+ }
+ if l, why := b.Layout(rt); l != LayoutFlat {
+ t.Fatalf("fixture classifies %q (%s), want flat", l, why)
+ }
+ stageRecordingLiveFullEnv(t, b, host, "v1")
+ refused := func(name string, rt registry.Route) {
+ t.Helper()
+ if _, _, err := b.Start(context.Background(), rt); !errors.Is(err, ErrFenced) {
+ t.Fatalf("%s: Start = %v, want the fenced refusal", name, err)
+ }
+ if _, _, err := b.StartGen(context.Background(), rt, 1, false); !errors.Is(err, ErrFenced) {
+ t.Fatalf("%s: StartGen = %v, want the fenced refusal", name, err)
+ }
+ }
+ // Past the layout refusal, a stateless row meets the next gate, its
+ // shared secrets (errStatelessSecretsWaiting): proof the layout did
+ // not refuse it. The fixture delivers no config, so no child runs.
+ started := func(name string, rt registry.Route) {
+ t.Helper()
+ if _, _, err := b.Start(context.Background(), rt); errors.Is(err, ErrFenced) || !errors.Is(err, errStatelessSecretsWaiting) {
+ t.Fatalf("%s: Start = %v, want to pass the layout refusal", name, err)
+ }
+ if _, _, err := b.StartGen(context.Background(), rt, 1, false); errors.Is(err, ErrFenced) || !errors.Is(err, errStatelessSecretsWaiting) {
+ t.Fatalf("%s: StartGen = %v, want to pass the layout refusal", name, err)
+ }
+ }
+ refused("no FlatLayoutChosen wired", rt)
+ b.FlatLayoutChosen = func() bool { return false }
+ refused("box has not chosen flat", rt)
+ foreign := rt
+ foreign.Socket = tmpSock(t)
+ if l, _ := b.Layout(foreign); l != LayoutForeign {
+ t.Fatalf("foreign fixture classifies %q", l)
+ }
+ refused("foreign paths", foreign)
+
+ served := rt
+ served.ServingVersion = "v1"
+ started("a resident that has served", served)
+ sleeper := rt
+ sleeper.Hibernate = true
+ started("a hibernating row", sleeper)
+ b.FlatLayoutChosen = func() bool { return true }
+ started("the box chose flat", rt)
+}
+
+// neverServedFlatRow is the production projection of a new binary resident
+// on a box that did not choose flat: provision.RouteFor on a non-hibernating
+// record, minted at the flat paths, marked stateless as staging marks it.
+func neverServedFlatRow(t *testing.T, b *ExecBackend, host string) registry.Route {
+ t.Helper()
+ off := false
+ rec := provision.Record{Account: "bab", App: "shop", Host: host, Channel: "canary/test", Hibernate: &off, CreatedAt: time.Unix(1, 0)}
+ rt := provision.RouteFor(rec, b.DataDir, "", false, nil)
+ rt.Socket = filepath.Join(b.RunDirOverride, host+".sock")
+ rt.Stateless = true
+ if !statelessResident(rt) || rt.ServingVersion != "" || rt.GoodVersion != "" {
+ t.Fatalf("fixture is not a never-served binary resident: %+v", rt)
+ }
+ return rt
+}
+
+// noLaunchArtifacts fails t if a launch of rt got any further than the
+// layout refusal: the per-instance env file (the admin token), a control
+// socket or any socket at the generation's path.
+func noLaunchArtifacts(t *testing.T, b *ExecBackend, rt registry.Route, n uint64) {
+ t.Helper()
+ p := b.pathsFor(rt)
+ for _, path := range []string{p.envFile, rt.Socket, rt.Socket + ".control", b.flatGenSocket(rt.Host, n), b.flatGenSocket(rt.Host, n) + ".control"} {
+ if _, err := os.Lstat(path); !os.IsNotExist(err) {
+ t.Fatalf("%s exists after the refused launch (err %v)", path, err)
+ }
+ }
+}
+
+// StartStaged is the production exec of a stateless binary resident (the
+// activator's wake goes through startPinnedAt, never Start or StartGen), so
+// the refusal holds there too, at the flat and the foreign paths, and
+// nothing is prepared first: no admin token, no control socket, no child.
+func TestExecBackendStartStagedRefusesANewFlatBinaryResident(t *testing.T) {
+ b := testExecBackend(t)
+ b.RunDirOverride = shortRunDir(t)
+ host := "shop.example.com"
+ rt := neverServedFlatRow(t, b, host)
+ id := stagedID(t, t.TempDir(), "v1")
+ gen := func(n uint64) Gen {
+ return Gen{N: n, Build: "v1", StagedPath: id.StagedPath, Digest: id.Digest, Stateless: true}
+ }
+ foreign := rt
+ foreign.Socket = tmpSock(t)
+ if l, _ := b.Layout(foreign); l != LayoutForeign {
+ t.Fatalf("foreign fixture classifies %q", l)
+ }
+ for _, tc := range []struct {
+ name string
+ rt registry.Route
+ want Layout
+ }{{"flat", rt, LayoutFlat}, {"foreign", foreign, LayoutForeign}} {
+ if l, why := b.Layout(tc.rt); l != tc.want {
+ t.Fatalf("%s fixture classifies %q (%s)", tc.name, l, why)
+ }
+ for _, wired := range []func() bool{nil, func() bool { return false }} {
+ b.FlatLayoutChosen = wired
+ g, p, err := b.StartStaged(context.Background(), tc.rt, gen(3))
+ if !errors.Is(err, ErrFenced) || p != nil {
+ t.Fatalf("%s: StartStaged = %+v, %v, %v; want the fenced refusal and no process", tc.name, g, p, err)
+ }
+ if tc.want == LayoutFlat {
+ noLaunchArtifacts(t, b, tc.rt, 3)
+ }
+ if _, err := os.Lstat(b.pathsFor(tc.rt).envFile); !os.IsNotExist(err) {
+ t.Fatalf("%s: the refused launch wrote the instance env file (err %v)", tc.name, err)
+ }
+ if _, err := os.Lstat(tc.rt.Socket + ".control"); !os.IsNotExist(err) {
+ t.Fatalf("%s: the refused launch bound a control socket (err %v)", tc.name, err)
+ }
+ }
+ }
+
+ // Past the layout refusal a stateless row meets the shared-secrets gate:
+ // proof that a served legacy resident and an explicit flat choice are
+ // not refused here either.
+ passed := func(name string, rt registry.Route) {
+ t.Helper()
+ if _, _, err := b.StartStaged(context.Background(), rt, gen(4)); errors.Is(err, ErrFenced) || !errors.Is(err, errStatelessSecretsWaiting) {
+ t.Fatalf("%s: StartStaged = %v, want to pass the layout refusal", name, err)
+ }
+ }
+ b.FlatLayoutChosen = func() bool { return false }
+ served := rt
+ served.ServingVersion = "v1"
+ passed("a resident that has served", served)
+ good := rt
+ good.GoodVersion = "v1"
+ passed("a resident with a good build", good)
+ b.FlatLayoutChosen = func() bool { return true }
+ passed("the box chose flat", rt)
+ // A foreign row has no shared-secrets gate before its exec: it reaches
+ // the exec itself, which refuses the fixture's non-executable "build".
+ if _, _, err := b.StartStaged(context.Background(), foreign, gen(5)); err != nil {
+ var pe *os.PathError
+ if !errors.As(err, &pe) || pe.Op != "fork/exec" || pe.Path != id.StagedPath {
+ t.Fatalf("the box chose flat, foreign paths: StartStaged = %v, want to reach the exec", err)
+ }
+ } else {
+ t.Fatal("the non-executable staged fixture unexpectedly launched")
+ }
+}
+
+// realStagedBackend is the wake rig's backend whose StartStaged is the real
+// ExecBackend's, reached as production reaches it (SplitBackend), and
+// which keeps what it returned: the HTTP layer maps a failure, so the spy
+// holds the error the launch actually refused with.
+type realStagedBackend struct {
+ *wakeRelBackend
+ split *SplitBackend
+ smu sync.Mutex
+ errs []error
+ procs int
+}
+
+func (b *realStagedBackend) StartStaged(ctx context.Context, rt registry.Route, g Gen) (Gen, Proc, error) {
+ got, p, err := b.split.StartStaged(ctx, rt, g)
+ b.smu.Lock()
+ b.errs = append(b.errs, err)
+ if p != nil {
+ b.procs++
+ }
+ b.smu.Unlock()
+ return got, p, err
+}
+
+func (b *realStagedBackend) launches() ([]error, int) {
+ b.smu.Lock()
+ defer b.smu.Unlock()
+ return append([]error(nil), b.errs...), b.procs
+}
+
+// ResidentRefusalFixture is the real-Service fixture of the resident-wake
+// regression, exported for the external layout test (which cannot be in this
+// package: layout imports activator). It returns the Service whose resident
+// wake of a never-served flat stateless row has already been refused (one
+// settled resident tick through the real StartStaged), its registry (holding
+// the staged row) and the real ExecBackend and row. Nothing is started.
+func ResidentRefusalFixture(t *testing.T) (*Service, *registry.Registry, *ExecBackend, registry.Route) {
+ svc, reg, eb, rt, spy := residentRefusalFixture(t)
+ tickSettled(t, svc)
+ if errs, procs := spy.launches(); len(errs) == 0 || procs != 0 {
+ t.Fatalf("fixture: refusals %v, processes %d", errs, procs)
+ }
+ return svc, reg, eb, rt
+}
+
+func residentRefusalFixture(t *testing.T) (*Service, *registry.Registry, *ExecBackend, registry.Route, *realStagedBackend) {
+ r := newWakeRelRig(t)
+ wireStatelessRig(r)
+ eb := testExecBackend(t)
+ eb.RunDirOverride = shortRunDir(t)
+ eb.FlatLayoutChosen = func() bool { return false }
+ spy := &realStagedBackend{wakeRelBackend: r.b, split: &SplitBackend{Exec: eb}}
+ r.a.backend = spy
+
+ reg, err := registry.Open(filepath.Join(t.TempDir(), "registry.db"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { reg.Close() })
+ base := neverServedFlatRow(t, eb, "shop.example.com")
+ base.Stateless = false // as minted: staging seeds it below
+ if err := reg.Upsert(base); err != nil {
+ t.Fatal(err)
+ }
+ store := release.NewDirStore(t.TempDir())
+ pub, priv, err := ed25519.GenerateKey(rand.Reader)
+ if err != nil {
+ t.Fatal(err)
+ }
+ platform := runtime.GOOS + "-" + runtime.GOARCH
+ manifest := release.Manifest{App: "shop", Version: "v1", Kind: "binary", Stateless: true, Artifacts: map[string]release.Artifact{platform: {File: "shop"}}}
+ ctx := context.Background()
+ if err := release.Ship(ctx, store, "bab", manifest, map[string][]byte{platform: []byte("binary")}); err != nil {
+ t.Fatal(err)
+ }
+ if err := release.Promote(ctx, store, priv, "bab", "shop", "canary/test", "v1"); err != nil {
+ t.Fatal(err)
+ }
+ opt := t.TempDir()
+ if err := release.Pass(ctx, reg, store, pub, opt, nil); err != nil {
+ t.Fatal(err)
+ }
+ fresh, err := reg.Get(base.Host)
+ if err != nil || fresh == nil {
+ t.Fatalf("staged row: %v %v", fresh, err)
+ }
+ r.rt = *fresh
+ if !statelessResident(r.rt) || r.rt.ServingVersion != "" || r.rt.GoodVersion != "" {
+ t.Fatalf("staging did not seed a never-served resident: %+v", r.rt)
+ }
+ if l, why := eb.Layout(r.rt); l != LayoutFlat {
+ t.Fatalf("the staged row classifies %q (%s), want flat", l, why)
+ }
+ selection, err := release.CanonicalRuntimeSelection(ctx, store, "bab", "shop", "v1", release.VersionPath(opt, "bab", "v1", "shop"), true)
+ if err != nil {
+ t.Fatal(err)
+ }
+ r.setPlan(WakePlan{Boot: selection.Identity, Mode: ModeHold, Declarations: []release.RuntimeSelection{selection}})
+ r.a.Routes, r.a.residentLister = reg, reg
+ r.a.residentJitter = func() float64 { return 0 }
+ return r.a, reg, eb, r.rt, spy
+}
+
+// The activator's own resident wake of a never-served stateless binary row
+// (the row staging marked stateless after its flat mint) goes doWake ->
+// doStatelessWake -> startPinnedAt -> SplitBackend.StartStaged ->
+// ExecBackend.StartStaged -> spawnChildFrom. On a box that did not choose
+// flat the launch is refused as fenced there, with no child, instance admin
+// token or control socket made.
+func TestResidentWakeRefusesANewFlatBinaryResident(t *testing.T) {
+ a, _, eb, rt, spy := residentRefusalFixture(t)
+ tickSettled(t, a)
+ errs, procs := spy.launches()
+ if len(errs) == 0 {
+ t.Fatal("the resident wake never reached ExecBackend.StartStaged")
+ }
+ for _, err := range errs {
+ if !errors.Is(err, ErrFenced) {
+ t.Fatalf("ExecBackend.StartStaged = %v, want the fenced refusal", err)
+ }
+ }
+ if procs != 0 || a.hasEntry(rt.Host) {
+ t.Fatalf("a flat child ran: %d process(es), entry %v", procs, a.hasEntry(rt.Host))
+ }
+ // Refused before any exec: a start that did not happen, not an uncertain stop.
+ if a.StopUncertain(rt.Host) {
+ t.Fatal("the refused resident wake left an uncertain stop on record")
+ }
+ noLaunchArtifacts(t, eb, rt, 1)
+}
diff --git a/internal/activator/stateless_test.go b/internal/activator/stateless_test.go
index cc3e0c9f8..d6f4f0873 100644
--- a/internal/activator/stateless_test.go
+++ b/internal/activator/stateless_test.go
@@ -241,6 +241,7 @@ func TestStatelessEveryEnvironment(t *testing.T) {
func TestStatelessBinaryArgumentsAtExec(t *testing.T) {
t.Run("flat", func(t *testing.T) {
b := testExecBackend(t)
+ b.FlatLayoutChosen = func() bool { return true }
b.RunDirOverride = t.TempDir()
host := "shop.example.com"
stageLive(t, b, host, "v1")
diff --git a/internal/console/apicli.go b/internal/console/apicli.go
index ab9180672..e294ba2e7 100644
--- a/internal/console/apicli.go
+++ b/internal/console/apicli.go
@@ -988,7 +988,7 @@ func (s *Server) handleAPIPromote(w http.ResponseWriter, r *http.Request) {
jsonError(w, http.StatusBadGateway, "could not read the pipeline for "+app)
return
}
- if err := deployScopeAllows(p, pipe != nil, channel, req.Hotfix); err != nil {
+ if err := deployScopeAllows(p, pipe, channel, req.Hotfix); err != nil {
s.writeDeployRefusal(w, err)
return
}
@@ -1129,7 +1129,7 @@ func (s *Server) handleAPIPromote(w http.ResponseWriter, r *http.Request) {
}
signer = sg
authorize = func(pp *release.Pipeline) error {
- return deployScopeAllows(p, pp != nil, channel, req.Hotfix)
+ return deployScopeAllows(p, pp, channel, req.Hotfix)
}
}
res, err := signer.PromoteOnLadder(ctx, s.cfg.Releases, acct.Sqid, app, channel, version,
@@ -1305,7 +1305,7 @@ func (s *Server) handleAPIRollback(w http.ResponseWriter, r *http.Request) {
jsonError(w, http.StatusBadGateway, "could not read the pipeline for "+app)
return
}
- if err := deployScopeAllows(p, pipe != nil, channel, false); err != nil {
+ if err := deployScopeAllows(p, pipe, channel, false); err != nil {
s.writeDeployRefusal(w, err)
return
}
@@ -1437,7 +1437,7 @@ func (s *Server) refuseStableOverAPI(w http.ResponseWriter, p Principal, acct *A
if rung, _ := release.Rung(channel); rung != release.RungStable {
return false
}
- if err := deployScopeAllows(p, false, channel, false); err != nil {
+ if err := deployScopeAllows(p, nil, channel, false); err != nil {
s.writeDeployRefusal(w, err)
return true
}
@@ -1458,7 +1458,7 @@ func (s *Server) writePasskeyRefusal(w http.ResponseWriter, acct *Account, app,
// inside its admitted mutation, of the pipeline read there.
func deployScopeAuthorize(p Principal, channel string) func(*release.Pipeline) error {
return func(pp *release.Pipeline) error {
- return deployScopeAllows(p, pp != nil, channel, false)
+ return deployScopeAllows(p, pp, channel, false)
}
}
diff --git a/internal/console/apigatepass.go b/internal/console/apigatepass.go
index 169610364..c22501e28 100644
--- a/internal/console/apigatepass.go
+++ b/internal/console/apigatepass.go
@@ -124,7 +124,7 @@ func (s *Server) handleAPIInstanceGatePass(w http.ResponseWriter, r *http.Reques
// pipeline: the channels a deploy credential ships its own build straight
// onto, with nothing in between.
func deployGatePassAllowed(p Principal, pipe *release.Pipeline, channel string) bool {
- if deployScopeAllows(p, pipe != nil, channel, false) != nil {
+ if deployScopeAllows(p, pipe, channel, false) != nil {
return false
}
if rung, _ := release.Rung(channel); rung == release.RungBeta {
diff --git a/internal/console/deployscope.go b/internal/console/deployscope.go
index ddde52175..0d88784a4 100644
--- a/internal/console/deployscope.go
+++ b/internal/console/deployscope.go
@@ -90,7 +90,7 @@ func (e *deployRefusal) Error() string { return e.msg }
// times per write: early in the handler for the message, and by the release
// primitives on their own pipeline reads (Task 7). For every principal that
// is not a deploy credential it returns nil and changes nothing.
-func deployScopeAllows(p Principal, pipelined bool, channel string, hotfix bool) error {
+func deployScopeAllows(p Principal, pipe *release.Pipeline, channel string, hotfix bool) error {
if p.Kind != PrincipalService || p.Role != svcrole.Deploy {
return nil
}
@@ -114,7 +114,8 @@ func deployScopeAllows(p Principal, pipelined bool, channel string, hotfix bool)
if !inScope {
return &deployRefusal{fmt.Sprintf("deploy credential %s may move %s only, and %s is not one of them.", p.Name, held, channel)}
}
- if pipelined && rung != release.RungCanary {
+ defaultEdge := pipe != nil && len(pipe.Channels) == 1 && pipe.Channels[0] == (release.PipelineChannel{Name: release.RungEdge})
+ if pipe != nil && !defaultEdge && rung != release.RungCanary {
return &deployRefusal{fmt.Sprintf("%s has a pipeline, so deploy credential %s may move canary/<name> channels only.", p.App, p.Name)}
}
return nil
diff --git a/internal/console/deployscope_test.go b/internal/console/deployscope_test.go
index 3e8341877..6f0ef0dd4 100644
--- a/internal/console/deployscope_test.go
+++ b/internal/console/deployscope_test.go
@@ -38,7 +38,11 @@ func TestDeployScopeAllows(t *testing.T) {
{"publish untouched", pub, true, "stable", true, true},
{"person untouched", person, true, "stable", true, true},
} {
- err := deployScopeAllows(tc.p, tc.pipelined, tc.channel, tc.hotfix)
+ var pipe *release.Pipeline
+ if tc.pipelined {
+ pipe = &release.Pipeline{Channels: []release.PipelineChannel{{Name: "edge"}, {Name: "stable"}}}
+ }
+ err := deployScopeAllows(tc.p, pipe, tc.channel, tc.hotfix)
if (err == nil) != tc.ok {
t.Errorf("%s: err = %v, want ok=%v", tc.name, err, tc.ok)
}
@@ -180,3 +184,82 @@ func TestDeployRollbackOfStableIsD22(t *testing.T) {
}
stableAbsent()
}
+
+func TestDeployScopeSingleChannel(t *testing.T) {
+ p := Principal{Kind: PrincipalService, Role: svcrole.Deploy, Name: "ci", App: "hello", Rungs: []string{"canary", "edge", "beta"}}
+ for _, tc := range []struct {
+ name string
+ channels []release.PipelineChannel
+ allowed bool
+ }{
+ {"default", release.DefaultPipelineChannels(), true},
+ {"empty", nil, false},
+ {"beta", []release.PipelineChannel{{Name: "beta"}}, false},
+ {"custom", []release.PipelineChannel{{Name: "production"}}, false},
+ {"bake", []release.PipelineChannel{{Name: "edge", Bake: "1h"}}, false},
+ {"explicit zero bake", []release.PipelineChannel{{Name: "edge", Bake: "0s"}}, false},
+ {"passkey", []release.PipelineChannel{{Name: "edge", Rules: release.ChannelRules{Passkey: true}}}, false},
+ {"promote approvals", []release.PipelineChannel{{Name: "edge", Rules: release.ChannelRules{PromoteApprovals: 1}}}, false},
+ {"change approvals", []release.PipelineChannel{{Name: "edge", Rules: release.ChannelRules{ChangeApprovals: 1}}}, false},
+ {"multiple", []release.PipelineChannel{{Name: "edge"}, {Name: "beta"}}, false},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ pipe := &release.Pipeline{Channels: tc.channels}
+ if err := deployScopeAllows(p, pipe, "edge", false); (err == nil) != tc.allowed {
+ t.Fatalf("edge: %v, want allowed=%v", err, tc.allowed)
+ }
+ if err := deployScopeAuthorize(p, "edge")(pipe); (err == nil) != tc.allowed {
+ t.Fatalf("write authorization: %v, want allowed=%v", err, tc.allowed)
+ }
+ if got := deployGatePassAllowed(p, pipe, "edge"); got != tc.allowed {
+ t.Fatalf("gate pass: %v, want %v", got, tc.allowed)
+ }
+ if err := deployScopeAllows(p, pipe, "edge", true); err == nil {
+ t.Fatal("hotfix allowed")
+ }
+ if err := deployScopeAllows(p, pipe, "stable", false); err == nil {
+ t.Fatal("stable allowed")
+ }
+ if err := deployScopeAllows(p, pipe, "canary/test", false); err != nil {
+ t.Fatal(err)
+ }
+ restricted := p
+ restricted.Rungs = []string{"canary"}
+ if err := deployScopeAllows(restricted, pipe, "edge", false); err == nil {
+ t.Fatal("edge allowed without edge grant")
+ }
+ })
+ }
+}
+
+func TestDeployDefaultPipelinePromoteAndRollback(t *testing.T) {
+ fx, _, deploy := deployFixture(t)
+ ctx := context.Background()
+ if _, err := release.SetPipeline(ctx, fx.rel, fx.priv, "bab", "hello", release.DefaultPipelineChannels(), "paul@keymail.dev"); err != nil {
+ t.Fatal(err)
+ }
+ fx.forgetFrame("hello")
+ for _, version := range []string{"v1", "v2"} {
+ status, out := postJSON(t, fx.ts.URL+"/api/cli/apps/bab/hello/promote", map[string]any{"version": version, "channel": "edge"}, deploy)
+ if status != http.StatusOK || str(t, out, "result") != "promoted" {
+ t.Fatalf("promote %s: %d %v", version, status, out)
+ }
+ if g := pointerGrant(t, fx, "edge"); g == nil || g["name"] != "deploy.ci" {
+ t.Fatalf("grant: %v", g)
+ }
+ }
+ status, out := postJSON(t, fx.ts.URL+"/api/cli/apps/bab/hello/rollback", map[string]any{"channel": "edge"}, deploy)
+ if status != http.StatusOK || str(t, out, "result") != "rolled back" {
+ t.Fatalf("rollback: %d %v", status, out)
+ }
+ cp, err := release.Channel(ctx, fx.rel, fx.pub, "bab", "hello", "edge")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if cp.Version != "v1" {
+ t.Fatalf("version: %s", cp.Version)
+ }
+ if g := pointerGrant(t, fx, "edge"); g == nil || g["name"] != "deploy.ci" {
+ t.Fatalf("rollback grant: %v", g)
+ }
+}
diff --git a/internal/console/securityheaders.go b/internal/console/securityheaders.go
new file mode 100644
index 000000000..7479b4f4f
--- /dev/null
+++ b/internal/console/securityheaders.go
@@ -0,0 +1,13 @@
+package console
+
+import "net/http"
+
+func (s *Server) browserSecurityHeaders(h http.Header) {
+ h.Set("Content-Security-Policy", "frame-ancestors 'none'; object-src 'none'; base-uri 'self'")
+ h.Set("X-Frame-Options", "DENY")
+ h.Set("X-Content-Type-Options", "nosniff")
+ h.Set("Referrer-Policy", "strict-origin-when-cross-origin")
+ if s.secure {
+ h.Set("Strict-Transport-Security", "max-age=86400")
+ }
+}
diff --git a/internal/console/securityheaders_test.go b/internal/console/securityheaders_test.go
new file mode 100644
index 000000000..b4810a5f9
--- /dev/null
+++ b/internal/console/securityheaders_test.go
@@ -0,0 +1,55 @@
+package console
+
+import (
+ "net/http"
+ "net/http/httptest"
+ "testing"
+)
+
+func TestBrowserSecurityHeadersAcrossResponses(t *testing.T) {
+ srv := newRedirectFixture(t, "https://console.example.test", []string{"dashboard.example.test"})
+ for _, tc := range []struct {
+ name, method, host, path string
+ status int
+ }{
+ {"success", "GET", "console.example.test", "/healthz", 200},
+ {"authentication refusal", "GET", "console.example.test", "/auth/cli/whoami", 401},
+ {"missing asset", "GET", "console.example.test", "/static/unknown/missing.js", 404},
+ {"redirect", "GET", "dashboard.example.test", "/healthz", 301},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ rec := serveRedirect(t, srv, tc.method, tc.host, tc.path)
+ if rec.Code != tc.status {
+ t.Fatalf("status = %d, want %d", rec.Code, tc.status)
+ }
+ for name, want := range map[string]string{
+ "Content-Security-Policy": "frame-ancestors 'none'; object-src 'none'; base-uri 'self'",
+ "X-Frame-Options": "DENY",
+ "X-Content-Type-Options": "nosniff",
+ "Referrer-Policy": "strict-origin-when-cross-origin",
+ "Strict-Transport-Security": "max-age=86400",
+ } {
+ if got := rec.Header().Get(name); got != want {
+ t.Errorf("%s = %q, want %q", name, got, want)
+ }
+ }
+ })
+ }
+}
+
+func TestBrowserSecurityHeadersHTTPOriginDoesNotEnableHSTS(t *testing.T) {
+ srv := newRedirectFixture(t, "http://localhost:8080", nil)
+ req := httptest.NewRequest(http.MethodGet, "/healthz", nil)
+ req.Header.Set("X-Forwarded-Proto", "https")
+ rec := httptest.NewRecorder()
+ srv.ServeHTTP(rec, req)
+ if rec.Code != http.StatusOK {
+ t.Fatalf("status = %d", rec.Code)
+ }
+ if got := rec.Header().Get("Strict-Transport-Security"); got != "" {
+ t.Fatalf("HTTP development origin received HSTS: %q", got)
+ }
+ if got := rec.Header().Get("X-Frame-Options"); got != "DENY" {
+ t.Fatalf("frame denial = %q", got)
+ }
+}
diff --git a/internal/console/server.go b/internal/console/server.go
index 40786de4c..0f1c43eb0 100644
--- a/internal/console/server.go
+++ b/internal/console/server.go
@@ -2087,6 +2087,7 @@ func (s *Server) geoipPass(ctx context.Context) {
// ordering rule concerns account-existence leaks; a host-level redirect
// reveals nothing).
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
+ s.browserSecurityHeaders(w.Header())
if s.redirects[normalizeHost(r.Host)] {
code := http.StatusMovedPermanently
if r.Method != http.MethodGet && r.Method != http.MethodHead {
diff --git a/internal/demobuild/budget.go b/internal/demobuild/budget.go
new file mode 100644
index 000000000..f30ebc63d
--- /dev/null
+++ b/internal/demobuild/budget.go
@@ -0,0 +1,143 @@
+package demobuild
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "os"
+ "path/filepath"
+ "strconv"
+ "strings"
+ "time"
+
+ "github.com/carlosframework/platform/internal/execsandbox"
+)
+
+// budgetSlice holds every native and gVisor build unit.
+const budgetSlice = "carlos-demo-builds.slice"
+
+// errBudgetPending marks a deferral: the budget change waits for running
+// work. Build retries it until the job's deadline (budgetRetry apart); every
+// other ErrBuild stays a build failure.
+var errBudgetPending = errors.New("build budget change pending")
+
+// budgetRetry is how long Build waits between admission attempts while a
+// budget change is pending.
+var budgetRetry = 2 * time.Second
+
+// reconcileBudget runs before a build is admitted. It is the only place a
+// build budget reaches the kernel after the slice was first started.
+//
+// systemd sets a slice's cgroup limits when the slice starts. daemon-reload
+// after the adopt pass re-renders the unit (a sandbox switch, a concurrency
+// change) updates systemd's view only, and the running slice keeps its old
+// limits (root-runner witness, systemd 257). So, when the kernel limits
+// differ from the rendered budget:
+// - with builds, snapshots or purges running, or anything left in the
+// slice, the build is deferred (ErrBuild, retryable): a running build
+// never has its budget changed under it;
+// - otherwise the empty slice is stopped, and the next build unit starts
+// it again on the budget systemd now has loaded.
+//
+// A slice whose loaded configuration is itself stale (no adopt pass since
+// host.env changed) fails assertBudget first and is left alone: stopping it
+// would only restart it on the same stale budget.
+func (w *Worker) reconcileBudget(ctx context.Context) error {
+ if err := w.assertBudget(ctx); err != nil {
+ return err
+ }
+ n, family := cap(w.slots), w.SandboxFamily()
+ if ok, err := kernelBudgetMatches(n, family); err != nil || ok {
+ return err
+ }
+ // Builds hold buildPurge for reading; snapshots and purges hold it
+ // outright. Holding it here means none of them is in flight in this
+ // process, and processLock means no other worker process exists.
+ if !w.buildPurge.TryLock() {
+ return fmt.Errorf("%w: %w: waits for running builds", ErrBuild, errBudgetPending)
+ }
+ defer w.buildPurge.Unlock()
+ if ok, err := kernelBudgetMatches(n, family); err != nil || ok {
+ return err
+ }
+ populated, err := budgetSlicePopulated()
+ if err != nil {
+ return err
+ }
+ if populated {
+ return fmt.Errorf("%w: %w: waits for an empty build slice", ErrBuild, errBudgetPending)
+ }
+ jobs, err := systemctl(ctx, "list-jobs", "--no-legend", "--no-pager")
+ if err != nil {
+ return err
+ }
+ // Absence needs the whole job list: one the capture may have cut at its
+ // limit could hide a queued build start, so it defers like a busy slice.
+ if len(jobs) >= systemctlCaptureLimit {
+ return fmt.Errorf("%w: %w: job list too long to prove nothing is queued", ErrBuild, errBudgetPending)
+ }
+ for _, line := range strings.Split(jobs, "\n") {
+ if f := strings.Fields(line); len(f) >= 2 && (f[1] == budgetSlice || strings.HasPrefix(f[1], "carlos-demo-build@") || strings.HasPrefix(f[1], "carlos-demo-build-gvisor@")) {
+ return fmt.Errorf("%w: %w: waits for queued %s", ErrBuild, errBudgetPending, f[1])
+ }
+ }
+ if _, err := systemctl(ctx, "stop", budgetSlice); err != nil {
+ return err
+ }
+ out, err := systemctl(ctx, "show", budgetSlice, "-p", "ActiveState")
+ if err != nil {
+ return err
+ }
+ if state := showProperties(out)["ActiveState"]; state != "inactive" {
+ return fmt.Errorf("%w: build slice %s after stop", ErrBuild, state)
+ }
+ return nil
+}
+
+// kernelBudgetMatches compares the build slice's cgroup limits with the
+// budget for n slots of family. No cgroup (the slice is not running) is a
+// match: the next start applies whatever systemd has loaded.
+func kernelBudgetMatches(n int, family execsandbox.Family) (bool, error) {
+ p := SlicePropertiesFor(n, family)
+ if p == nil {
+ return false, ErrBuild
+ }
+ if _, err := os.Lstat(buildCgroupRoot); errors.Is(err, os.ErrNotExist) {
+ return true, nil
+ } else if err != nil {
+ return false, err
+ }
+ want := map[string]string{
+ "memory.max": strconv.FormatInt(p["MemoryMax"], 10),
+ "memory.swap.max": "0",
+ "pids.max": strconv.FormatInt(p["TasksMax"], 10),
+ "cpu.max": strconv.FormatInt(p["CPUQuota"]*1000, 10) + " 100000",
+ }
+ for name, value := range want {
+ b, err := os.ReadFile(filepath.Join(buildCgroupRoot, name))
+ if err != nil {
+ return false, err
+ }
+ if strings.TrimSpace(string(b)) != value {
+ return false, nil
+ }
+ }
+ return true, nil
+}
+
+// budgetSlicePopulated reads the slice's cgroup.events. No cgroup is empty.
+func budgetSlicePopulated() (bool, error) {
+ b, err := os.ReadFile(filepath.Join(buildCgroupRoot, "cgroup.events"))
+ if errors.Is(err, os.ErrNotExist) {
+ return false, nil
+ }
+ if err != nil {
+ return false, err
+ }
+ for _, line := range strings.Split(string(b), "\n") {
+ if f := strings.Fields(line); len(f) == 2 && f[0] == "populated" {
+ return f[1] != "0", nil
+ }
+ }
+ return false, fmt.Errorf("%w: build slice cgroup.events has no populated line", ErrBuild)
+}
diff --git a/internal/demobuild/budget_rootrunner_linux_test.go b/internal/demobuild/budget_rootrunner_linux_test.go
new file mode 100644
index 000000000..a3b6bdcc6
--- /dev/null
+++ b/internal/demobuild/budget_rootrunner_linux_test.go
@@ -0,0 +1,146 @@
+//go:build linux && rootrunner
+
+package demobuild
+
+import (
+ "context"
+ "errors"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "strconv"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/execsandbox"
+)
+
+// TestRootBuildBudgetReconcile: on real systemd, the build worker's
+// reconciler brings an active build slice with a stale kernel budget to the
+// loaded one, in both directions of a sandbox switch. It defers (retryable
+// DEMO-BUILD) while anything runs in the slice and never touches a running
+// one; once the slice is empty it stops it, and the next unit in the slice
+// starts it on the new budget.
+func TestRootBuildBudgetReconcile(t *testing.T) {
+ if os.Geteuid() != 0 {
+ t.Fatal("needs root")
+ }
+ if _, err := os.Lstat(filepath.Join("/etc/systemd/system", budgetSlice)); err == nil {
+ t.Fatal("refusing: a real build slice is installed here")
+ }
+ unitPath := filepath.Join("/run/systemd/system", budgetSlice)
+ run := func(args ...string) string {
+ t.Helper()
+ out, err := exec.Command(args[0], args[1:]...).CombinedOutput()
+ if err != nil {
+ t.Fatalf("%v: %v: %s", args, err, out)
+ }
+ return strings.TrimSpace(string(out))
+ }
+ install := func(family execsandbox.Family) {
+ t.Helper()
+ p := SlicePropertiesFor(1, family)
+ body := "[Unit]\nDescription=carlos offline demo build budget\n\n[Slice]\nMemoryMax=" + strconv.FormatInt(p["MemoryMax"], 10) + "\nMemorySwapMax=0\nTasksMax=" + strconv.FormatInt(p["TasksMax"], 10) + "\nCPUQuota=" + strconv.FormatInt(p["CPUQuota"], 10) + "%\nCPUWeight=10\n"
+ if err := os.WriteFile(unitPath, []byte(body), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ run("systemctl", "daemon-reload")
+ }
+ const sleeper = "carlos-rr-build-sleeper"
+ startSleeper := func() {
+ t.Helper()
+ run("systemd-run", "--unit="+sleeper, "--slice="+budgetSlice, "--property=Type=exec", "/bin/sleep", "600")
+ time.Sleep(500 * time.Millisecond)
+ }
+ stopSleeper := func() {
+ t.Helper()
+ run("systemctl", "stop", sleeper+".service")
+ time.Sleep(500 * time.Millisecond)
+ }
+ kernel := func() string {
+ t.Helper()
+ var parts []string
+ for _, f := range []string{"memory.max", "memory.swap.max", "pids.max", "cpu.max"} {
+ b, err := os.ReadFile(filepath.Join(buildCgroupRoot, f))
+ if err != nil {
+ t.Fatalf("%s: %v", f, err)
+ }
+ parts = append(parts, f+"="+strings.TrimSpace(string(b)))
+ }
+ return strings.Join(parts, " ")
+ }
+ t.Cleanup(func() {
+ _ = exec.Command("systemctl", "stop", sleeper+".service", budgetSlice).Run()
+ _ = os.Remove(unitPath)
+ _ = exec.Command("systemctl", "daemon-reload").Run()
+ })
+ ctx := context.Background()
+
+ install(execsandbox.FamilySystemd)
+ startSleeper()
+ if ok, err := kernelBudgetMatches(1, execsandbox.FamilySystemd); err != nil || !ok {
+ t.Fatalf("baseline: %v %v (%s)", ok, err, kernel())
+ }
+ for _, step := range []struct{ from, to execsandbox.Family }{
+ {execsandbox.FamilySystemd, execsandbox.FamilyGVisor},
+ {execsandbox.FamilyGVisor, execsandbox.FamilySystemd},
+ } {
+ w := &Worker{family: step.to, slots: make(chan struct{}, 1)}
+ install(step.to) // the adopt pass: file + daemon-reload
+ before := kernel()
+ t.Logf("%s -> %s, after reload only: %s", step.from, step.to, before)
+ if ok, _ := kernelBudgetMatches(1, step.to); ok {
+ t.Fatalf("reload alone moved the kernel budget; the witness premise is gone: %s", before)
+ }
+
+ // A build (here the sleeper) still runs in the slice: defer.
+ err := w.reconcileBudget(ctx)
+ if !errors.Is(err, ErrBuild) {
+ t.Fatalf("busy slice: want a DEMO-BUILD deferral, got %v", err)
+ }
+ if kernel() != before || run("systemctl", "is-active", sleeper+".service") != "active" {
+ t.Fatalf("busy slice was touched: %s", kernel())
+ }
+ t.Logf("busy slice deferred: %v", err)
+
+ // The slice empties. systemd may re-apply the loaded budget itself
+ // when the last unit leaves (seen on 257); either way the
+ // reconciler must leave the slice on the loaded budget.
+ stopSleeper()
+ ok, _ := kernelBudgetMatches(1, step.to)
+ t.Logf("slice emptied: kernel %s (already on the new budget: %v)", kernel(), ok)
+ if err := w.reconcileBudget(ctx); err != nil {
+ t.Fatalf("empty slice: %v", err)
+ }
+ // The stop branch on real systemd: an empty, active slice whose
+ // kernel limits are stale (the state the reload left on the box).
+ startSleeper()
+ stopSleeper()
+ old := SlicePropertiesFor(1, step.from)
+ for name, v := range map[string]string{"memory.max": strconv.FormatInt(old["MemoryMax"], 10), "pids.max": strconv.FormatInt(old["TasksMax"], 10)} {
+ if err := os.WriteFile(filepath.Join(buildCgroupRoot, name), []byte(v), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if ok, _ := kernelBudgetMatches(1, step.to); ok {
+ t.Fatalf("could not stage stale limits: %s", kernel())
+ }
+ if err := w.reconcileBudget(ctx); err != nil {
+ t.Fatalf("empty stale slice: %v", err)
+ }
+ if out, _ := exec.Command("systemctl", "is-active", budgetSlice).CombinedOutput(); strings.TrimSpace(string(out)) != "inactive" {
+ t.Fatalf("empty stale slice not stopped: %s", out)
+ }
+ t.Logf("empty stale slice stopped")
+ startSleeper()
+ if ok, err := kernelBudgetMatches(1, step.to); err != nil || !ok {
+ t.Fatalf("restarted slice: %v %v (%s)", ok, err, kernel())
+ }
+ t.Logf("restarted on the %s budget: %s", step.to, kernel())
+ // Converged: a further admission check changes nothing.
+ if err := w.reconcileBudget(ctx); err != nil || run("systemctl", "is-active", sleeper+".service") != "active" {
+ t.Fatalf("converged slice: %v", err)
+ }
+ }
+}
diff --git a/internal/demobuild/budget_test.go b/internal/demobuild/budget_test.go
new file mode 100644
index 000000000..ef4c07e7e
--- /dev/null
+++ b/internal/demobuild/budget_test.go
@@ -0,0 +1,190 @@
+package demobuild
+
+import (
+ "bytes"
+ "context"
+ "errors"
+ "fmt"
+ "os"
+ "path/filepath"
+ "strconv"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/execsandbox"
+)
+
+// budgetFixture: a worker with one slot in family, a fake build slice cgroup
+// holding kernel limits for kernelFamily, and a fake systemctl whose loaded
+// budget is the rendered one for loadedFamily.
+type budgetFixture struct {
+ w *Worker
+ calls []string
+ jobs string
+ active string
+ stopErr error
+}
+
+func newBudgetFixture(t *testing.T, family, loadedFamily execsandbox.Family, kernelFamily execsandbox.Family, populated bool) *budgetFixture {
+ t.Helper()
+ f := &budgetFixture{active: "inactive"}
+ f.w = &Worker{family: family, slots: make(chan struct{}, 1)}
+ oldRoot, oldCtl := buildCgroupRoot, systemctl
+ t.Cleanup(func() { buildCgroupRoot, systemctl = oldRoot, oldCtl })
+ buildCgroupRoot = filepath.Join(t.TempDir(), "carlos-demo-builds.slice")
+ if kernelFamily != "" {
+ if err := os.MkdirAll(buildCgroupRoot, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ k := SlicePropertiesFor(1, kernelFamily)
+ pop := "0"
+ if populated {
+ pop = "1"
+ }
+ for name, v := range map[string]string{
+ "memory.max": strconv.FormatInt(k["MemoryMax"], 10), "memory.swap.max": "0",
+ "pids.max": strconv.FormatInt(k["TasksMax"], 10), "cpu.max": "50000 100000",
+ "cgroup.events": "populated " + pop + "\nfrozen 0\n",
+ } {
+ if err := os.WriteFile(filepath.Join(buildCgroupRoot, name), []byte(v+"\n"), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ }
+ }
+ loaded := SlicePropertiesFor(1, loadedFamily)
+ systemctl = func(_ context.Context, args ...string) (string, error) {
+ f.calls = append(f.calls, strings.Join(args, " "))
+ switch {
+ case args[0] == "show" && strings.Contains(strings.Join(args, " "), "MemoryMax"):
+ return "MemoryMax=" + strconv.FormatInt(loaded["MemoryMax"], 10) + "\nMemorySwapMax=0\nTasksMax=" + strconv.FormatInt(loaded["TasksMax"], 10) + "\nCPUQuotaPerSecUSec=500ms\n", nil
+ case args[0] == "show":
+ return "ActiveState=" + f.active + "\n", nil
+ case args[0] == "list-jobs":
+ return f.jobs, nil
+ case args[0] == "stop":
+ if f.stopErr != nil {
+ return "", f.stopErr
+ }
+ // Stopping the slice removes its cgroup.
+ if err := os.RemoveAll(buildCgroupRoot); err != nil {
+ t.Fatal(err)
+ }
+ }
+ return "", nil
+ }
+ return f
+}
+
+func (f *budgetFixture) stopped() bool {
+ for _, c := range f.calls {
+ if c == "stop "+budgetSlice {
+ return true
+ }
+ }
+ return false
+}
+
+func TestReconcileBudget(t *testing.T) {
+ gv, sd := execsandbox.FamilyGVisor, execsandbox.FamilySystemd
+ for _, tc := range []struct {
+ name string
+ family, loaded, kn execsandbox.Family
+ populated, busy bool
+ jobs string
+ active string
+ stopErr error
+ wantErr, wantStop bool
+ }{
+ {name: "kernel matches", family: gv, loaded: gv, kn: gv},
+ {name: "slice not running", family: gv, loaded: gv},
+ {name: "stale kernel, empty slice is stopped", family: gv, loaded: gv, kn: sd, wantStop: true},
+ {name: "stale kernel back to systemd", family: sd, loaded: sd, kn: gv, wantStop: true},
+ {name: "stale config is left for adopt", family: gv, loaded: sd, kn: sd, wantErr: true},
+ {name: "builds running defer", family: gv, loaded: gv, kn: sd, busy: true, wantErr: true},
+ {name: "populated slice defers", family: gv, loaded: gv, kn: sd, populated: true, wantErr: true},
+ {name: "queued build defers", family: gv, loaded: gv, kn: sd, jobs: "12 carlos-demo-build@aa_1.service start waiting\n", wantErr: true},
+ {name: "queued slice job defers", family: gv, loaded: gv, kn: sd, jobs: "13 carlos-demo-builds.slice stop running\n", wantErr: true},
+ {name: "truncated job list defers", family: gv, loaded: gv, kn: sd, jobs: strings.Repeat("1 other.service start waiting\n", systemctlCaptureLimit/30+1), wantErr: true},
+ {name: "stop fails", family: gv, loaded: gv, kn: sd, stopErr: errors.New("bus"), wantErr: true, wantStop: true},
+ {name: "still active after stop", family: gv, loaded: gv, kn: sd, active: "active", wantErr: true, wantStop: true},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ f := newBudgetFixture(t, tc.family, tc.loaded, tc.kn, tc.populated)
+ f.jobs, f.stopErr = tc.jobs, tc.stopErr
+ if tc.active != "" {
+ f.active = tc.active
+ }
+ if tc.busy {
+ f.w.buildPurge.RLock()
+ defer f.w.buildPurge.RUnlock()
+ }
+ err := f.w.reconcileBudget(context.Background())
+ if (err != nil) != tc.wantErr {
+ t.Fatalf("err %v, calls %v", err, f.calls)
+ }
+ if tc.wantErr && !errors.Is(err, ErrBuild) && tc.stopErr == nil {
+ t.Fatalf("a deferral must be a retryable DEMO-BUILD: %v", err)
+ }
+ pending := tc.busy || tc.populated || tc.jobs != ""
+ if errors.Is(err, errBudgetPending) != pending {
+ t.Fatalf("pending=%v for %v", errors.Is(err, errBudgetPending), err)
+ }
+ if f.stopped() != tc.wantStop {
+ t.Fatalf("stopped=%v, calls %v", f.stopped(), f.calls)
+ }
+ if !tc.wantStop && tc.stopErr == nil {
+ for _, c := range f.calls {
+ if strings.HasPrefix(c, "stop") || strings.HasPrefix(c, "set-property") {
+ t.Fatalf("changed the slice: %v", f.calls)
+ }
+ }
+ }
+ })
+ }
+}
+
+// A pending budget change keeps the job waiting, not failed: Build retries
+// admission until the job's deadline. Any other admission error fails at once.
+func TestBuildWaitsOutPendingBudget(t *testing.T) {
+ old := budgetRetry
+ budgetRetry = 5 * time.Millisecond
+ t.Cleanup(func() { budgetRetry = old })
+ pending := fmt.Errorf("%w: %w: test", ErrBuild, errBudgetPending)
+
+ w, j, priv, src := workerFixture(t)
+ tries := 0
+ w.admit = func(context.Context) error {
+ if tries++; tries < 3 {
+ return pending
+ }
+ return nil
+ }
+ ran := false
+ w.run = func(context.Context, string, Lock) (BuildOutput, error) { ran = true; return BuildOutput{}, nil }
+ wire, _ := SignJob(priv, j)
+ if _, err := w.Build(context.Background(), wire, bytes.NewReader(src)); err != nil || !ran || tries != 3 {
+ t.Fatalf("err=%v ran=%v tries=%d", err, ran, tries)
+ }
+
+ w, j, priv, src = workerFixture(t)
+ w.admit = func(context.Context) error { return pending }
+ w.run = func(context.Context, string, Lock) (BuildOutput, error) {
+ t.Fatal("ran while pending")
+ return BuildOutput{}, nil
+ }
+ wire, _ = SignJob(priv, j)
+ ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)
+ defer cancel()
+ if _, err := w.Build(ctx, wire, bytes.NewReader(src)); !errors.Is(err, errBudgetPending) {
+ t.Fatalf("a budget still pending at the deadline: %v", err)
+ }
+
+ w, j, priv, src = workerFixture(t)
+ calls := 0
+ w.admit = func(context.Context) error { calls++; return ErrBuild }
+ wire, _ = SignJob(priv, j)
+ if _, err := w.Build(context.Background(), wire, bytes.NewReader(src)); !errors.Is(err, ErrBuild) || calls != 1 {
+ t.Fatalf("a real admission failure must not retry: %v after %d", err, calls)
+ }
+}
diff --git a/internal/demobuild/worker.go b/internal/demobuild/worker.go
index e6b531f97..29c3c4cf2 100644
--- a/internal/demobuild/worker.go
+++ b/internal/demobuild/worker.go
@@ -44,12 +44,16 @@ type Worker struct {
proof func(context.Context) error
prepare func(context.Context, string, Source) (func() error, error)
run func(context.Context, string, Lock) (BuildOutput, error)
- processLock *os.File
- mu sync.Mutex
- poisoned bool
- ready bool
- initMu sync.Mutex
- initDone bool
+ // admit runs before a build is admitted; nil is reconcileBudget, the
+ // production check. Unit tests that stand in prepare and run stand this
+ // in too.
+ admit func(context.Context) error
+ processLock *os.File
+ mu sync.Mutex
+ poisoned bool
+ ready bool
+ initMu sync.Mutex
+ initDone bool
snapshotPoisoned bool
}
@@ -209,10 +213,32 @@ func (w *Worker) Build(ctx context.Context, wire []byte, source io.Reader) (out
if err != nil {
return out, err
}
- w.buildPurge.RLock()
- defer w.buildPurge.RUnlock()
+ // Before admission: a budget the kernel does not have yet reaches the
+ // slice only while nothing runs in it (budget.go).
ctx, cancel := context.WithDeadline(ctx, j.Deadline)
defer cancel()
+ admit := w.admit
+ if admit == nil {
+ admit = w.reconcileBudget
+ }
+ // A pending budget change waits for running work to finish; the job
+ // keeps its place until its own deadline rather than failing.
+ for {
+ err := admit(ctx)
+ if err == nil {
+ break
+ }
+ if !errors.Is(err, errBudgetPending) {
+ return out, err
+ }
+ select {
+ case <-ctx.Done():
+ return out, err
+ case <-time.After(budgetRetry):
+ }
+ }
+ w.buildPurge.RLock()
+ defer w.buildPurge.RUnlock()
select {
case w.slots <- struct{}{}:
defer func() { <-w.slots }()
diff --git a/internal/demobuild/worker_test.go b/internal/demobuild/worker_test.go
index 45890f632..e0cc2ba04 100644
--- a/internal/demobuild/worker_test.go
+++ b/internal/demobuild/worker_test.go
@@ -31,7 +31,7 @@ func workerFixture(t *testing.T) (*Worker, Job, ed25519.PrivateKey, []byte) {
if err != nil {
t.Fatal(err)
}
- w := &Worker{removeSandbox: func(string) error { return nil }, ready: true, cfg: demo.Config{Account: "shop", Fleet: "demo", Domain: "example.com", BuildConcurrency: 1}, box: "box-1", pub: pub, lock: testLock(t), digest: strings.Repeat("b", 64), root: t.TempDir(), slots: make(chan struct{}, 1), proof: func(context.Context) error { return nil }}
+ w := &Worker{removeSandbox: func(string) error { return nil }, ready: true, cfg: demo.Config{Account: "shop", Fleet: "demo", Domain: "example.com", BuildConcurrency: 1}, box: "box-1", pub: pub, lock: testLock(t), digest: strings.Repeat("b", 64), root: t.TempDir(), slots: make(chan struct{}, 1), proof: func(context.Context) error { return nil }, admit: func(context.Context) error { return nil }}
w.prepare = func(context.Context, string, Source) (func() error, error) { return func() error { return nil }, nil }
w.run = func(context.Context, string, Lock) (BuildOutput, error) { return BuildOutput{}, nil }
j := Job{ID: base64.RawURLEncoding.EncodeToString(bytes.Repeat([]byte{1}, 32)), DemoID: base64.RawURLEncoding.EncodeToString(bytes.Repeat([]byte{2}, 16)), Account: "shop", App: "tmp-demo-bright-otter-42", Host: "bright-otter-42.example.com", Lifetime: "life-1", Fleet: "demo", Box: "box-1", SourceSHA256: v.SHA256, BundleSHA256: w.digest, Generation: 1, Attempt: 1, Deadline: time.Now().UTC().Add(time.Minute)}
@@ -142,7 +142,7 @@ func TestDemoBuildSlotsAndReplay(t *testing.T) {
t.Fatal("replayed completed attempt")
}
// A new process reads the same durable marker before it opens source.
- w2 := &Worker{ready: true, cfg: w.cfg, box: w.box, pub: w.pub, lock: w.lock, digest: w.digest, root: w.root, slots: make(chan struct{}, 1), proof: w.proof, prepare: w.prepare, run: w.run}
+ w2 := &Worker{ready: true, cfg: w.cfg, box: w.box, pub: w.pub, lock: w.lock, digest: w.digest, root: w.root, slots: make(chan struct{}, 1), proof: w.proof, prepare: w.prepare, run: w.run, admit: w.admit}
if _, err := w2.Build(context.Background(), wire, neverRead{t}); err == nil {
t.Fatal("replayed after root restart")
}
diff --git a/internal/host/agent.go b/internal/host/agent.go
index ad62edf2b..60fca0784 100644
--- a/internal/host/agent.go
+++ b/internal/host/agent.go
@@ -630,6 +630,9 @@ func runAgent(args []string, buildClaims ClaimFactory) {
log.Printf("agent: %v (nested wakes and the layout pass refuse until the unit is fixed)", err)
}
eb.NestedOK = nestedGate(selfCheck, instancefs.MountNoSymfollow, eb.Control.Ready)
+ // A new always-on binary row at the flat paths starts as an exec
+ // child only on a box that chose flat (ExecBackend.FlatLayoutChosen).
+ eb.FlatLayoutChosen = flatLayoutChosen
// CARLOS_SWAP=overlap turns on generations (plan 1), and with them
// plan 3's Swap, before the Service exists, which reads the switch
// once in New. Plan 2's per-generation containment goes on with
diff --git a/internal/host/agent_layout_test.go b/internal/host/agent_layout_test.go
index b354e7861..fb3800c00 100644
--- a/internal/host/agent_layout_test.go
+++ b/internal/host/agent_layout_test.go
@@ -985,9 +985,12 @@ func TestLayoutLegUsesTheDefaultWhenNoIntentIsRecorded(t *testing.T) {
}
// Startup recovery and the reconciler's mint read the same default: with
-// no intent and a ready box both answer nested; with no intent and a box
-// that is not ready both answer none; CARLOS_LAYOUT_DEFAULT=flat answers
-// none on a ready box.
+// no intent and a ready box both answer nested; with no intent and an
+// armed box whose gate is not ready startup answers unreadable and the
+// mint answers nested (the wake gate waits, the tenant is never flat);
+// a box that cannot wake nested (no activator, below the floor) mints
+// flat unless a managed nested sibling proves the box has moved;
+// CARLOS_LAYOUT_DEFAULT=flat answers none on a ready box.
func TestStartupAndMintReadTheDefault(t *testing.T) {
resetLayoutGlobals(t)
t.Setenv(layoutDefaultEnv, "")
@@ -1011,16 +1014,29 @@ func TestStartupAndMintReadTheDefault(t *testing.T) {
if got := startupLayoutIntent(ctx, s, nil, "kass-1"); got != layout.IntentUnreadable {
t.Fatalf("startup, gate ready = %q, want unreadable: startup does not trust the gate", got)
}
- // The mint asks the gate; not ready is flat...
+ // The mint asks the gate; an armed box whose gate is not ready (or
+ // has not answered yet) still mints nested: the gate guards the wake,
+ // and a flat mint would be the implicit downgrade the default forbids.
armDefaultGate(t, errors.New("not yet run"))
+ if mode, err := mintLayoutIntent(ctx, s); err != nil || mode != release.LayoutModeNested {
+ t.Fatalf("mint, armed and not ready = %q %v, want nested", mode, err)
+ }
+ // A box that can never wake nested mints flat: no activator armed, or a
+ // release below the floor...
+ t.Setenv("CARLOS_DATA_DIR", "/data")
+ layoutDefaultGate.Store(nil)
+ if mode, err := mintLayoutIntent(ctx, s); err != nil || mode != "" {
+ t.Fatalf("mint, no activator = %q %v, want none", mode, err)
+ }
+ armDefaultGate(t, errors.New("not yet run"))
+ layoutBuild = func() string { return "v0.24.2" }
if mode, err := mintLayoutIntent(ctx, s); err != nil || mode != "" {
- t.Fatalf("mint, not ready = %q %v, want none", mode, err)
+ t.Fatalf("mint, below the floor = %q %v, want none", mode, err)
}
// ...unless the box already holds an activator-managed nested row,
- // which is proof it has moved: a fresh row beside it is minted nested
- // before the gate's first answer. A nested row that is not managed,
- // or flat rows, are not that proof.
- t.Setenv("CARLOS_DATA_DIR", "/data")
+ // which is proof it has moved: a fresh row beside it is minted nested.
+ // A nested row that is not managed, or flat rows, are not that proof.
+ layoutDefaultGate.Store(nil)
nestedManaged := registry.Route{Host: "a.example.com", Kind: "instance", Hibernate: true, DBPath: provision.NestedDBPath("/data", "a.example.com"), Socket: provision.NestedSocket("a.example.com")}
nestedUnflagged := registry.Route{Host: "u.example.com", Kind: "instance", DBPath: provision.NestedDBPath("/data", "u.example.com"), Socket: provision.NestedSocket("u.example.com")}
flat := registry.Route{Host: "f.example.com", Kind: "instance", Hibernate: true, DBPath: provision.DefaultDBPath("/data", "f.example.com"), Socket: provision.DefaultSocket("f.example.com")}
@@ -1028,14 +1044,20 @@ func TestStartupAndMintReadTheDefault(t *testing.T) {
return func() ([]registry.Route, error) { return rs, nil }
}
if mode, err := mintLayoutIntentWith(ctx, s, rows(flat, nestedUnflagged)); err != nil || mode != "" {
- t.Fatalf("mint, not ready, no managed nested row = %q %v, want none", mode, err)
+ t.Fatalf("mint, no activator, no managed nested row = %q %v, want none", mode, err)
}
if mode, err := mintLayoutIntentWith(ctx, s, rows(flat, nestedManaged)); err != nil || mode != release.LayoutModeNested {
- t.Fatalf("mint, not ready, a managed nested row = %q %v, want nested", mode, err)
+ t.Fatalf("mint, no activator, a managed nested row = %q %v, want nested", mode, err)
}
if _, err := mintLayoutIntentWith(ctx, s, func() ([]registry.Route, error) { return nil, errors.New("registry locked") }); err == nil {
t.Fatal("a registry that cannot be listed must defer the mint, not guess")
}
+ // An armed box short of ready never asks the registry: nested outright.
+ layoutBuild = func() string { return "v0.25.0" }
+ armDefaultGate(t, errors.New("not yet run"))
+ if mode, err := mintLayoutIntentWith(ctx, s, func() ([]registry.Route, error) { return nil, errors.New("registry locked") }); err != nil || mode != release.LayoutModeNested {
+ t.Fatalf("mint, armed and not ready, registry locked = %q %v, want nested without a listing", mode, err)
+ }
armDefaultGate(t, nil)
if mode, err := mintLayoutIntent(ctx, s); err != nil || mode != release.LayoutModeNested {
t.Fatalf("mint, ready = %q %v, want nested", mode, err)
@@ -1127,3 +1149,29 @@ func TestLayoutLegRetriesWhileTheDefaultIsBlocked(t *testing.T) {
t.Fatal("a typo waits on nothing")
}
}
+
+// flatLayoutChosen, the activator's FlatLayoutChosen: true only for a
+// recorded flat intent, or no recorded intent (none, the same value as
+// nothing read yet) under CARLOS_LAYOUT_DEFAULT=flat. A nested-default box that is not ready
+// (none), nested, unreadable and an invalid default all answer false.
+func TestFlatLayoutChosen(t *testing.T) {
+ resetLayoutGlobals(t)
+ for _, tc := range []struct {
+ seen, env string
+ want bool
+ }{
+ {release.LayoutModeNone, "", false},
+ {release.LayoutModeNone, "flat", true},
+ {release.LayoutModeNone, "nestd", false},
+ {release.LayoutModeFlat, "", true},
+ {release.LayoutModeFlat, "nested", true},
+ {release.LayoutModeNested, "flat", false},
+ {string(layout.IntentUnreadable), "flat", false},
+ } {
+ t.Setenv(layoutDefaultEnv, tc.env)
+ noteLayoutIntent(tc.seen)
+ if got := flatLayoutChosen(); got != tc.want {
+ t.Errorf("seen %q env %q: flatLayoutChosen = %v, want %v", tc.seen, tc.env, got, tc.want)
+ }
+ }
+}
diff --git a/internal/host/demo_slice_adopt_linux_test.go b/internal/host/demo_slice_adopt_linux_test.go
new file mode 100644
index 000000000..0fcefa7bc
--- /dev/null
+++ b/internal/host/demo_slice_adopt_linux_test.go
@@ -0,0 +1,172 @@
+package host
+
+import (
+ "errors"
+ "os"
+ "path/filepath"
+ "slices"
+ "strconv"
+ "strings"
+ "testing"
+
+ "github.com/carlosframework/platform/internal/demobuild"
+ "github.com/carlosframework/platform/internal/execsandbox"
+)
+
+// A demo build box switched from systemd to gVisor in host.env changes no
+// unit but the build budget slice. One adopt pass must re-render it and
+// reload systemd; before this, the pass returned as already armed and every
+// gVisor build refused at its budget check (v0.34.35 dev witness).
+func TestAdoptRerendersDemoBuildSliceOnSandboxFlip(t *testing.T) {
+ root := t.TempDir()
+ etc, opt := filepath.Join(root, "etc"), filepath.Join(root, "opt/carlos")
+ unitDir := filepath.Join(etc, "systemd/system")
+ for _, dir := range []string{unitDir, filepath.Join(etc, "carlos")} {
+ if err := os.MkdirAll(dir, 0755); err != nil {
+ t.Fatal(err)
+ }
+ }
+ const demoEnv = "CARLOS_DEMO_BOX=1\nCARLOS_DEMO_ACCOUNT=shop\nCARLOS_DEMO_FLEET=demo\nCARLOS_DEMO_DOMAIN=example.com\nCARLOS_DEMO_BUILD_WORKER=1\nCARLOS_DEMO_BUILD_CONCURRENCY=1\nCARLOS_DEMO_TOOLCHAIN_DIR=/opt/demo-toolchain\n"
+ envPath := filepath.Join(etc, "carlos/host.env")
+ writeEnv := func(mode string) {
+ t.Helper()
+ if err := os.WriteFile(envPath, []byte("CARLOS_EXEC_SANDBOX="+mode+"\n"+demoEnv), 0600); err != nil {
+ t.Fatal(err)
+ }
+ }
+ writeEnv("systemd")
+ settings, err := readClaimUnitSettings(envPath)
+ if err != nil || !settings.demo.BuildWorker {
+ t.Fatalf("settings: %+v %v", settings, err)
+ }
+ // An armed systemd-mode box: every unit as this build renders it.
+ for _, name := range systemUnitFiles {
+ raw, err := unitsFS.ReadFile("units/" + name)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filepath.Join(unitDir, name), claimUnitContent(name, raw, settings), 0644); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if _, err := installDemoUnitsIn(unitDir, settings.demo); err != nil {
+ t.Fatal(err)
+ }
+ // systemd's loaded view of the slice: what the last successful
+ // daemon-reload read from the file.
+ var loaded string
+ slicePath := filepath.Join(unitDir, demoBuildsSlice)
+ load := func() {
+ b, err := os.ReadFile(slicePath)
+ if err != nil {
+ t.Fatal(err)
+ }
+ loaded = ""
+ for _, line := range strings.Split(string(b), "\n") {
+ if strings.HasPrefix(line, "MemoryMax=") || strings.HasPrefix(line, "TasksMax=") {
+ loaded += line + "\n"
+ }
+ }
+ }
+ load()
+ probe := func(args ...string) (string, error) {
+ if args[0] == "show" && args[1] == demoBuildsSlice {
+ return loaded, nil
+ }
+ if args[1] == dbReadSocketUnit {
+ if args[0] == "is-active" {
+ return "inactive", systemctlExit(3)
+ }
+ return "disabled", systemctlExit(1)
+ }
+ if args[0] == "is-active" {
+ return "active", nil
+ }
+ return "enabled", nil
+ }
+ var calls [][]string
+ reloadFails := false
+ call := func(args ...string) (string, error) {
+ calls = append(calls, args)
+ if len(args) == 1 && args[0] == "daemon-reload" {
+ if reloadFails {
+ return "", errors.New("daemon-reload failed")
+ }
+ load()
+ }
+ return "", nil
+ }
+ lock := filepath.Join(systemRootDir(opt), systemLockFile)
+ want := func(family execsandbox.Family) string {
+ p := demobuild.SlicePropertiesFor(1, family)
+ return "MemoryMax=" + strconv.FormatInt(p["MemoryMax"], 10) + "\nMemorySwapMax=0\nTasksMax=" + strconv.FormatInt(p["TasksMax"], 10) + "\n"
+ }
+ if want(execsandbox.FamilySystemd) == want(execsandbox.FamilyGVisor) {
+ t.Fatal("the two families size the slice alike; this test proves nothing")
+ }
+ readSlice := func() string {
+ t.Helper()
+ b, err := os.ReadFile(slicePath)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return string(b)
+ }
+
+ ensureSystemUnits(etc, lock, call, probe, t.Logf)
+ if len(calls) != 0 {
+ t.Fatalf("armed systemd box changed units: %v", calls)
+ }
+ if !strings.Contains(readSlice(), want(execsandbox.FamilySystemd)) {
+ t.Fatalf("baseline slice: %s", readSlice())
+ }
+
+ writeEnv("gvisor")
+ ensureSystemUnits(etc, lock, call, probe, t.Logf)
+ if got := readSlice(); !strings.Contains(got, want(execsandbox.FamilyGVisor)) {
+ t.Fatalf("one pass after the flip left the slice at:\n%s", got)
+ }
+ if !slices.ContainsFunc(calls, func(a []string) bool { return len(a) == 1 && a[0] == "daemon-reload" }) {
+ t.Fatalf("no daemon-reload after re-rendering the slice: %v", calls)
+ }
+ calls = nil
+ ensureSystemUnits(etc, lock, call, probe, t.Logf)
+ if len(calls) != 0 {
+ t.Fatalf("second pass on the flipped box changed units again: %v", calls)
+ }
+
+ writeEnv("systemd")
+ ensureSystemUnits(etc, lock, call, probe, t.Logf)
+ if got := readSlice(); !strings.Contains(got, want(execsandbox.FamilySystemd)) {
+ t.Fatalf("rollback pass left the slice at:\n%s", got)
+ }
+
+ // A pass that writes the slice but fails its reload leaves systemd on
+ // the old budget. The next pass must notice from systemd's loaded view
+ // (the file already matches) and reload again; then it goes quiet.
+ writeEnv("gvisor")
+ reloadFails = true
+ calls = nil
+ ensureSystemUnits(etc, lock, call, probe, t.Logf)
+ if got := readSlice(); !strings.Contains(got, want(execsandbox.FamilyGVisor)) {
+ t.Fatalf("failed-reload pass did not write the slice:\n%s", got)
+ }
+ if strings.Contains(loaded, "TasksMax=192") {
+ t.Fatal("fixture: a failed reload changed the loaded view")
+ }
+ reloadFails = false
+ calls = nil
+ ensureSystemUnits(etc, lock, call, probe, t.Logf)
+ if !slices.ContainsFunc(calls, func(a []string) bool { return len(a) == 1 && a[0] == "daemon-reload" }) {
+ t.Fatalf("pass after a failed reload did not reload again: %v", calls)
+ }
+ if !strings.Contains(loaded, "TasksMax=192") {
+ t.Fatalf("loaded view after the retry: %q", loaded)
+ }
+ calls = nil
+ ensureSystemUnits(etc, lock, call, probe, t.Logf)
+ if len(calls) != 0 {
+ t.Fatalf("converged box changed units again: %v", calls)
+ }
+
+}
diff --git a/internal/host/group_names_test.go b/internal/host/group_names_test.go
index 77a4e0a0a..4667526bb 100644
--- a/internal/host/group_names_test.go
+++ b/internal/host/group_names_test.go
@@ -440,12 +440,13 @@ var groupNameProducerInventory = map[string]string{
// Edge page cache slice 1: routeScope builds an in-memory upstream only to
// read the route's page scope (account, app, primary host). It publishes,
// registers and routes no name; no name class.
- "../edge/pagecache.go:routeScope": "0d0ce1202034e50490832377c0d1568abaf1ee363d38b6763781906f8f1cf5ac",
- "../edge/platformalias.go:PlatformAliasFold": "a18e4963cf88320ef3fb94b666b02838dc12cc3e9b2df3f2cbe2576ca682735f",
- "../edge/regional.go:*Edge.foldRegional": "2c52d0d9147ab4b426649a78573a8550e0ba1073e2f5e5ef10e894f2570e9a8d",
- "../provision/forward.go:forwardRowFor": "e7294d6a3c96e51646257200f5cedb26aaf491afea23be3d943b3e3f742c4db4",
- "../provision/reconcile.go:Reconcile": "b2bc85f6ea8218fe4114a2847c7f4b828daa28181562f104bd5023179c03b9d0",
- "../provision/reconcile.go:RouteFor": "0a490d02aefdc829fe1b5bfd82314fd8984afbeceb01e31264920777203964f9",
+ "../edge/pagecache.go:routeScope": "0d0ce1202034e50490832377c0d1568abaf1ee363d38b6763781906f8f1cf5ac",
+ "../edge/platformalias.go:PlatformAliasFold": "a18e4963cf88320ef3fb94b666b02838dc12cc3e9b2df3f2cbe2576ca682735f",
+ "../edge/regional.go:*Edge.foldRegional": "2c52d0d9147ab4b426649a78573a8550e0ba1073e2f5e5ef10e894f2570e9a8d",
+ "../provision/forward.go:forwardRowFor": "e7294d6a3c96e51646257200f5cedb26aaf491afea23be3d943b3e3f742c4db4",
+ "../provision/reconcile.go:Reconcile": "b2bc85f6ea8218fe4114a2847c7f4b828daa28181562f104bd5023179c03b9d0",
+ // Resident replicas use nested local paths; exact-route names and owners do not change.
+ "../provision/reconcile.go:RouteFor": "f42827f4faca3572837e627a694c72928048e245573c50a75c357a44be28bb8d",
"../provision/reconcile.go:mintHeld": "9fe4ad876c727af36cc06bd0105baf344748c61e6f21ced48e5288a323851344",
"../provision/seedreconcile.go:purgeAbortedFromLocal": "889e93e6fbd74adf614ba184bcd2f554196eccc4506829c65326a3502e98d89a",
"../provision/seedrollback.go:removeOrphanedLocal": "6dd05836ac1d346de23ad555d50bb6c8fcd574cf05b6dfbf916eb0b220d88586",
diff --git a/internal/host/layoutleg.go b/internal/host/layoutleg.go
index 190eb2383..497c93be7 100644
--- a/internal/host/layoutleg.go
+++ b/internal/host/layoutleg.go
@@ -824,13 +824,18 @@ func mintLayoutIntent(ctx context.Context, store release.Store) (string, error)
// mintLayoutIntentWith is mintLayoutIntent with the box's own rows in hand
// (nil: no registry to ask). With no intent recorded and the deployment's
-// default nested, the default's gate is asked; and when the gate has not
-// yet answered (the first reconcile after an agent restart runs before the
-// control service's first probe) a box whose registry already holds an
-// activator-managed row at the nested paths counts as nested for mints
-// all the same: the box has evidently moved, and a flat row minted beside
-// nested siblings is the exposure the default exists to end. The gate
-// still guards every wake, so a nested row minted this way waits for it.
+// default nested, the default's gate is asked. A box that could wake
+// nested (an activator armed, at or above the floor) whose gate has not
+// answered yet, or answers not ready, still mints nested: the first
+// reconcile after an agent restart runs before the control service's
+// first probe, and a box short of a mount is fixed, not downgraded. A new
+// tenant minted flat there would run with the agent's uid beside its
+// nested siblings, the exposure the default exists to end; minted nested
+// it waits, with the gate's reason in status, until the box is ready or
+// an operator records flat. The gate still guards every wake. A box that
+// can never wake nested (no activator, below the floor) mints flat, as
+// under CARLOS_LAYOUT_DEFAULT=flat, unless its registry already holds an
+// activator-managed row at the nested paths: the box has evidently moved.
func mintLayoutIntentWith(ctx context.Context, store release.Store, routes func() ([]registry.Route, error)) (string, error) {
in, found, err := release.LoadLayoutIntent(ctx, store, BoxLabel())
switch {
@@ -841,14 +846,19 @@ func mintLayoutIntentWith(ctx context.Context, store release.Store, routes func(
if mode == release.LayoutModeNested {
return mode, nil
}
- if def, invalid := layoutDefault(os.Getenv); def == release.LayoutModeNested && invalid == "" && routes != nil {
- rows, err := routes()
- if err != nil {
- return "", fmt.Errorf("layout default: list routes: %w", err)
- }
- if nestedRowsPresent(rows) {
+ if def, invalid := layoutDefault(os.Getenv); def == release.LayoutModeNested && invalid == "" {
+ if layoutDefaultGate.Load() != nil && !release.BelowFloor(layoutBuild(), release.LayoutFloor) {
return release.LayoutModeNested, nil
}
+ if routes != nil {
+ rows, err := routes()
+ if err != nil {
+ return "", fmt.Errorf("layout default: list routes: %w", err)
+ }
+ if nestedRowsPresent(rows) {
+ return release.LayoutModeNested, nil
+ }
+ }
}
return release.LayoutModeNone, nil
case !release.ValidLayoutMode(in.Mode):
@@ -856,3 +866,21 @@ func mintLayoutIntentWith(ctx context.Context, store release.Store, routes func(
}
return in.Mode, nil
}
+
+// flatLayoutChosen reports whether this box runs flat on purpose: the
+// intent last converged or read at startup is a recorded flat, or no
+// recorded intent has been seen (none, which is also "" before the leg's
+// first read) and CARLOS_LAYOUT_DEFAULT=flat. Nested, none on a
+// nested-default deployment (a box that is not ready yet), an invalid
+// default and unreadable all answer false: a box that has not said flat
+// does not start a new resident flat (activator.ExecBackend.FlatLayoutChosen).
+func flatLayoutChosen() bool {
+ switch lastLayoutIntent() {
+ case release.LayoutModeFlat:
+ return true
+ case release.LayoutModeNone:
+ def, invalid := layoutDefault(os.Getenv)
+ return def == release.LayoutModeFlat && invalid == ""
+ }
+ return false
+}
diff --git a/internal/host/rootfs_advice_test.go b/internal/host/rootfs_advice_test.go
index cb2c810dc..c0dacb7ba 100644
--- a/internal/host/rootfs_advice_test.go
+++ b/internal/host/rootfs_advice_test.go
@@ -2,7 +2,6 @@ package host
import (
"context"
- "errors"
"log"
"os"
"path/filepath"
@@ -376,7 +375,7 @@ func TestLayoutLegIsQuietAboutKeptRootfsRows(t *testing.T) {
}
// TestMintEvidenceIgnoresRootfsRows (task 5 fix round 1): with no intent,
-// the nested default and its gate not yet passed, a binary row is minted
+// the nested default and no activator armed, a binary row is minted
// flat unless a binary managed row already sits at the nested paths. A
// resident or an unknown runtime there is no such proof: rootfs rows are
// nested by construction. Not parallel: it sets env and the layout globals.
@@ -387,7 +386,10 @@ func TestMintEvidenceIgnoresRootfsRows(t *testing.T) {
t.Cleanup(func() { layoutBuild = prev })
layoutBuild = func() string { return "v0.25.0" }
t.Setenv("CARLOS_DATA_DIR", "/data")
- armDefaultGate(t, errors.New("not yet run"))
+ // No activator armed: the one case the mint still asks the registry
+ // for a nested sibling (an armed box mints nested whatever the gate
+ // says, TestStartupAndMintReadTheDefault).
+ layoutDefaultGate.Store(nil)
ctx := context.Background()
s := release.NewDirStore(t.TempDir())
nested := func(host, runtime string, hib bool) registry.Route {
@@ -405,7 +407,7 @@ func TestMintEvidenceIgnoresRootfsRows(t *testing.T) {
} {
rows := func() ([]registry.Route, error) { return []registry.Route{c.rt}, nil }
if mode, err := mintLayoutIntentWith(ctx, s, rows); err != nil || mode != c.want {
- t.Errorf("mint, gate not ready, only %s as evidence = %q, %v; want %q", name, mode, err, c.want)
+ t.Errorf("mint, no activator, only %s as evidence = %q, %v; want %q", name, mode, err, c.want)
}
}
}
diff --git a/internal/host/runsc_update_dirs_linux_test.go b/internal/host/runsc_update_dirs_linux_test.go
index 1184569e3..807d3c66c 100644
--- a/internal/host/runsc_update_dirs_linux_test.go
+++ b/internal/host/runsc_update_dirs_linux_test.go
@@ -313,6 +313,10 @@ func TestSandboxUpdateControlRestartForNewRootfs(t *testing.T) {
}
shows := 0
probe := func(args ...string) (string, error) {
+ if args[0] == "show" && args[1] == demoBuildsSlice {
+ // The adopt pass's loaded-budget check; no answer is no difference.
+ return "", nil
+ }
if args[0] == "show" {
if strings.Join(args, " ") != "show -p MainPID,InvocationID,ControlGroup "+claimControlUnit {
t.Errorf("probe %v", args)
diff --git a/internal/host/systemunits.go b/internal/host/systemunits.go
index 1c5ba3d06..79e480172 100644
--- a/internal/host/systemunits.go
+++ b/internal/host/systemunits.go
@@ -34,7 +34,10 @@ var ensureSystemArmed = []string{systemUpdatePathUnit, systemRecoverUnit, instan
// carlos-dbread.socket and its service template are the db-read worker's
// (db region forward spec §8.3): installed and the socket armed here, the
// template never started.
-var systemUnitFiles = []string{"carlos-runsc.service", instancectl.UnitPrefixGVisor + ".service", "carlos-instance-gvisor-probe.service", "carlos-demo-build-gvisor@.service", "carlos-system-update.path", "carlos-system-update.service", systemRecoverUnit, instanceControlSocket, "carlos-instance-control.service", dbReadSocketUnit, "carlos-dbread@.service", "carlos-demo-build@.service", "carlos-demo-builds.slice"}
+// demoBuildsSlice is the demo build budget, rendered per box by claimUnitContent.
+const demoBuildsSlice = "carlos-demo-builds.slice"
+
+var systemUnitFiles = []string{"carlos-runsc.service", instancectl.UnitPrefixGVisor + ".service", "carlos-instance-gvisor-probe.service", "carlos-demo-build-gvisor@.service", "carlos-system-update.path", "carlos-system-update.service", systemRecoverUnit, instanceControlSocket, "carlos-instance-control.service", dbReadSocketUnit, "carlos-dbread@.service", "carlos-demo-build@.service", demoBuildsSlice}
// ensureSystemUnits is the second belt of spec §7: a box the roll script
// forgot to arm is armed within the hour by the root adopt pass. It
@@ -200,6 +203,35 @@ func ensureSystemUnitsWithGuard(etcDir, lockPath string, systemctl, probe func(a
return
}
controlChanged := settingsErr == nil && (claimSettings.enabled || claimSettings.demo.BoxMode() || claimControlRendered(installed)) && (err != nil || !bytes.Equal(installed, claimUnitContent(claimControlUnit, control, claimSettings)))
+ // The demo build budget slice is rendered from host.env too: the build
+ // concurrency and the effective exec sandbox size it. A host.env change
+ // alone (a box switched to gVisor) touches no other unit, so without this
+ // comparison the pass would return as already armed and leave the slice
+ // sized for the old sandbox, and every build would refuse at its budget
+ // check. A missing slice is already a reinstall (missing).
+ sliceChanged := false
+ if settingsErr == nil {
+ sliceRaw, err := unitsFS.ReadFile("units/" + demoBuildsSlice)
+ if err != nil {
+ logf("adopt: system units: %v", err)
+ return
+ }
+ sliceInstalled, err := os.ReadFile(filepath.Join(unitDir, demoBuildsSlice))
+ if err != nil && !os.IsNotExist(err) {
+ logf("adopt: demo build slice: %v", err)
+ return
+ }
+ want := claimUnitContent(demoBuildsSlice, sliceRaw, claimSettings)
+ sliceChanged = err == nil && !bytes.Equal(sliceInstalled, want)
+ // Matching bytes are not enough: a pass that wrote the slice and then
+ // failed its daemon-reload (or lost its group permit before it) leaves
+ // systemd on the old budget with nothing left to compare. Ask systemd
+ // what it has loaded; only a definite mismatch counts.
+ if err == nil && !sliceChanged {
+ out, _ := probe("show", demoBuildsSlice, "-p", "MemoryMax,TasksMax")
+ sliceChanged = sliceLoadedDiffers(out, want)
+ }
+ }
dbrEnabled := parseIsEnabled(dbrEnabledOut)
// Dark: neither listening nor enabled for the next boot.
dbrDark := !*dbrActive && (dbrEnabled == nil || !*dbrEnabled)
@@ -212,7 +244,7 @@ func ensureSystemUnitsWithGuard(etcDir, lockPath string, systemctl, probe func(a
return
}
}
- if !demoChanged && !missing && !controlChanged && *isActive && isEnabled != nil && *isEnabled && *ctlActive && dbrSettled {
+ if !demoChanged && !missing && !controlChanged && !sliceChanged && *isActive && isEnabled != nil && *isEnabled && *ctlActive && dbrSettled {
return
}
if err := os.MkdirAll(unitDir, 0o755); err != nil {
@@ -295,3 +327,27 @@ func systemctlProbe(args ...string) (string, error) {
out, err := exec.Command("systemctl", args...).Output()
return string(out), err
}
+
+// sliceLoadedDiffers reports a definite difference between the budget
+// systemd has loaded for the demo build slice (`systemctl show -p
+// MemoryMax,TasksMax`) and the rendered unit. Output missing either
+// property says nothing and is not a difference.
+func sliceLoadedDiffers(show string, rendered []byte) bool {
+ values := func(text string) map[string]string {
+ m := map[string]string{}
+ for _, line := range strings.Split(text, "\n") {
+ k, v, ok := strings.Cut(strings.TrimSpace(line), "=")
+ if ok && (k == "MemoryMax" || k == "TasksMax") {
+ m[k] = v
+ }
+ }
+ return m
+ }
+ loaded, want := values(show), values(string(rendered))
+ for _, k := range []string{"MemoryMax", "TasksMax"} {
+ if loaded[k] == "" || want[k] == "" {
+ return false
+ }
+ }
+ return loaded["MemoryMax"] != want["MemoryMax"] || loaded["TasksMax"] != want["TasksMax"]
+}
diff --git a/internal/host/systemunits_test.go b/internal/host/systemunits_test.go
index fe5fc01f3..893794da4 100644
--- a/internal/host/systemunits_test.go
+++ b/internal/host/systemunits_test.go
@@ -69,7 +69,8 @@ func TestEnsureSystemUnitsInstallsAndArmsWhatIsMissing(t *testing.T) {
return "", nil
}
ensureSystemUnits(etc, lockPath, systemctl, probe2, t.Logf)
- if len(calls) != 5 {
+ // Five arming questions plus the demo build slice's loaded budget.
+ if len(calls) != 6 || calls[5] != "show "+demoBuildsSlice+" -p MemoryMax,TasksMax" {
t.Fatalf("an armed box got %v", calls)
}
}
@@ -260,10 +261,11 @@ func TestEnsureSystemUnitsRetiresUnitsNoLongerShipped(t *testing.T) {
}
}
- // Nothing left to retire: the armed pass is back to its five questions.
+ // Nothing left to retire: the armed pass is back to its six questions
+ // (the sixth asks systemd for the demo build slice's loaded budget).
calls = nil
ensureSystemUnits(etc, lockPath, systemctl, armed, t.Logf)
- if len(calls) != 5 {
+ if len(calls) != 6 {
t.Fatalf("an armed box with nothing to retire got %v", calls)
}
}
diff --git a/internal/moves/archive/zstd_malformed_test.go b/internal/moves/archive/zstd_malformed_test.go
new file mode 100644
index 000000000..b7fa14259
--- /dev/null
+++ b/internal/moves/archive/zstd_malformed_test.go
@@ -0,0 +1,57 @@
+package archive
+
+import (
+ "bytes"
+ "errors"
+ "testing"
+)
+
+// malformedZstd is a zstd frame whose sequence decoding panicked
+// github.com/klauspost/compress before v1.20.2 (security review
+// 2026-11-09, zstd-probe). It must now fail as an ordinary decode error.
+func malformedZstd() []byte {
+ b := []byte{0x28, 0xb5, 0x2f, 0xfd, 0x00, 0x38, 0x74, 0x06, 0x00, 0x42, 0xb8, 0x32, 0x0d, 0x1a, 0x00, 0x00, 0x00, 0x90, 0xaf, 0xfa, 0xff, 0x03, 0x00, 0x80, 0xff, 0x7f}
+ b = append(b, bytes.Repeat([]byte{0xa5, 0x94, 0x52, 0x4a, 0x29}, 37)...)
+ b = append(b, 0xa5, 0x94, 0x12, 0x00, 0xad, 0x56, 0x03, 0xee, 0xff, 0xdf, 0xb3, 0x1a, 0x1c, 0x1a, 0x00, 0xe0, 0xff, 0x1f, 0x0f, 0xb1, 0x9c, 0x5a, 0xcf, 0x4d, 0xe4, 0x1d, 0x7b, 0xab, 0x99, 0x5e, 0x01, 0x51, 0xa4, 0x73, 0xd8, 0xb1, 0xf3, 0x39, 0x4b, 0x67, 0xf6, 0xab, 0x1a, 0xab, 0x1a, 0xab, 0x1a)
+ b = append(b, bytes.Repeat([]byte{0x8c, 0x31, 0xc6, 0x18, 0x63}, 1365)...)
+ b = append(b, 0x8c, 0x31)
+ b = append(b, bytes.Repeat([]byte{0x63, 0x8c, 0x31, 0xc6, 0x18}, 1365)...)
+ b = append(b, 0x63, 0x2c)
+ b = append(b, bytes.Repeat([]byte{0x31, 0xc6, 0x18, 0x63, 0x8c}, 1365)...)
+ b = append(b, 0x31, 0x46)
+ b = append(b, bytes.Repeat([]byte{0x31, 0xc6, 0x18, 0x63, 0x8c}, 1365)...)
+ return append(b, 0x31, 0x06, 0x00)
+}
+
+// The malformed frame follows a valid frame holding a whole tar, so the
+// decoder only meets it when Extract and Verify read the decoded stream on
+// to its end (they do, to enforce decodedLimit); a frame in first position
+// would be refused by the tar reader before its bad block was decoded.
+func TestMalformedZstdFrameErrorsWithoutPanic(t *testing.T) {
+ frame := append(tarZst(t, []rawEntry{reg("files/a", "x")}, nil), malformedZstd()...)
+
+ t.Run("Extract", func(t *testing.T) {
+ parent, files, env := extractTarget(t)
+ if err := Extract(bytes.NewReader(frame), files, env); err == nil {
+ t.Fatal("Extract accepted a malformed zstd frame")
+ }
+ assertUntouched(t, parent, files, env)
+ })
+
+ t.Run("Verify", func(t *testing.T) {
+ pub, priv, b := keys(t)
+ var sealed bytes.Buffer
+ key, sealedSHA, err := Seal(bytes.NewReader(frame), pub, b, &sealed)
+ if err != nil {
+ t.Fatal(err)
+ }
+ m := Manifest{V: ManifestVersion, Plain: "sha256:x", Sealed: sealedSHA, Bytes: 1, Entries: []Entry{{Path: "files/a", Size: 1, SHA256: digestBytes([]byte("x"))}}, SealedDataKey: key, Chunk: ChunkSize}
+ err = Verify(bytes.NewReader(sealed.Bytes()), m, priv, b)
+ if err == nil {
+ t.Fatal("Verify accepted a malformed zstd frame")
+ }
+ if errors.Is(err, ErrTooLarge) {
+ t.Fatalf("Verify = %v, want a decode error", err)
+ }
+ })
+}
diff --git a/internal/provision/reconcile.go b/internal/provision/reconcile.go
index af510bd4b..f290446da 100644
--- a/internal/provision/reconcile.go
+++ b/internal/provision/reconcile.go
@@ -628,8 +628,12 @@ func RouteFor(rec Record, dataDir, seed string, nested bool, policy *UpdatePolic
// flat in every release (design §8.2 step 1). A born-HA row is
// nested whatever nested says (#446): it wakes only nested (region
// HA P1a), and a fresh box mints before its first nested-default
- // decision, so a flat mint could never wake on it.
- if (nested || rec.HA || rec.Demo != nil) && rt.Hibernate {
+ // decision, so a flat mint could never wake on it. A row the
+ // replica assignment projects stateless (projectReplicaAssignment,
+ // above) is a platform-managed resident the tick starts, not an
+ // external process: it is nested on the same terms as a
+ // hibernating row.
+ if (nested || rec.HA || rec.Demo != nil) && (rt.Hibernate || rt.Stateless) {
rt.Socket = NestedSocket(rec.Host)
rt.DBPath = NestedDBPath(dataDir, rec.Host)
}
diff --git a/internal/provision/replicas_test.go b/internal/provision/replicas_test.go
index 44afda718..23dcd62fc 100644
--- a/internal/provision/replicas_test.go
+++ b/internal/provision/replicas_test.go
@@ -2,6 +2,7 @@ package provision
import (
"bytes"
+ "context"
"database/sql"
"encoding/json"
"fmt"
@@ -445,3 +446,35 @@ func TestReplicaAssignmentAdmissionFromRecord(t *testing.T) {
})
}
}
+
+// A record whose replica assignment projects it stateless is a resident the
+// activator's tick starts, so on a nested box it is minted at the nested
+// paths exactly as a hibernating row is; on a flat box it stays flat.
+func TestReplicaResidentMintsNestedUnderANestedIntent(t *testing.T) {
+ for _, mode := range []string{release.LayoutModeNested, release.LayoutModeFlat} {
+ t.Run(mode, func(t *testing.T) {
+ s, rec, cfg := replicaReconcileFixture(t)
+ cfg.FleetBox = "a"
+ cfg.Layout = func(context.Context, release.Store) (string, error) { return mode, nil }
+ reg := regWith(t)
+ defer reg.Close()
+ if err := Reconcile(ctx, s, reg, cfg); err != nil {
+ t.Fatal(err)
+ }
+ got := *mustGet(t, reg, rec.Host)
+ if !got.Stateless || got.Hibernate {
+ t.Fatalf("minted row stateless %v hibernate %v, want a stateless resident", got.Stateless, got.Hibernate)
+ }
+ wantDB, wantSock := DefaultDBPath(cfg.DataDir, rec.Host), DefaultSocket(rec.Host)
+ if mode == release.LayoutModeNested {
+ wantDB, wantSock = NestedDBPath(cfg.DataDir, rec.Host), NestedSocket(rec.Host)
+ }
+ if got.DBPath != wantDB || got.Socket != wantSock {
+ t.Fatalf("%s box minted the resident at db %q socket %q, want %q, %q", mode, got.DBPath, got.Socket, wantDB, wantSock)
+ }
+ if NestedPaths(cfg.DataDir, got) != (mode == release.LayoutModeNested) {
+ t.Fatalf("NestedPaths = %v under %s", NestedPaths(cfg.DataDir, got), mode)
+ }
+ })
+ }
+}
diff --git a/internal/provision/testdata/plan14-root-reads-chain.tsv b/internal/provision/testdata/plan14-root-reads-chain.tsv
index 51af650d7..01fd1a9f3 100644
--- a/internal/provision/testdata/plan14-root-reads-chain.tsv
+++ b/internal/provision/testdata/plan14-root-reads-chain.tsv
@@ -140,3 +140,6 @@ plan14-root-reads-gvisor-update-dirs.tsv 1f1b2fdb569b7be42e75e10d1943d7e51270829
plan14-root-reads-region-ha-held-build.tsv beb085e4c6cdb3d430d12a8dc3c93f25cc3faf1aa7d62be37698ff9c9c82ecce
plan14-root-reads-fixedbox-health-alarms.tsv 0f7153571df8c1b4b50c31f57efcfdf60c71a12c80fd935fb3ea202fa0201dd5
plan14-root-reads-fixed-host-ignore-user-data.tsv 250e3ba91e1bc5fcd6be5cc2bafce4c7d6645d2d2f0c080913b99f01b1d19129
+plan14-root-reads-deploy-edge-718.tsv 250e3ba91e1bc5fcd6be5cc2bafce4c7d6645d2d2f0c080913b99f01b1d19129
+plan14-root-reads-demo-slice-adopt.tsv 707018faaa1fee3b47abb78389ae7854264e76621cc316889061adb69bf13e10
+plan14-root-reads-security-review-mitigations.tsv a6f3f9eec4aac5ea88f20d0e52eaa0651fce80c0d49b60883ff61ceade33d288
diff --git a/internal/provision/testdata/plan14-root-reads-demo-slice-adopt.tsv b/internal/provision/testdata/plan14-root-reads-demo-slice-adopt.tsv
new file mode 100644
index 000000000..bca83f8b8
--- /dev/null
+++ b/internal/provision/testdata/plan14-root-reads-demo-slice-adopt.tsv
@@ -0,0 +1,13 @@
+# Census overlay demo-slice-adopt, written by census-propose (#369). census-ruling-demo-slice-adopt, approved on #280 before the merge; the approval card is docs/superpowers/notes/census-proposal-demo-slice-adopt.md.
+# 1 body, 1 sites, 2 envelope: each changed unit re-frozen at its existing disposition with its claim appended.
+# 2 new dispositions: 0 reads re-frozen at their disposition with the claim, 2 new units frozen accepted-legacy, 0 quiet units retired while they read nothing, 0 other.
+@legacy 43550b6e48cc4c57755d999ad44c7a7ed9369b6c53ce89fc59eb00c0e187ddab internal/demobuild/worker.go Worker.Build legacy accepted-legacy accepted-legacy;rev3=census-ruling-agent-start-demo-1;basis=Holds the build/purge read lock through cleanup; existing bounded source read remains.;rev3=census-ruling-demo-slice-adopt;basis=Before admission, call the admit hook (nil = reconcileBudget); a pending budget change (errBudgetPending) is retried every 2 s until the job deadline, any other error fails at once. reconcileBudget reads the fixed build slice's systemctl show budget, its cgroup limit files and cgroup.events under the fixed root cgroup path, and list-jobs (a listing at the capture limit defers); only with buildPurge held exclusively, the slice empty and no build or slice job queued does it run systemctl stop on the fixed slice name. No tenant, app or agent input names a path or unit. file:ReadAll@1087 be01e7c25a520d79132c28cb1bc6ac274139643981a5f7d415cd876e333c2da8
+@legacy bf0fab994b0fd42b2af18b70e21c4b8cbe3b4dfe8e0e9988f246f0ea9275afb6 internal/demobuild/budget.go budgetSlicePopulated legacy accepted-legacy accepted-legacy;rev3=census-ruling-demo-slice-adopt;basis=New. Reads cgroup.events under the fixed build slice cgroup path (buildCgroupRoot); absent = empty; a file without a populated line refuses. file:ReadFile@55 60e72229ce907ec9eb953caf4d35c56416153a10f9e73520b55571c2e11b7ca2
+@legacy 4b52c494b53f26d262697e10cfd31bad182f2c54c1b56e529b9b930fa439c936 internal/demobuild/budget.go kernelBudgetMatches legacy accepted-legacy accepted-legacy;rev3=census-ruling-demo-slice-adopt;basis=New. Reads memory.max, memory.swap.max, pids.max and cpu.max under the fixed build slice cgroup path and compares them with SlicePropertiesFor; absent cgroup = slice not running = match; read errors refuse. file:Lstat@168,file:ReadFile@591 fc138916d7510dd62066c8bafa97c8c4b7bf9a108537862f73f9bfbdcd2853c8
+@legacy 55e6adc18f848f6049ffc4504debbacd1f5704dc1f9eac798bc74d2d09b83196 internal/host/systemunits.go ensureSystemUnitsWithGuard legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p3b;basis=Move unit-repair body here with existing lock/unit/host.env reads; under lock require operator repair permit on groups before writes and each systemctl effect, preserve root masks/drop-in and omit automatic update/recovery units. New indirect protected marker/permit reads, never agent receipt; fixed repair unchanged.;rev3=census-ruling-gvisor-demos;basis=Create runtime/rootfs directories and repair installer plus three measured workload templates without arming them. Existing unit/host.env reads unchanged.;rev3=census-ruling-gvisor-update-dirs;basis=Create the two live sandbox directories (the same fixed ensureSandboxDirectories paths) before the apply lock and the early returns on non-group boxes; group members still create them only after the maintenance permit. A creation error still ends the pass at the original point. Then call refreshControlSandboxRootfs. No new path, input or systemctl verb beyond the try-restart below.;rev3=census-ruling-demo-slice-adopt;basis=Compare the installed carlos-demo-builds.slice (fixed root unit path, embedded unit) with its host.env rendering, and ask systemd for the slice's loaded MemoryMax/TasksMax (systemctl show on the fixed name). A definite difference is a reinstall (existing write loop + daemon-reload). No live budget change, no new path, input or write target. file:OpenFile@985,file:ReadFile@5626,file:ReadFile@5759,file:ReadFile@6647,file:ReadFile@6789,file:ReadFile@8548,file:Stat@5535 134e8105086fb29df32933f0ef26e664c0f08b7b8667a909838f2bde0c0fecfb
+internal/demobuild/worker.go Worker.Build legacy accepted-legacy accepted-legacy;rev3=census-ruling-agent-start-demo-1;basis=Holds the build/purge read lock through cleanup; existing bounded source read remains.;rev3=census-ruling-demo-slice-adopt;basis=Before admission, call the admit hook (nil = reconcileBudget); a pending budget change (errBudgetPending) is retried every 2 s until the job deadline, any other error fails at once. reconcileBudget reads the fixed build slice's systemctl show budget, its cgroup limit files and cgroup.events under the fixed root cgroup path, and list-jobs (a listing at the capture limit defers); only with buildPurge held exclusively, the slice empty and no build or slice job queued does it run systemctl stop on the fixed slice name. No tenant, app or agent input names a path or unit. file:ReadAll@1087 be01e7c25a520d79132c28cb1bc6ac274139643981a5f7d415cd876e333c2da8
+internal/demobuild/budget.go budgetSlicePopulated legacy accepted-legacy accepted-legacy;rev3=census-ruling-demo-slice-adopt;basis=New. Reads cgroup.events under the fixed build slice cgroup path (buildCgroupRoot); absent = empty; a file without a populated line refuses. file:ReadFile@55 60e72229ce907ec9eb953caf4d35c56416153a10f9e73520b55571c2e11b7ca2
+internal/demobuild/budget.go kernelBudgetMatches legacy accepted-legacy accepted-legacy;rev3=census-ruling-demo-slice-adopt;basis=New. Reads memory.max, memory.swap.max, pids.max and cpu.max under the fixed build slice cgroup path and compares them with SlicePropertiesFor; absent cgroup = slice not running = match; read errors refuse. file:Lstat@168,file:ReadFile@591 fc138916d7510dd62066c8bafa97c8c4b7bf9a108537862f73f9bfbdcd2853c8
+internal/host/systemunits.go ensureSystemUnitsWithGuard legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p3b;basis=Move unit-repair body here with existing lock/unit/host.env reads; under lock require operator repair permit on groups before writes and each systemctl effect, preserve root masks/drop-in and omit automatic update/recovery units. New indirect protected marker/permit reads, never agent receipt; fixed repair unchanged.;rev3=census-ruling-gvisor-demos;basis=Create runtime/rootfs directories and repair installer plus three measured workload templates without arming them. Existing unit/host.env reads unchanged.;rev3=census-ruling-gvisor-update-dirs;basis=Create the two live sandbox directories (the same fixed ensureSandboxDirectories paths) before the apply lock and the early returns on non-group boxes; group members still create them only after the maintenance permit. A creation error still ends the pass at the original point. Then call refreshControlSandboxRootfs. No new path, input or systemctl verb beyond the try-restart below.;rev3=census-ruling-demo-slice-adopt;basis=Compare the installed carlos-demo-builds.slice (fixed root unit path, embedded unit) with its host.env rendering, and ask systemd for the slice's loaded MemoryMax/TasksMax (systemctl show on the fixed name). A definite difference is a reinstall (existing write loop + daemon-reload). No live budget change, no new path, input or write target. file:OpenFile@985,file:ReadFile@5626,file:ReadFile@5759,file:ReadFile@6647,file:ReadFile@6789,file:ReadFile@8548,file:Stat@5535 134e8105086fb29df32933f0ef26e664c0f08b7b8667a909838f2bde0c0fecfb
+@coverage internal/demobuild 64b77e1e6fd5dfa470fd4ab98f82b8b1df689ffde04eedbb757cb6ad627fac52
+@coverage internal/host 88889b9888f3bec0a97e22581c486a81cd33951a8b2148299788ce5abe0512f6
diff --git a/internal/provision/testdata/plan14-root-reads-deploy-edge-718.tsv b/internal/provision/testdata/plan14-root-reads-deploy-edge-718.tsv
new file mode 100644
index 000000000..1832650c1
--- /dev/null
+++ b/internal/provision/testdata/plan14-root-reads-deploy-edge-718.tsv
@@ -0,0 +1,3 @@
+# Census overlay deploy-edge-718, written by census-propose (#369). census-ruling-deploy-edge-718, approved on #280 before the merge; the approval card is docs/superpowers/notes/census-proposal-deploy-edge-718.md.
+# 0 body, 0 sites, 1 envelope: each changed unit re-frozen at its existing disposition with its claim appended.
+@coverage . b988bc9ed43b956dbda0907c623554df11d014c9bdcadc2aaecdc88fc5ac738a
diff --git a/internal/provision/testdata/plan14-root-reads-security-review-mitigations.tsv b/internal/provision/testdata/plan14-root-reads-security-review-mitigations.tsv
new file mode 100644
index 000000000..a62452423
--- /dev/null
+++ b/internal/provision/testdata/plan14-root-reads-security-review-mitigations.tsv
@@ -0,0 +1,15 @@
+# Census overlay security-review-mitigations, written by census-propose (#369). census-ruling-security-review-mitigations, approved on #280 before the merge; the approval card is docs/superpowers/notes/census-proposal-security-review-mitigations.md.
+# 2 body, 1 sites, 4 envelope: each changed unit re-frozen at its existing disposition with its claim appended.
+# 2 new dispositions: 1 reads re-frozen at their disposition with the claim, 1 new units frozen accepted-legacy, 0 quiet units retired while they read nothing, 0 other.
+@legacy 271a69c18bec930e0a4a7b7b4f9fe5778e3fd8843809a47bc93b06538937e1ad internal/host/layoutleg.go mintLayoutIntentWith legacy accepted-legacy accepted-legacy;rev3=J1;basis=root-route;rev3=census-ruling-security-review-mitigations;basis=Mint nested on nested-default, activator-armed, floor-capable boxes while isolation readiness is pending; wake still gates on readiness. Explicit flat and incapable-box compatibility unchanged; same intent/env/registry sources. whole:Route@762 e07b678da489350b4cecbfd4c22e6fcc64c42697b3e0e0c25c54c90fba4d5a8b
+@legacy 9d22341e4041f9a1f873f62a33158513b4e64ccc37b6dab053069c4e919727e7 internal/activator/backend_exec.go ExecBackend.residentLayoutRefusal legacy accepted-legacy accepted-legacy;rev3=census-ruling-security-review-mitigations;basis=New agent-side refusal reads existing Route GoodVersion and ServingVersion and the route's stateless/resident shape; callback reads cached operator choice. No filesystem/store read; served legacy residents and explicit flat remain supported. R4-requested launchRefused marker proves this pre-exec refusal started nothing, allowing existing stop-proof recovery; predicate and sources unchanged. registry:GoodVersion@138,registry:ServingVersion@111,whole:Route@104 eab300984a3579fcb162e5d34530b5d1ae96f1c35e775e9d56cca6967e654f21
+@legacy 6008f52811aaf67b35fa92836c8cace9915bf5555df08a31a42cda7ed1be959a internal/activator/backend_exec.go ExecBackend.spawnChildFrom legacy accepted-legacy accepted-legacy;rev3=census-ruling-zddr3;basis=Census ruling zddr3: changed legacy row (comment-only change describing the shim placement); the same class as the accepted-legacy Manager.startIn and placementLive under fix1-merge-review (existing agent delegated-cgroup management remains legacy); no root decision; no registry, /data, release or claim reads. Boundary: the agent's own delegated cgroup subtree (including its scratch probe child), /proc/self, and pipes to and from its own parent, running as carlos.;rev3=census-ruling-region-ha-p1a;basis=the agent as carlos (the flat start body): the same change as seedChild: ensureAdminTokenFor(ctx, rt, paths) for the token (the same flat path), the key's producer carrying the HA mint decision, and launchEnvLayer(ctx, rt) for the env and key layer the replica gate reads; a non-HA host's token, key and env are produced and read as before; +whole:Route; only adds refusals for HA hosts;rev3=census-ruling-stateless-replicas-1;basis=Task 3a: Use the verified generation/launch mode to remove CARLOS_DB after environment merges and omit the binary --db argument where applicable. Existing runtime, layout, secrets and exec gates remain; route reads are mode projection only.;rev3=census-ruling-edge-page-cache-1;basis=the control listener is now built with the whole route (edge.ListenControl(controlSocket, rt, ...)), the +whole:Route site; it computes the launch inputs once from the build it execs by path (a staged exe's caller-named build, or the gate-resolved pinned version; "" for an unpinned live link) and fileEnv it already read, keeps them on the childProc, and for a live-link spawn publishes them to the in-memory cache (NoteProcessInputs) beside the existing purge; no new file read;rev3=census-ruling-gvisor-demos;basis=Task 5: gate launch using startup-captured mode and existing route/role/layout before preparation or execution; migrate structured root start identity and reject mismatches. Unsupported gVisor paths refuse; native behavior and existing root authority checks retained. No new root read source. Merge2 e8a1ddde: retain main build parameter, pinned live identity, launchInputs from captured build/environment, and current-process input publication. edge.ListenControl now receives the whole Route as main requires (+whole:Route); no new filesystem or storage input. Branch sandboxLaunch remains before preparation and spawn; existing direct primitive gate unchanged.;rev3=census-ruling-security-review-mitigations;basis=Enforce the unchanged never-served resident refusal once at the shared flat/foreign primary binary spawn sink, before placement, live-link/token/env/control preparation or execution. Covers plain, generation and staged Service wakes; existing served/explicit-flat exemptions and other gates retained. No new filesystem/store source. file:Command@11357,registry:Host@12640,registry:Host@13001,registry:Host@13095,registry:Host@258,registry:Host@4214,registry:Host@4269,registry:Host@4349,registry:Host@4563,registry:Stateless@11288,whole:Route@11180,whole:Route@11329,whole:Route@11737,whole:Route@13392,whole:Route@13484,whole:Route@1527,whole:Route@189,whole:Route@1944,whole:Route@2305,whole:Route@287,whole:Route@4447,whole:Route@4757,whole:Route@476,whole:Route@6828,whole:Route@9093 62a25da95d4b4b98122648e98d7348f1159f50077e7cfb8d282d811627580dfd
+internal/host/agent.go runAgent authority B,C,D,F rev3=census-ruling-self-serve-moves-1;basis=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): builds the box's lifetime judge once (newBoxJudge, nil with host claims on) and hands it to the seed placement, the moves and runs workers and every loop it starts; read sites unchanged, offsets moved; B,C,D,F authority retained; self-serve moves 1 Task 8: derives the box's lifetimes switch from the judge once (lifetimes := boxJudge != nil) and hands it to the edges file loop; read sites unchanged, offsets moved;rev3=census-ruling-plans-4d-lapse;basis=arms two more plans hooks from the same snapshot: e.SetPlanDisabledFor(planDisabledFor) beside SetPlanGovernedFor, and svc.SetDisabledFor(planDisabledRoute) beside SetMaxRunFor (plans 4d); the reads live in those units (plans-4d-units decision); read sites unchanged, offsets moved;rev3=census-ruling-rootfs-apps-2;basis=main's body as of the merge of origin/main 9b81d97b (with main's plan rate ceiling, edge request records, regional box names, self-serve moves plan 1, plans 4d-1 lapse and its other later changes under main's own census rulings) plus the rootfs placement wiring in the activator start: an agentRootfs built from eb.NestedOK, CARLOS_DEPLOYMENT_SINGLE_TENANT, CARLOS_POOLS, the claim flag, swapArming's answer, the control client's /ready/rootfs and, on a fleet box whose identity resolved, fleetOwnerCheck over the deploy store main already opens for the fleet label (fleetStore), then arm and armedRootfs.Store; this body reads nothing new itself; the closures it wires read later, at a rootfs wake and each status tick: GET /ready/rootfs over the control socket, NestedOK's checks, and release.FleetOwnerKey for the judged row's own account and this box's fleet from the deploy store;rev3=census-ruling-instance-egress-sizes-328-329;basis=#328 plan 2 Tasks 7 and 11, #329 plan 3 Task 7 and plan 1 Task 7's policy cache: the control client is built once and handed to eb.Control, to the status tick (egressStatus) and to a new egressNudgeLoop goroutine; armSizeSource(svc, "/sys/fs/cgroup") after the activator Service; armPolicyCache() after armChangeIndex; statusLoop takes egressStatus. The reads are those units' own (decision rows); this body reads nothing new: the same five sites, offsets moved, in the agent; B,C,D,F authority retained.;rev3=census-ruling-remote-instance-metrics;basis=builds the metrics loop's owners closure (metricsOwners over the agent's registry, the activator and cgm.Leftover) when an activator exists and hands it to metricsLoop; reads nothing new itself;rev3=census-ruling-edge-asset-cache-3;basis=adds file:Statfs. runAgent keeps its authority (B,C,D,F). The new site is assetcache.Statfs, an exported assetcache.FS interface value (var Statfs FS = statfsFS{}), not a function value and not a call in runAgent: the ready hook passes it to armEdgeAssetCache as the store's filesystem, and armEdgeAssetCache calls its Space method on the configured data directory (dataDir(): $CARLOS_DATA_DIR, else /data), which calls unix.Statfs there (statfsFS.Space, accepted legacy at census-ruling-edge-asset-cache-2). No request-supplied pathname reaches it.;rev3=census-ruling-remote-metrics-nested;basis=main's body (merged origin/main acfa4f80, under main's own census rulings) plus: snapshots the nested layout (snapshotNestedUnits over /sys/fs/cgroup/carlos.slice/carlos-instances.slice) once at start, before the activator, and hands the metrics loop a unitSources struct (stamped units, routeHostNames, that root and the snapshot); reads nothing new itself;rev3=census-ruling-region-ha-p1a;basis=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): wires region HA P1a into the activator: cfg.Record = haRecordFacts(openDeployStore, boxJudge) (the box's lifetime judge this body already builds with newBoxJudge, nil with host claims on; CI fix) and cfg.Self = lease.CurrentSelf; eb.Lifetimes (the process's lifetime index), eb.Registry, eb.StartupSwept (seedSweptAtStart.Load), eb.FilesStore from newProductionFilesStore (now lease.NewFilesStore, rootaws-loaded, a log line on failure) and lease.SetObligationDir(<data>/.ha-owed) (logged on failure; HA acquires then refuse); this body reads nothing new itself, the same five sites; the reads are those units' own (haRecordFacts and lease's SetObligationDir are new rows on this card); merge of origin/main d7ae1d76: main's own later changes to this body are kept as main has them, under main's rulings (census-ruling-remote-instance-metrics: the metricsOwners closure for metricsLoop; census-ruling-edge-asset-cache-3: the +file:Statfs site, assetcache.Statfs handed to the asset ready hook); this branch's change is the same as above;rev3=census-ruling-region-ha-p1b1;basis=region HA P1b-1: builds one termfence.Confirmer (Self from lease.CurrentSelf at each call, EC2 DescribeInstances method only, client from rootaws.LoadDefaultConfig with retries off, built lazily on first use) and sets eb.OwnerTerminated; this body reads nothing new itself, the same six sites;rev3=census-ruling-rootfs-apps-3;basis=rootfs Plan 3 Task 7: the startup Sweep literal hands its answer to startupSwept, which logs as before and, only on a clean sweep, marks rootfs admission swept (MarkRootfsSwept); same Sweep call, no read added;rev3=census-ruling-managed-fleets-1b;basis=managed fleets 1b (controller ruling after branch review R1, and Paul's R2 ruling): sets svc.Fleet = fleetWakeFor(os.Getenv, identity, identErr, fleetStore) from the identity it already resolves once and the deployment store the fleet loops already opened, and logs an ERROR naming the identity error when the box is on a fleet with an invalid identity. fleetWakeFor reads CARLOS_REGION and CARLOS_FLEET from the same environment. Read sites unchanged (6). Agent, not root; a platform box is unchanged.;rev3=census-ruling-rootfs-apps-6;basis=rootfs Plan 6 Task 12: one call more beside armRunsPass, armInteractivePass(svc, reg, rolloutSink, boxJudge), in the same activator Configure hook, handing it the same box judge; fix round 1 (Astra P2, shutdown): after svc.Shutdown(ctx), shutdownInteractive(ctx) ends and joins every interactive session under the same shutdown budget; the worker's own reads are its units' (interactive.go); this body reads nothing new, the same six sites; merge of origin/main 6f1f6ca6: main's svc.Fleet = fleetWakeFor(...) and its invalid-identity ERROR line are kept as main has them (census-ruling-managed-fleets-1b); this branch's change is the same as above; read sites unchanged (6);rev3=census-ruling-fix-set-aside-exdev;basis=set-aside EXDEV fix: one field more on the agent ExecBackend literal, RawInstanceDir: layout.RawInstanceDir (a pure path join: <dataDir>/.instances/<InstanceID(host)>), so the start rule set-aside moves a copy out through the raw directory instead of through the nosymfollow bind; this body reads nothing new, the same six sites;rev3=census-ruling-durability-3a-escrow;basis=durability 3a Task 3: one more assignment beside eb.FilesStore: eb.EscrowKey = haEscrowKey(os.Getenv("CARLOS_SECRETS_KEY")), the agent's own environment parsed by appconfig.ParsePrivateKey as the moves pass parses it (unset or unparseable: a log line and nil, and HA publication refuses on the box). No path is opened or read, no read site added; the same six sites, offsets moved; B,C,D,F authority retained. Durability 3a Task 4: one more goroutine beside configSyncLoop: go escrowLoop(agentCtx, reg, svc), the escrow sweep every 30 s over the same registry and Service. This body reads nothing new itself; the same six sites, offsets moved; B,C,D,F authority retained. Durability 3a Task 5: one more call beside eb.EscrowKey: wireRawSecretPages(eb, PageOperator, metricsBoxLabel(os.Getenv, readMachineID())), which sets eb.OnRawSecret to page an operator (alerting.Page through PageOperator, LevelIncident) on its own goroutine with a 20 s timeout; metricsBoxLabel and readMachineID are the reads this body already makes for the moves refusal log; no new read site; the same six sites, offsets moved; B,C,D,F authority retained. Merge of origin/main 90c4d3aa: main's own later changes to this body are kept as main has them, under main's rulings; this branch's change is the same as above. Merge of origin/main 00bf5b8c (fleet set-aside EXDEV fix): main's change to this body is kept as main has it, under its own census ruling; this branch's change is unchanged.;rev3=census-ruling-probe-burst-limit;basis=two more sink wirings beside setAnalyticsSink: setProtectionSink(e.SetProtectionRecordOnly) and setAssetOwnersSource(e.AssetOwners), function values the telemetry pass calls; this body reads nothing new, the same six sites; authority B,C,D,F retained; no new root read or write kind;rev3=census-ruling-region-ha-p1b3a;basis=Arm HA placement exactly once on the existing Service before activatorStart and edges publication, wiring AwakeApps and the PageOperator callback; existing six read sites unchanged, no new root authority.;rev3=census-ruling-stateless-replicas-1;basis=Final review I3: start the concrete coordinator's renewal worker with agent setup; existing closeReplicaCoordinator shutdown cancels and joins it before release. No new read sites or credentials. Merge origin/main c59715e7: retain main's armHAPlacement(svc, PageOperator) wiring beside the existing activator setup; stateless coordinator and shutdown wiring remain. Same read sites; no new root read or credential.;rev3=census-ruling-edge-held-streams;basis=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): in the edge-ready callback, calls act.SetHeldWakeHook(e.HeldWake) when act is non-nil (installing the non-blocking wake callback) and stores e.HeldStreamsForStatus in heldStreamsSource. Wiring of in-memory callbacks only; no read added.;rev3=census-ruling-region-ha-p1b3b-t;basis=Wire Service.SetDutyView to the live edge DutySnapshot in the ready callback. No new read; no new loop or cloud operation. B2 wires the registry as the persistent DutyStore before service startup; no new cloud or filesystem path. B3b: arm one journal-backed termination consumer before service startup using agentCtx and the shared confirmer; expose edge tick and join at edge shutdown. No new direct read sites.;rev3=census-ruling-agent-start-demo-1;basis=Passes the existing registry, data store and hibernation prefix into the demo worker, and the existing instance-control client into the demo before-exec hook. No alternate data store or polling loop. Merge resolution against origin/main 9bd45488 retains main's HA departure controller, lifecycle and duty wiring alongside the demo data store and worker; no read site added by the resolution.;rev3=census-ruling-region-ha-p3a;basis=P3a Task 3: install closed fixed admission before every launch source, bind activator/backend and edge, wire the real termination Started lifecycle and role reader after the change index; close before cancellation/child shutdown. No new external reads or cloud authority. Fix R1: move bind/lifecycle/edge-option wiring into wireAgentAdmission and worker listing into runWorkerBootPassAfterAdmission. Worker boot waits for admission before listing then uses unchanged bounded wakes and per-host serialization; whole Route read moves to the helper. No new storage, cloud, or root execution authority. Preserve merged main's agent wiring and census basis; the branch removes one whole Route use by moving worker iteration to the helper, with no added read kind.;rev3=census-ruling-stateless-replicas-2;basis=Slice 3b: arms a fleet-only worker using the existing registry, activator, backend and authenticated console transport. Owned worker stops and joins at shutdown. No new bucket reader. merge of origin/main 9b8b2c50: retain HA duty/departure lifecycle, wake-slot and existing agent wiring alongside the replica placement worker; no new read introduced by resolution. merge of origin/main 6be08467: Retain main demo configuration, admission, build and expiry wiring alongside the replica worker; merge-only body change, no additional read. merge of origin/main 7920cccf: Retain main box-role/group admission wiring and boot publication beside the owned replica worker and shutdown; main moves the boot registry List into runWorkerBootPassAfterAdmission, removing its inline whole Route site. No new read introduced by conflict resolution.;rev3=census-ruling-stateless-replicas-3;basis=Task 1 fix round 1 M3: retain the private snapshot source and cancel/join ownership, but use the replica-health-specific retry loop. It logs its first failure only and retains the existing exponential backoff capped at 30 seconds; unsupported builds return nil. Existing five direct read sites unchanged; no new credentials, bucket reader or app lifecycle action. Fix round 1 Q20: publish Edge.ReplicaSnapshots as a separate in-memory status source, leaving the tenant-visible Upstreams source unchanged. No new external reader or authority.;rev3=census-ruling-region-ha-p3b;basis=Load root-written group marker/configuration, configure signed boot binding and agent receipt completer, wire cancellable admission into departure work and expose cached GroupReaderSnapshot. New indirect boot reads use protected root files; agent-owned receipt controls duplicate initial completion only, never root restart permission. Same five direct sites. Merge 45cebde4 retains the replica health socket lifecycle and setReplicaSource beside GroupReaderSnapshot; no extra read beyond main.;rev3=census-ruling-agent-start-demo-2;basis=agent.go:309-329 opens demo-traffic.db beside the operator-configured registry when a demo domain exists, closes it at shutdown and wires drain-before-purge; :1010-1019 shares the worker and write gate; :1164-1177 installs the fleet identity and closed-until-worker serving callback. One added whole Route pass; the new indirect filesystem/SQL reads are claimed in openDemoTraffic and worker/store units. No request chooses the database pathname.;rev3=census-ruling-region-ha-p1b3b-s;basis=Wire the service duty view to authoritative cached sidecar manifest placement in LifetimeIndex and the edge sidecar projection; missing policy denies duty. Existing instance duty wiring remains.;rev3=census-ruling-region-ha-g2-t3;basis=T3a: wire eb.Page = PageOperator beside OwnerTerminated before departures arm, so suspect-holder pages work if departure setup fails; no new read; existing nine sites and authority unchanged; pages through the existing sink. T3b: publish the same backend through an atomic pointer for the metrics observer, and clear it on return; no new external read or authority.;rev3=census-ruling-agent-start-demo-3;basis=Wire the claim activator and root snapshot client into the demo worker; pass moved readiness to status reporting. Census read-site delta: unchanged (9).;rev3=census-ruling-region-ha-g2-fixes;basis=Wire local pool evidence, live withdrawal activator, startup ingress scan and alias publication, and edge lookup; no new direct sites; new indirect record/claim reads use existing store/judge paths described in ingress helpers.;rev3=census-ruling-region-ha-g2r-fixes;basis=W3: starts the existing record-view backstop loop with a departure-inventory listener (non-blocking, coalesced signal) even without an armed RecordView; it requests the existing full pass (backstopFullDue) there. Same nine read sites; no new read or authority.;rev3=census-ruling-region-ha-graceful-terminate-t2;basis=Derive one signal-time deadline with a 90-second budget; cap departure stop and startup/seed/service shutdown joins by it. No read added.;rev3=census-ruling-static-sweep-periodic;basis=in the edge-ready callback, publishes e.LargestStaticTree in staticTreeSource for the disk alert line (diskAlertFrac in the metrics loop); in-memory wiring only, no read added; read sites unchanged (9);rev3=census-ruling-edge-page-cache-1;basis=wires the exec backend's CurrentInputs into the edge cache (wireCurrentInputs) and, in the ready hook after armEdgeAssetCache (whose returned store it now keeps), calls armEdgePageCache, which does nothing unless CARLOS_PAGE_CACHE=1; read sites unchanged (9); no read added;rev3=census-ruling-gvisor-demos;basis=Capture sandbox resolution and refusal once; log errors once; gate route admission and BeforeExec before process launch. No new root read. Task 5: pass the once-captured sandbox effective mode/config error into ExecBackend, UnitBackend and the immutable Client expectation. Same startup environment/registry reads; swapArming declines gVisor before placement. Task 8: arm read-only status projection with the existing Client.SandboxStatus callback. Agent status now queries the existing root /ready endpoint; no new root authority or guest-file input. Merge2 e8a1ddde: retain main wireCurrentInputs and armEdgePageCache through the existing asset-store ready hook alongside branch once-captured sandbox mode, wake gates and root status wiring. No new direct read; main page-cache helpers retain their own census overlays.;rev3=census-ruling-region-ha-held-build;basis=wires the drain state: svc.SetDrainingSource(boxDrain.IsDraining), svc.SetPeerDrainView(e.PeerDraining), e.SetPeerDrainedHook(svc.DropHoldersNaming); in-memory only; no read added; region HA held-requests Task 5: on group members, starts the drain driver over the activator, the edge and boxDrain, and serves its root-only drain socket; no read added beyond the socket's own Branch review r1: the drain state follows the root start fence on group members (the fence reader is the existing fenceLocation.read, a root-owned fixed path); e.SetPeerUndrainedHook(svc.AllowHoldersNaming) beside the drained hook (memory only); the drain socket serves only the agent's own user. No read added.;rev3=census-ruling-security-review-mitigations;basis=Wire the cached operator flat-layout choice into the exec backend's new-resident refusal; no read source added, existing authority retained. file:Exec@20408,file:Open@2191,file:Statfs@52583,registry:App@13287,registry:Host@48605,whole:Route@13279,whole:Route@47011,whole:Route@48728,whole:Route@48790 bd72b307c6393eb4251ede6a4ff52c6d5116f318f55257ab80a8b8370ee2ba35
+internal/host/layoutleg.go mintLayoutIntentWith legacy accepted-legacy accepted-legacy;rev3=J1;basis=root-route;rev3=census-ruling-security-review-mitigations;basis=Mint nested on nested-default, activator-armed, floor-capable boxes while isolation readiness is pending; wake still gates on readiness. Explicit flat and incapable-box compatibility unchanged; same intent/env/registry sources. whole:Route@762 e07b678da489350b4cecbfd4c22e6fcc64c42697b3e0e0c25c54c90fba4d5a8b
+internal/activator/backend_exec.go ExecBackend.residentLayoutRefusal legacy accepted-legacy accepted-legacy;rev3=census-ruling-security-review-mitigations;basis=New agent-side refusal reads existing Route GoodVersion and ServingVersion and the route's stateless/resident shape; callback reads cached operator choice. No filesystem/store read; served legacy residents and explicit flat remain supported. R4-requested launchRefused marker proves this pre-exec refusal started nothing, allowing existing stop-proof recovery; predicate and sources unchanged. registry:GoodVersion@138,registry:ServingVersion@111,whole:Route@104 eab300984a3579fcb162e5d34530b5d1ae96f1c35e775e9d56cca6967e654f21
+internal/provision/reconcile.go RouteFor authority C,E3 rev3=census-ruling-self-serve-moves-1;basis=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos); also root, in the claim root's landing registration (ClaimRootHTTP.rootLandingRoute) and the relocation install (relocationRecord): census-ruling-seeded-instances's body with two more fields from the record: the row's lifetime pair (rec.Incarnation, rec.MoveSeq), so a row minted outside a move takes the record's lifetime and its last move's sequence (0, 0 for a fieldless record with no move history); every caller gets it, the root ones included: the root callers (ClaimRootHTTP.rootLandingRoute, relocationRecord) now mint (0, move_seq) on a claims-on record, a non-zero sequence once that record has had an offline move (move_seq advances on claims-on offline moves too), which moves Fingerprint and SnapshotFingerprint once for that row; main's C,E3 authority retained; self-serve moves 1 Task 7 (fix round 1: root callers named);rev3=census-ruling-region-ha-p1a;basis=the agent's reconcile passes, and also root's callers (rootupdates.go, rootinventory_install.go and relocationinstall.go on HEAD): one more field copied from the record, HA: rec.HA, so a row minted from a record stamped HA carries the sticky born-HA mark; the record is the console-written instance record each caller already read; root's own code reads nothing of Route.HA, and Fingerprint does not include it (SnapshotFingerprint does, for a set mark); the same nine sites, no read added;rev3=census-ruling-rootfs-apps-3;basis=rootfs Plan 3 Task 2: the row is minted with the record's Runtime (the console-written instance record, guarded by WriteRecord's runtimeFixed); a rootfs row always gets the nested socket and db path under dataDir and no seed or seed source; the paths are computed from the host, not read from the record;rev3=census-ruling-fresh-box-446;basis=#446: a born-HA record mints the nested paths whatever nested says, as a rootfs row already does; same reads;rev3=census-ruling-managed-fleets-1b;basis=managed fleets 1b (Task 2, rule 6): the route also carries Assigned = rec.FleetBoxAt and Moved = rec.FleetBoxMoved, copied from the record it is handed. Read sites unchanged (13). In the agent; in root's claim landing registration (ClaimRootHTTP.rootLandingRoute, shelved claims code) the canonical route gains these two copied fields, which no root check compares (the comparison at rootinventory.go and ValidateAgentInventory read neither). No new input to root.;rev3=census-ruling-agent-start-demo-1;basis=Reads the record descriptor, carries it onto the route, and gives demos nested paths; no new external read.;rev3=census-ruling-stateless-replicas-2;basis=Projects count, canonical boxes, revision, CreatedAt-derived lifetime and stateless hint from the supplied record. No store read; hint does not authorize a database bypass. merge of origin/main 6be08467: Retain main demo nested paths and descriptor stamping beside replica projection; merge-only composition.;rev3=census-ruling-agent-start-demo-3;basis=Translate bound source claim state into operation-owned hold/status and fresh seed state into the destination import gate. Census read-site delta: +registry:HoldOp, +registry:ImportGate, +registry:Seed, +registry:Status.;rev3=census-ruling-edge-page-cache-1;basis=sets the route's new PagesOff from the record (!rec.PagesOn(): true only when the record's optional pages field is present and false); a field of the record it already reads, no new read; also in root's claim landing and relocation install, where the row only carries the column; read sites unchanged (19); no read added;rev3=census-ruling-security-review-mitigations;basis=Read Stateless projected from a validated replica assignment so managed resident copies get nested paths when nested is selected. Canonical path functions only, explicit/external route paths unchanged; authority C,E3 retained. registry:Addr@3259,registry:Addrs@3268,registry:DBPath@1967,registry:DBPath@2755,registry:DBPath@3177,registry:Health@3278,registry:Hibernate@2682,registry:HoldOp@1846,registry:ImportGate@1730,registry:Seed@1771,registry:Seed@3223,registry:SeedSource@3232,registry:Socket@1929,registry:Socket@2717,registry:Socket@3140,registry:Stateless@2698,registry:Status@1835,whole:Route@1666,whole:Route@1692,whole:Route@3316 dec7088b197b904e113d1eefd27a046ff4cd2c920e33126146ef9cbeacad28ef
+internal/activator/backend_exec.go ExecBackend.spawnChildFrom legacy accepted-legacy accepted-legacy;rev3=census-ruling-zddr3;basis=Census ruling zddr3: changed legacy row (comment-only change describing the shim placement); the same class as the accepted-legacy Manager.startIn and placementLive under fix1-merge-review (existing agent delegated-cgroup management remains legacy); no root decision; no registry, /data, release or claim reads. Boundary: the agent's own delegated cgroup subtree (including its scratch probe child), /proc/self, and pipes to and from its own parent, running as carlos.;rev3=census-ruling-region-ha-p1a;basis=the agent as carlos (the flat start body): the same change as seedChild: ensureAdminTokenFor(ctx, rt, paths) for the token (the same flat path), the key's producer carrying the HA mint decision, and launchEnvLayer(ctx, rt) for the env and key layer the replica gate reads; a non-HA host's token, key and env are produced and read as before; +whole:Route; only adds refusals for HA hosts;rev3=census-ruling-stateless-replicas-1;basis=Task 3a: Use the verified generation/launch mode to remove CARLOS_DB after environment merges and omit the binary --db argument where applicable. Existing runtime, layout, secrets and exec gates remain; route reads are mode projection only.;rev3=census-ruling-edge-page-cache-1;basis=the control listener is now built with the whole route (edge.ListenControl(controlSocket, rt, ...)), the +whole:Route site; it computes the launch inputs once from the build it execs by path (a staged exe's caller-named build, or the gate-resolved pinned version; "" for an unpinned live link) and fileEnv it already read, keeps them on the childProc, and for a live-link spawn publishes them to the in-memory cache (NoteProcessInputs) beside the existing purge; no new file read;rev3=census-ruling-gvisor-demos;basis=Task 5: gate launch using startup-captured mode and existing route/role/layout before preparation or execution; migrate structured root start identity and reject mismatches. Unsupported gVisor paths refuse; native behavior and existing root authority checks retained. No new root read source. Merge2 e8a1ddde: retain main build parameter, pinned live identity, launchInputs from captured build/environment, and current-process input publication. edge.ListenControl now receives the whole Route as main requires (+whole:Route); no new filesystem or storage input. Branch sandboxLaunch remains before preparation and spawn; existing direct primitive gate unchanged.;rev3=census-ruling-security-review-mitigations;basis=Enforce the unchanged never-served resident refusal once at the shared flat/foreign primary binary spawn sink, before placement, live-link/token/env/control preparation or execution. Covers plain, generation and staged Service wakes; existing served/explicit-flat exemptions and other gates retained. No new filesystem/store source. file:Command@11357,registry:Host@12640,registry:Host@13001,registry:Host@13095,registry:Host@258,registry:Host@4214,registry:Host@4269,registry:Host@4349,registry:Host@4563,registry:Stateless@11288,whole:Route@11180,whole:Route@11329,whole:Route@11737,whole:Route@13392,whole:Route@13484,whole:Route@1527,whole:Route@189,whole:Route@1944,whole:Route@2305,whole:Route@287,whole:Route@4447,whole:Route@4757,whole:Route@476,whole:Route@6828,whole:Route@9093 62a25da95d4b4b98122648e98d7348f1159f50077e7cfb8d282d811627580dfd
+@coverage . a8a543b00d620367c1c8cd92405990fa80f17cb24f064272a73b3b0181f0c482
+@coverage internal/activator e70ae33ab4b4fc57bada29629ddb3b3292a98265f28e861406f63e62be616755
+@coverage internal/host 7f8ae4cdb0dfe0bb2d6780500ad16c32b94fad06d6b8ac5ac28170208ade8ee1
+@coverage internal/provision a18e60c5f5e1369c16ffeb3ca53169110ff12c0cf11125d4698bd7f0ebb020b3
diff --git a/internal/rootfsimage/zstd_malformed_test.go b/internal/rootfsimage/zstd_malformed_test.go
new file mode 100644
index 000000000..abc446f30
--- /dev/null
+++ b/internal/rootfsimage/zstd_malformed_test.go
@@ -0,0 +1,42 @@
+package rootfsimage
+
+import (
+ "archive/tar"
+ "bytes"
+ "testing"
+)
+
+// malformedZstd is a zstd frame whose sequence decoding panicked
+// github.com/klauspost/compress before v1.20.2 (security review
+// 2026-11-09, zstd-probe). It must now fail as an ordinary decode error.
+func malformedZstd() []byte {
+ b := []byte{0x28, 0xb5, 0x2f, 0xfd, 0x00, 0x38, 0x74, 0x06, 0x00, 0x42, 0xb8, 0x32, 0x0d, 0x1a, 0x00, 0x00, 0x00, 0x90, 0xaf, 0xfa, 0xff, 0x03, 0x00, 0x80, 0xff, 0x7f}
+ b = append(b, bytes.Repeat([]byte{0xa5, 0x94, 0x52, 0x4a, 0x29}, 37)...)
+ b = append(b, 0xa5, 0x94, 0x12, 0x00, 0xad, 0x56, 0x03, 0xee, 0xff, 0xdf, 0xb3, 0x1a, 0x1c, 0x1a, 0x00, 0xe0, 0xff, 0x1f, 0x0f, 0xb1, 0x9c, 0x5a, 0xcf, 0x4d, 0xe4, 0x1d, 0x7b, 0xab, 0x99, 0x5e, 0x01, 0x51, 0xa4, 0x73, 0xd8, 0xb1, 0xf3, 0x39, 0x4b, 0x67, 0xf6, 0xab, 0x1a, 0xab, 0x1a, 0xab, 0x1a)
+ b = append(b, bytes.Repeat([]byte{0x8c, 0x31, 0xc6, 0x18, 0x63}, 1365)...)
+ b = append(b, 0x8c, 0x31)
+ b = append(b, bytes.Repeat([]byte{0x63, 0x8c, 0x31, 0xc6, 0x18}, 1365)...)
+ b = append(b, 0x63, 0x2c)
+ b = append(b, bytes.Repeat([]byte{0x31, 0xc6, 0x18, 0x63, 0x8c}, 1365)...)
+ b = append(b, 0x31, 0x46)
+ b = append(b, bytes.Repeat([]byte{0x31, 0xc6, 0x18, 0x63, 0x8c}, 1365)...)
+ return append(b, 0x31, 0x06, 0x00)
+}
+
+// A layer blob that is a valid zstd frame (one tar header announcing a
+// regular file) followed by a malformed frame, which holds the file's body,
+// is refused by OpenLayout as an error, not a panic in the decoder. The
+// header comes first because the tar reader would refuse a malformed
+// frame in first position before its bad block was decoded.
+func TestOpenLayoutRefusesAMalformedZstdLayer(t *testing.T) {
+ var hdr bytes.Buffer
+ if err := tar.NewWriter(&hdr).WriteHeader(&tar.Header{Name: "f", Typeflag: tar.TypeReg, Mode: 0o644, Size: 1 << 20}); err != nil {
+ t.Fatal(err)
+ }
+ layer := append(zstded(t, hdr.Bytes()), malformedZstd()...)
+ dir := t.TempDir()
+ writeLayout(t, dir, false, tImage{platform: "linux/arm64", layers: [][]byte{layer}})
+ if _, err := OpenLayout(dir, t.TempDir()); err == nil {
+ t.Fatal("OpenLayout accepted a malformed zstd layer")
+ }
+}
diff --git a/pipeline.go b/pipeline.go
index e231a1eb3..df212a029 100644
--- a/pipeline.go
+++ b/pipeline.go
@@ -262,12 +262,7 @@ func runPipelineShow(args []string) {
log.Fatal(err)
}
channels := pipelineOrDefault(p)
- // A single-channel pipeline (the "no pipeline.json" default, or a real
- // one-channel pipeline someone composed down to that) is not shown as a
- // one-row ladder table — there is no order or rule to tabulate yet, and
- // a table with one row reads as ceremony around nothing (Task 10
- // controller ruling 5). The hint names the one command that grows it.
- if len(channels) == 1 {
+ if len(channels) == 1 && channels[0] == (apiPipelineChannel{Name: "edge"}) {
fmt.Fprintf(stdout, "%s — one channel, no pipeline set (carlos pipeline init --template edge-production|full-ladder adds more)\n",
channels[0].Name)
} else {
diff --git a/pipeline_test.go b/pipeline_test.go
index 28948b6c5..76e3605be 100644
--- a/pipeline_test.go
+++ b/pipeline_test.go
@@ -547,3 +547,43 @@ func TestPipelineDirectModeRefused(t *testing.T) {
t.Fatal("want direct mode (nil session) with CARLOS_DEPLOYMENT_DIR set")
}
}
+
+func TestPipelineShowSingleChannelRules(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ channel apiPipelineChannel
+ defaultPipeline bool
+ }{
+ {"default", apiPipelineChannel{Name: "edge"}, true},
+ {"passkey", apiPipelineChannel{Name: "edge", Passkey: true}, false},
+ {"promote approvals", apiPipelineChannel{Name: "edge", PromoteApprovals: 1}, false},
+ {"change approvals", apiPipelineChannel{Name: "edge", ChangeApprovals: 1}, false},
+ {"bake", apiPipelineChannel{Name: "edge", Bake: "1h"}, false},
+ {"zero bake", apiPipelineChannel{Name: "edge", Bake: "0s"}, false},
+ {"custom", apiPipelineChannel{Name: "production"}, false},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ useTempCredentials(t)
+ clearDeploymentEnv(t)
+ mux := http.NewServeMux()
+ mux.HandleFunc("GET /api/cli/apps/"+apiTestAccount+"/titogo/pipeline", func(w http.ResponseWriter, r *http.Request) {
+ json.NewEncoder(w).Encode(map[string]any{"pipeline": apiPipeline{Channels: []apiPipelineChannel{tc.channel}}})
+ })
+ mux.HandleFunc("GET /api/cli/apps/"+apiTestAccount+"/titogo/pending", func(w http.ResponseWriter, r *http.Request) {
+ json.NewEncoder(w).Encode(map[string]any{"pending": []map[string]any{}})
+ })
+ ts := httptest.NewServer(mux)
+ defer ts.Close()
+ loginTo(t, ts.URL, "vicky@keymail.dev")
+ buf := captureStdout(t)
+ runPipeline([]string{"show", "-app", "titogo", "-account", apiTestAccount})
+ out := buf.String()
+ if strings.Contains(out, "no pipeline set") != tc.defaultPipeline {
+ t.Fatalf("unexpected description: %s", out)
+ }
+ if strings.Contains(out, "RULES") == tc.defaultPipeline {
+ t.Fatalf("unexpected table: %s", out)
+ }
+ })
+ }
+}