carlos / platform Public

Merge remote-tracking branch 'origin/main' into region-ha-p1b2-forwarding

# Conflicts:
#	internal/provision/testdata/plan14-root-reads-chain.tsv
claude agent, operated by paul@keymail.dev e8c69ed069c24d59bfd912c31c00950d1ef68304 parent 2371792parent a66482c
46 files changed, +1,931 −314
  • docs/superpowers/notes/census-proposal-region-ha-p1b2.md +1 −1
  • docs/superpowers/notes/census-proposal-rootfs-check-volumes.md +23 −0
  • docs/superpowers/notes/census-proposal-rootfs-fleet-followups.md +29 −0
  • docs/superpowers/reviews/CODEX-FINDINGS-billing-success-r1.md +20 −0
  • docs/superpowers/reviews/CODEX-FINDINGS-rootfs-check-volumes-R1.md +17 −0
  • docs/superpowers/reviews/CODEX-FINDINGS-rootfs-check-volumes-R2.md +26 −0
  • docs/superpowers/reviews/CODEX-FINDINGS-rootfs-check-volumes-R3.md +18 −0
  • docs/superpowers/reviews/CODEX-FINDINGS-rootfs-fleet-followups-R1.md +30 −0
  • docs/superpowers/reviews/CODEX-REVIEW-BRIEF-billing-success.md +28 −0
  • docs/superpowers/reviews/CODEX-REVIEW-BRIEF-rootfs-check-volumes-R2.md +11 −0
  • docs/superpowers/reviews/CODEX-REVIEW-BRIEF-rootfs-check-volumes-R3.md +13 −0
  • docs/superpowers/reviews/CODEX-REVIEW-BRIEF-rootfs-check-volumes.md +33 −0
  • docs/superpowers/reviews/CODEX-REVIEW-BRIEF-rootfs-fleet-followups.md +29 −0
  • internal/activator/logsink.go +26 −0
  • internal/activator/prepare.go +12 −7
  • internal/activator/rootfs_process_logs_test.go +112 −0
  • internal/activator/rootfsrelease.go +3 −7
  • internal/applog/record.go +5 −0
  • internal/applog/sink.go +15 −0
  • internal/applog/sink_test.go +26 −0
  • internal/console/apiinstances.go +47 −2
  • internal/console/billingchange.go +44 −6
  • internal/console/billingchange_test.go +106 −16
  • internal/console/billingcheckout.go +3 −3
  • internal/console/billingcheckout_test.go +7 −7
  • internal/console/billingpage.go +73 −34
  • internal/console/billingpage_copy.go +17 −6
  • internal/console/billingpage_test.go +165 −72
  • internal/console/fleethealth_test.go +124 −0
  • internal/console/templates/billing.html +0 −12
  • internal/console/templates/billing_done.html +17 −0
  • internal/console/templates/layout.html +27 −30
  • internal/provision/plan9_b8_census_test.go +1 −1
  • internal/provision/rootfs_check_volumes_census_test.go +37 −0
  • internal/provision/rootfs_fleet_followups_census_test.go +38 −0
  • internal/provision/testdata/plan14-root-reads-chain.tsv +3 −1
  • internal/provision/testdata/plan14-root-reads-region-ha-p1b2.tsv +1 −1
  • internal/provision/testdata/plan14-root-reads-rootfs-check-volumes.tsv +8 −0
  • internal/provision/testdata/plan14-root-reads-rootfs-fleet-followups.tsv +15 −0
  • logs_e2e_test.go +120 −59
  • main.go +4 −0
  • ship_check.go +114 −29
  • ship_check_prepare_test.go +210 −0
  • ship_check_probe.go +47 −0
  • ship_check_test.go +225 −20
  • ship_rootfs_unix_test.go +1 −0

CI failed — run details

Intent

Human

<task-notification> <task-id>brhefinvc</task-id> <tool-use-id>toolu_0173ScZ8eA8g8veFQ9PCD3Aq</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/953e7524-2e06-4308-b9ce-fd1b38579971/tasks/brhefinvc.output</output-file> <status>completed</status> <summary>Background command "Commit the census, push, and run the Astra census review" completed (exit code 0)</summary> </task-notification>

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

diff --git a/docs/superpowers/notes/census-proposal-region-ha-p1b2.md b/docs/superpowers/notes/census-proposal-region-ha-p1b2.md
index 397976df7..8f6f2df1f 100644
--- a/docs/superpowers/notes/census-proposal-region-ha-p1b2.md
+++ b/docs/superpowers/notes/census-proposal-region-ha-p1b2.md
@@ -34,6 +34,6 @@ New dispositions, which census-propose wrote and the reviewer checks against the
- new `internal/edge/forwardha.go:Edge.frontForwardHA`: reads +registry:HA, +registry:Host, +whole:Route ×3; written legacy, accepted-legacy, frozen
- reads `internal/activator/activator.go:Service.serveWakeError`: +whole:Route; keeps diagnostic, task C,J4
-Seal: `94b8ccf921f64be24a4773f72d55a8e24ceba3acfb40eefe3b56af6f5b008138` → `b8341530f4a5e8101746f610ee8eb25bd273bed6f45bf6a2ff279e9b8c20c0b1`.
+Seal: `78b7e7e30ad3ada44388a4ee16f3950ef888ae03e552477dcbfbb07c51ffb83e` → `f8190d29dc824bfb15be305c0363f95709239d1711df7fbe4fb86bb5a423985c`.
Overlay: `internal/provision/testdata/plan14-root-reads-region-ha-p1b2.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`.
diff --git a/docs/superpowers/notes/census-proposal-rootfs-check-volumes.md b/docs/superpowers/notes/census-proposal-rootfs-check-volumes.md
new file mode 100644
index 000000000..c23666568
--- /dev/null
+++ b/docs/superpowers/notes/census-proposal-rootfs-check-volumes.md
@@ -0,0 +1,23 @@
+# Census approval: rootfs-check-volumes
+
+Ruling `census-ruling-rootfs-check-volumes`. The independent reviewer approves or rejects every change below, 1 with a new disposition; nothing goes to the census owner (Paul, #280, 2026-10-26).
+
+| unit | change | read sites | what changed |
+|---|---|---|---|
+| `ship_check.go` `rootfsCheck.runArgs` | body | unchanged (2) | R2 P1: the data and run volume mounts (-v) now carry :nocopy through rootfsCheck.volumeMount, so Docker and Podman never fill an empty check volume from the image directory at the mount point (which would reset the prepared owner and mode); same volumes, same paths, same probe mount, nothing else in the argv changed. Runs on the person's machine as the person; no box unit; no read added. |
+
+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.
+
+Recorded dispositions, which each change must still satisfy:
+
+- `ship_check.go` `rootfsCheck.runArgs`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-rootfs-apps-1;basis=root-input (J4, as main's db.go units); the carlos CLI on a person's machine, as the person (no box unit): new (rootfs Plan 1), builds the docker or podman run argv for one check container; the scanner matches the word Command, here a field of release.Process (a process's argv), not os/exec; reads no file; decides nothing for root
+
+New dispositions, which census-propose wrote and the reviewer checks against the unit's reads and the diff:
+
+- new `ship_check_probe.go:prepareCheckDir`: reads +file:Lstat; written legacy, accepted-legacy, frozen
+
+Seal: `94b8ccf921f64be24a4773f72d55a8e24ceba3acfb40eefe3b56af6f5b008138` → `042684bf5af6f61ce8b87f10b68a42b08d131ba4cb5bcab16320c7b032a724e6`.
+
+Overlay: `internal/provision/testdata/plan14-root-reads-rootfs-check-volumes.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`.
diff --git a/docs/superpowers/notes/census-proposal-rootfs-fleet-followups.md b/docs/superpowers/notes/census-proposal-rootfs-fleet-followups.md
new file mode 100644
index 000000000..ec62a9318
--- /dev/null
+++ b/docs/superpowers/notes/census-proposal-rootfs-fleet-followups.md
@@ -0,0 +1,29 @@
+# Census approval: rootfs-fleet-followups
+
+Ruling `census-ruling-rootfs-fleet-followups`. The independent reviewer approves or rejects every change below, 1 with a new disposition; nothing goes to the census owner (Paul, #280, 2026-10-26).
+
+| unit | change | read sites | what changed |
+|---|---|---|---|
+| `internal/activator/prepare.go` `ExecBackend.prepareKeyedAt` | body | unchanged (13) | names the process for the role log listener: release.ProcessWeb when rt.Rootfs() and the role is run, else none, passed to logEmitter; reads rt.Runtime through Rootfs(); no file, path or env read added or moved |
+| `internal/activator/prepare.go` `ExecBackend.prepareWorker` | body | unchanged (6) | passes the worker name (already checked by release.ValidWorkerName at the top) to logEmitter as the process; no read added or moved |
+| `internal/activator/prepare.go` `ExecBackend.logEmitter` | sites | -registry:App, -registry:Host | takes a process name and returns appLineEmitter(b.Logs, rt, process); the route account, app and host reads moved into appLineEmitter; no file read |
+| `internal/activator/rootfsrelease.go` `Service.releaseAppLog` | sites | -registry:App, -registry:Host | returns lineEmitter(appLineEmitter(a.Logs, rt, release.ProcessRelease)); the route reads moved into appLineEmitter; no file read |
+
+Envelopes re-pinned: `internal/activator`, `internal/applog`.
+
+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/activator/prepare.go` `ExecBackend.prepareKeyedAt`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-carlos-run;basis=Re-digested at the pre-land merge: the body includes main's own change under census ruling zddr4, with no further change from this branch beyond carrying main's new early return into the six-value signature. the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): body of the frozen prepareAt, which is now its wrapper; it also returns the instance key's layer and reads no env for the cmd role; same reads, same nested launch paths;rev3=census-ruling-wake-latency-2;basis=takes an optional timer and marks its steps with time.Now() (dirs, admin token, instance key, env, control socket, key gate, logs); no read added or moved;rev3=census-ruling-region-ha-p1a;basis=the agent as carlos, run and seed roles only, under a 30 s context (haSecretsBudget): the token producer is ensureAdminTokenFor(hctx, rt, p) (on this nested path the same beneath producer, EnsureAdminTokenBeneath's, plus the HA mint decision inside it); ensureInstanceKeyFor now gets hctx instead of context.Background(), so the key's bucket read is bounded by 30 s as well as configReadTimeout; the env is launchEnvLayer(hctx, rt) (instanceEnvLayer for a non-HA host; for an HA host one capture, published and acknowledged); a test seam (haLaunchHooks.afterGate, nil in production) is called before the producers. The separate haMintGate and haSecretsReady calls are gone (final fix F2). Sites against main: -registry:Host (the rt.Host+".env" argument EnsureAdminTokenBeneath took) and +whole:Route (rt to launchEnvLayer); the cmd role and a non-HA host are unchanged
+- `internal/activator/prepare.go` `ExecBackend.prepareWorker`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-rootfs-apps-3-workers;basis=rootfs Plan 3 Group W, W1: prepare for a worker: the instance's two directories and the worker log socket's, the worker's stale exit records cleared by its name prefix (another worker's and every generation's kept), its log listener bound where root's worker drop-in points StandardOutput=; reads no environment file; binds no control listener; asks no replica gate
+- `internal/activator/prepare.go` `ExecBackend.logEmitter`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=J1;basis=root-route
+- `internal/activator/rootfsrelease.go` `Service.releaseAppLog`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-rootfs-apps-3-release;basis=rootfs Plan 3 Group R, R1 [pf R1.5]: new; the writer a release's output goes through: each line to the instance's own app log (a.Logs.App(account, app, host, line)); reads the route's account, app and host for the log's key; no file read
+
+New dispositions, which census-propose wrote and the reviewer checks against the unit's reads and the diff:
+
+- new `internal/activator/logsink.go:appLineEmitter`: reads +registry:App, +registry:Host, +whole:Route; written legacy, accepted-legacy, frozen
+
+Seal: `042684bf5af6f61ce8b87f10b68a42b08d131ba4cb5bcab16320c7b032a724e6` → `78b7e7e30ad3ada44388a4ee16f3950ef888ae03e552477dcbfbb07c51ffb83e`.
+
+Overlay: `internal/provision/testdata/plan14-root-reads-rootfs-fleet-followups.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`.
diff --git a/docs/superpowers/reviews/CODEX-FINDINGS-billing-success-r1.md b/docs/superpowers/reviews/CODEX-FINDINGS-billing-success-r1.md
new file mode 100644
index 000000000..6432dd9f1
--- /dev/null
+++ b/docs/superpowers/reviews/CODEX-FINDINGS-billing-success-r1.md
@@ -0,0 +1,20 @@
+# Astra findings: billing-success, round 1 of 3
+
+gpt-6-astra via codex, high, at e0630a00. Unedited.
+
+Reviewed `origin/main...e0630a00410c446e31fd6c80171ad48bf552005a`, round 1. No P1 findings.
+
+1. **P2 — A missing subscription counts as a successful refresh.**
+ [billingchange.go:554](/home/paulca/.cache/tmp/claude-1001/billing-success/internal/console/billingchange.go:554) discards the returned subscription and uses only `err == nil`. However, [refreshLocked:293](/home/paulca/.cache/tmp/claude-1001/billing-success/internal/console/billingsync.go:293) returns a nil subscription without an error when the provider answers `ErrNotFound` and recording the billing problem succeeds.
+
+ **Failure scenario:** An upgrade or pack increase is applied, then the refresh returns `ErrNotFound`. The new limits remain unsynced, but the redirect carries the success marker and purchase-specific success flash. The billing problem prevents the success screen, leaving the normal page with old limits and a flash claiming the purchase is ready.
+
+ **Fix:** Require `err == nil && sub != nil` before selecting the success reply. Add a regression test that returns `ErrNotFound` on the refresh after an applied change and expects the generic flash without a marker.
+
+ **Fault family:** Purchase confirmation must require a completed subscription refresh.
+
+No P3 findings. Apply the P2 fix without reopening review.
+
+Validation: diff whitespace checks and formatting passed; static checks found CSRF fields in all nine billing POST forms. Targeted tests could not start because the read-only sandbox blocked Go’s build directory. No files changed.
+
+**READY AFTER FIXES**
\ No newline at end of file
diff --git a/docs/superpowers/reviews/CODEX-FINDINGS-rootfs-check-volumes-R1.md b/docs/superpowers/reviews/CODEX-FINDINGS-rootfs-check-volumes-R1.md
new file mode 100644
index 000000000..e2be49076
--- /dev/null
+++ b/docs/superpowers/reviews/CODEX-FINDINGS-rootfs-check-volumes-R1.md
@@ -0,0 +1,17 @@
+Reviewed `03e08f569cb2ecd07e0ecdc1ceba5d29f9b8cbad`, round 1/3.
+
+- **P1 — Helper container collides with a valid worker named `prepare`.** Verified in [ship_check.go:210](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/rootfs-check-volumes/ship_check.go:210): the helper requests `<prefix>-prepare`, remains until deferred cleanup, and `start` at line 300 assigns that same name to worker `prepare`. `ValidWorkerName` permits it (`internal/release/rootfs.go:70–85`). A healthy app with this worker fails its check when the runtime rejects the duplicate container name. **Fix:** give the helper a name outside the worker-name grammar and add a regression test whose fake rejects duplicate names. **Invariant:** internal helper names must not overlap valid process names.
+
+- **P2 — Tests do not pin the ownership transition or chmod-before-chown ordering.** [ship_check_prepare_test.go:20](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/rootfs-check-volumes/ship_check_prepare_test.go:20) passes the directory’s existing UID/GID at line 39. Verified by inspection: deleting `Lchown`, or moving it before `Chmod`, would satisfy these assertions. Such regressions would prevent UID 65534 from writing, or make chmod fail without `CAP_FOWNER`. **Fix:** add a capability-constrained integration test that changes ownership from root to 65534 and confirms that user can write; verify both mutations fail. **Invariant:** preparation must establish writable ownership using only `CAP_CHOWN`.
+
+No P3 findings.
+
+Census verdicts:
+
+- **APPROVE — `ship_check_probe.go:prepareCheckDir`.** Read lines 108–140. The `file:Lstat` read and `legacy / accepted-legacy` disposition match the container-only caller. It refuses a final symlink or non-directory, changes mode before ownership, and does not recurse.
+- **APPROVE — envelope `.`.** Read changed code in `main.go:21–51`, `ship_check.go:132–153,180–239,299–365`, and `ship_check_probe.go:108–140`; traced import, probe selection and cleanup. Import discards source execution metadata, the helper runs the selected probe with fixed arguments, and no box-root caller gains a new input path. The P1 collision is a functional defect.
+- **APPROVE — record-write re-pin `main.go:main`.** Read the dispatch and `internal/provision/rootfs_check_volumes_census_test.go:16–37`. The new dispatch writes no record; the `instances` and `sidecars` literals remain unchanged.
+
+Targeted check and census tests were attempted but stopped before compilation: Go could not create its work directory under read-only `$TMPDIR`. `GOCACHE` remained unset. No files changed; no full suites or mutation runs executed.
+
+NOT READY
\ No newline at end of file
diff --git a/docs/superpowers/reviews/CODEX-FINDINGS-rootfs-check-volumes-R2.md b/docs/superpowers/reviews/CODEX-FINDINGS-rootfs-check-volumes-R2.md
new file mode 100644
index 000000000..cad84514b
--- /dev/null
+++ b/docs/superpowers/reviews/CODEX-FINDINGS-rootfs-check-volumes-R2.md
@@ -0,0 +1,26 @@
+- **R1 P1 — resolved.** The helper uses `<prefix>_prepare`, outside the worker-name grammar ([ship_check.go:215](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/rootfs-check-volumes/ship_check.go:215)). The fake rejects duplicate names, and the regression covers worker `prepare`.
+- **R1 P2 — resolved.** [ship_check_prepare_test.go:86](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/rootfs-check-volumes/ship_check_prepare_test.go:86) asserts chmod 0700 before lchown 65534:65534, through both function and verb. Removing or reversing those calls breaks the assertion.
+
+Reviewed `d57b4bf04c4908f519fc17f6255e0e0dc2a3acc9`, round 2/3.
+
+**P1 — Docker volume population can undo preparation before the first app process starts.** Both the helper ([ship_check.go:220](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/rootfs-check-volumes/ship_check.go:220)) and app processes ([ship_check.go:286](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/rootfs-check-volumes/ship_check.go:286)) mount the data volume without disabling image-content copying.
+
+Failure scenario: a valid image contains an empty `/data/instances/check` directory, mode 0755. Import normalizes its owner to 0:0. Preparation leaves the volume empty but changes its owner to 65534:65534. When Docker creates release—or web without release—it populates the still-empty volume again, restoring the image directory’s ownership and mode. UID 65534 then cannot create `CARLOS_DB`, so a healthy app fails its check.
+
+Verified by source inspection, not a runtime reproduction: Docker skips population only when the destination contains entries; its copy implementation restores directory metadata.
+
+[https://raw.githubusercontent.com/moby/moby/v27.5.1/container/container_unix.go](https://raw.githubusercontent.com/moby/moby/v27.5.1/container/container_unix.go), [https://raw.githubusercontent.com/containerd/continuity/main/fs/copy.go](https://raw.githubusercontent.com/containerd/continuity/main/fs/copy.go), [https://raw.githubusercontent.com/containerd/continuity/main/fs/copy_linux.go](https://raw.githubusercontent.com/containerd/continuity/main/fs/copy_linux.go)
+
+**Fix:** disable image-content copying on every data-volume mount, using syntax supported by each runtime. Add a regression with that empty directory present in the image, asserting UID 65534 can write after the next container starts. **Invariant/fault family:** prepared data-volume ownership must remain writable by the check user across container launches.
+
+No new P2 or P3 findings.
+
+Census verdicts:
+
+- **APPROVE — `ship_check_probe.go:prepareCheckDir`.** Read lines 108–147. `file:Lstat` and `legacy / accepted-legacy` match the container-only caller. Final symlinks and non-directories are refused; chmod precedes lchown; neither recurses.
+- **APPROVE — envelope `.`.** Read `main.go:21–51`, `ship_check.go:132–243,303–369`, and `ship_check_probe.go:108–147`; traced import, probe selection and cleanup. No box-root caller gains an input path or weaker validation. The finding above concerns local-check functionality.
+- **APPROVE — record-write re-pin `main.go:main`.** Read the dispatch and `internal/provision/rootfs_check_volumes_census_test.go:16–37`. The added dispatch writes no record; the `instances` and `sidecars` literals remain unchanged.
+
+Targeted check and census tests stopped before compilation because `$TMPDIR` is read-only. GOCACHE remained unset. No full suites ran; no files changed.
+
+NOT READY
\ No newline at end of file
diff --git a/docs/superpowers/reviews/CODEX-FINDINGS-rootfs-check-volumes-R3.md b/docs/superpowers/reviews/CODEX-FINDINGS-rootfs-check-volumes-R3.md
new file mode 100644
index 000000000..65e77fbbb
--- /dev/null
+++ b/docs/superpowers/reviews/CODEX-FINDINGS-rootfs-check-volumes-R3.md
@@ -0,0 +1,18 @@
+- **R1 P1 — resolved.** Helper name `<prefix>_prepare` cannot collide with worker names ([ship_check.go:215](ship_check.go:215)); the regression fake rejects duplicate names.
+- **R1 P2 — resolved.** Tests pin chmod 0700 before lchown 65534:65534, including the verb’s arguments ([ship_check_prepare_test.go:86](ship_check_prepare_test.go:86)).
+- **R2 P1 — resolved.** Every data/run volume mount uses `:nocopy`; the regression covers prepare, release, web and worker ([ship_check_test.go:695](ship_check_test.go:695)).
+
+Reviewed commit `05e4e6b23c28351d178580865545998173cec811`, round 3/3, including the R2 fix and whole branch against `1fa2a99b`.
+
+No new P1, P2 or P3 findings. Runtime syntax was cross-checked against the Moby parser and Podman documentation: [https://raw.githubusercontent.com/moby/moby/v27.5.1/volume/mounts/linux_parser.go](https://raw.githubusercontent.com/moby/moby/v27.5.1/volume/mounts/linux_parser.go), [https://docs.podman.io/en/v5.2.2/markdown/podman-run.1.html](https://docs.podman.io/en/v5.2.2/markdown/podman-run.1.html).
+
+Census verdicts:
+
+- **APPROVE — `ship_check_probe.go:prepareCheckDir`.** Read lines 108–147. `file:Lstat`, `legacy / accepted-legacy` remains appropriate for the container-only caller. Final symlinks and non-directories are refused; chmod precedes lchown; neither recurses.
+- **APPROVE — `ship_check.go:rootfsCheck.runArgs`.** Read lines 246–312. The body change adds `:nocopy` through `volumeMount`; paths, probe mount, privileges and command construction retain their checks. No file read or box-root authority is added; the existing disposition remains appropriate.
+- **APPROVE — envelope `.`.** Read `main.go:21–51`, `ship_check.go:108–382,526–544`, and `ship_check_probe.go:108–147,223–259`; traced import and normalization. The helper executes the selected probe with fixed arguments, cleanup records resources before creation, and release failure/timeout behavior is preserved. No box-root input path or weaker validation is introduced.
+- **APPROVE — record-write re-pin `main.go:main`.** Read the dispatch diff and `internal/provision/rootfs_check_volumes_census_test.go:16–37`. The new dispatch writes no record; the `instances` and `sidecars` literals are unchanged.
+
+Targeted check and census tests stopped before compilation because `$TMPDIR` is read-only. GOCACHE remained unset. Formatting and diff checks passed. No full suites ran; no files changed.
+
+READY
\ No newline at end of file
diff --git a/docs/superpowers/reviews/CODEX-FINDINGS-rootfs-fleet-followups-R1.md b/docs/superpowers/reviews/CODEX-FINDINGS-rootfs-fleet-followups-R1.md
new file mode 100644
index 000000000..f6b0b2039
--- /dev/null
+++ b/docs/superpowers/reviews/CODEX-FINDINGS-rootfs-fleet-followups-R1.md
@@ -0,0 +1,30 @@
+No P1 findings.
+
+**P2 — Fleet HEALTH can describe an earlier instance lifetime.** At [apiinstances.go:498](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/rootfs-fleet-followups/internal/console/apiinstances.go:498), `fleetHealth` accepts the rollout view without checking when its box report was generated. The platform-remote path explicitly rejects reports generated before `rec.CreatedAt` at [remoteinstances.go:344](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/rootfs-fleet-followups/internal/console/remoteinstances.go:344).
+
+If an instance is deleted and recreated with the same host, account and app while its previous snapshot remains fresh, the new row inherits the old instance’s `Running`, `Asleep` or `Failed` word. It should remain unknown until a report covers the new record.
+
+**Fix:** retain the snapshot’s `GeneratedAt` in the rollout join and require it to be after `rec.CreatedAt` before deriving fleet health. Add an API witness with a report predating the record and a newer-report control.
+
+**Invariant / fault family:** health observations must belong to the current instance lifetime.
+
+No P3 findings.
+
+Census verdicts for `ff0605208c91c02b86beae5fdb12136e0d10ca88`:
+
+| Unit or envelope | Verdict and evidence |
+|---|---|
+| `ExecBackend.prepareKeyedAt` | **APPROVE**, existing legacy disposition. [prepare.go:179](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/rootfs-fleet-followups/internal/activator/prepare.go:179): adds process selection; launch gates and filesystem operations remain intact. |
+| `ExecBackend.prepareWorker` | **APPROVE**, existing legacy disposition. [prepare.go:209](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/rootfs-fleet-followups/internal/activator/prepare.go:209): validated worker name reaches the existing listener; no additional reads. |
+| `ExecBackend.logEmitter` | **APPROVE**, existing legacy disposition. [prepare.go:325](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/rootfs-fleet-followups/internal/activator/prepare.go:325): delegates route attribution to `appLineEmitter`. |
+| `Service.releaseAppLog` | **APPROVE**, existing legacy disposition. [rootfsrelease.go:353](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/rootfs-fleet-followups/internal/activator/rootfsrelease.go:353): same output destination, with the release process name. |
+| `appLineEmitter` | **APPROVE**, new `legacy / accepted-legacy` disposition. [logsink.go:47](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/rootfs-fleet-followups/internal/activator/logsink.go:47): reads route identity and invokes an in-memory sink; grants no filesystem or execution authority. |
+| `internal/activator` envelope | **APPROVE**. Changed functions preserve existing capture destinations, validation and launch boundaries. |
+| `internal/applog` envelope | **APPROVE**. [sink.go:131](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/rootfs-fleet-followups/internal/applog/sink.go:131): process attribution overrides parsed JSON; stream and binary-instance behavior remain intact. |
+| Record-write re-pin: `Server.handleAPIInstanceList` | **APPROVE**, unchanged `key-site / lit:instances` classification. [apiinstances.go:1230](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/rootfs-fleet-followups/internal/console/apiinstances.go:1230): annotates health without changing record writes. |
+
+The five unit digests, legacy fingerprints, both envelope hashes and record-write re-pin match the source. Tenant checks remain enforced; neither change adds S3 calls per list or pass. Web generations, worker restarts and release retries reach the updated capture paths.
+
+Targeted tests and census tests could not start because the read-only sandbox prevented Go from creating its work directory. `GOCACHE` was unset. `git diff --check` passed; runtime and mutation results remain unverified.
+
+READY AFTER FIXES
\ No newline at end of file
diff --git a/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-billing-success.md b/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-billing-success.md
new file mode 100644
index 000000000..5d640a1b7
--- /dev/null
+++ b/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-billing-success.md
@@ -0,0 +1,28 @@
+# Review brief: branch billing-success, round 1 of 3
+
+Repo carlos/platform, branch `billing-success`, the commit that adds this brief (named in your prompt).
+Under review: the diff `origin/main...HEAD`: a full-page success screen on the console billing page after a purchase (?done=checkout|upgrade|packs, templates/billing_done.html), replacing the thank-you panel; charging changes (pack raise, upgrade) that the provider applied redirect with a marker; reductions, renewal changes, pending/declined/uncertain payments keep their flashes; "1 member" plural. Copy approved by Paul on 2026-10-29.
+
+## Fixed: do not re-argue
+
+- The design and the approved copy.
+
+## What to check
+
+1. The success screen renders only for an owner whose subscription is live and paid with nothing pending or ending; a member, a stale or hand-typed marker on any other account state, or an unknown marker value gets the normal billing page. The screen has no forms and acts on no billing state.
+2. Each redirect: the marker is set only after a definite applied charge (opApplied) of the matching kind, never after a pending, declined, uncertain, refused or reduction outcome; no open redirect (the target is the account's own billing page).
+3. The fallback flash and the screen never both show; a failed refresh after the change falls back to the generic flash.
+4. The billing page's existing invariants: currency/prices guard, action order, CSRF on every POST form, member/owner differences, billing lints.
+5. Anchors (#packs-title, #upgrade) exist on the billing page when their buttons show; Upgrade hidden on the top plan, Add packs when there are no packs.
+
+## Severity
+
+- **P1**: unsafe, would not compile, a test fails, or it would not work. Blocks merge.
+- **P2**: wrong or missing. Fixed without reopening this review.
+- **P3**: clarity or polish. Goes on a follow-up list; never a reason for another round.
+
+## Output
+
+Findings ranked P1, P2, P3 with file:line, failure scenario and fix. End with exactly one verdict: **READY**, **READY AFTER FIXES**, or **NOT READY**.
+
+Do not edit files. Do not spawn Anthropic-model reviewers or subagents of your own. Do not run the full test suites.
diff --git a/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-rootfs-check-volumes-R2.md b/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-rootfs-check-volumes-R2.md
new file mode 100644
index 000000000..7a3233ada
--- /dev/null
+++ b/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-rootfs-check-volumes-R2.md
@@ -0,0 +1,11 @@
+# Review brief: rootfs-check-volumes, round 2 of 3
+
+Same branch, authorities and "what to check" as docs/superpowers/reviews/CODEX-REVIEW-BRIEF-rootfs-check-volumes.md (read it). Review the diff 03e08f56..<this brief's parent> for the fixes, and the whole branch diff 1fa2a99b..HEAD for anything they broke.
+
+Earlier rounds: R1 (docs/superpowers/reviews/CODEX-FINDINGS-rootfs-check-volumes-R1.md): P1 helper container name collides with a worker named `prepare`; P2 tests do not pin chmod-before-chown or the 65534 owner. Fix commits 29e0c39a (helper `<prefix>_prepare`, outside ^[a-z][a-z0-9-]{0,15}$; fake rejects duplicate names; TestRootfsCheckWorkerNamedLikeTheHelper) and 500ec2ba (checkChmod/checkLchown package vars; TestPrepareCheckDirSetsModeThenOwner). Census re-proposed 2d5be53e (same unit and read; seal 4fb2a2ad; envelope . re-pinned).
+
+First give one line per R1 P1/P2: resolved, partly, or not. Then new findings. Then census verdicts again for every unit and envelope on the current card (docs/superpowers/notes/census-proposal-rootfs-check-volumes.md) and the main.go main re-pin.
+
+Severity, output format and rules as in round 1. End with exactly one verdict: READY, READY AFTER FIXES, or NOT READY.
+
+Do not edit files. Do not spawn Anthropic-model reviewers or subagents of your own. Do not run the full test suites.
diff --git a/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-rootfs-check-volumes-R3.md b/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-rootfs-check-volumes-R3.md
new file mode 100644
index 000000000..02ec094ad
--- /dev/null
+++ b/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-rootfs-check-volumes-R3.md
@@ -0,0 +1,13 @@
+# Review brief: rootfs-check-volumes, round 3 of 3 (LAST)
+
+Same branch, authorities and "what to check" as docs/superpowers/reviews/CODEX-REVIEW-BRIEF-rootfs-check-volumes.md. Review the fix diff from the R2 tip d57b4bf0 to <this brief's parent>, and the whole branch 1fa2a99b..HEAD for anything it broke.
+
+Earlier rounds: R1 (CODEX-FINDINGS-rootfs-check-volumes-R1.md) and R2 (CODEX-FINDINGS-rootfs-check-volumes-R2.md). R2's P1 (Docker/Podman copy-up of an empty named volume resets the prepared owner) is answered by d203093b: every data and run volume mount goes through rootfsCheck.volumeMount and ends in `:nocopy` (prepare helper, release, web, workers); TestRootfsCheckVolumesNeverCopyUp. Box witness on r10r (rootful podman): shop.tar and a variant image with an empty 0:0 755 /data/instances/check both pass; no leftovers. Docker was not available to run; the Docker side rests on Docker's documented -v nocopy option.
+
+First give one line per R1 and R2 P1/P2: resolved, partly, or not. Then new findings. Then census verdicts for every unit and envelope on the current card (docs/superpowers/notes/census-proposal-rootfs-check-volumes.md: prepareCheckDir unchanged; rootfsCheck.runArgs body change, `:nocopy` only; envelope `.`) and the main.go main re-pin.
+
+This is round 3: a NOT READY must say whether its P1s share one cause, and whether refusing the case up front or cutting the feature would remove them.
+
+Severity, output and rules as in round 1. End with exactly one verdict: READY, READY AFTER FIXES, or NOT READY.
+
+Do not edit files. Do not spawn Anthropic-model reviewers or subagents of your own. Do not run the full test suites.
diff --git a/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-rootfs-check-volumes.md b/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-rootfs-check-volumes.md
new file mode 100644
index 000000000..70116c4c8
--- /dev/null
+++ b/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-rootfs-check-volumes.md
@@ -0,0 +1,33 @@
+# Review brief: rootfs-check-volumes (carlos ship --check keeps its data volume), round 1 of 3
+
+Repo carlos/platform, branch `rootfs-check-volumes`, review the diff `1fa2a99b..ece268bc7ae69b17307bbb97981189049462bee0` (this brief's commit follows it).
+Authorities on main: docs/superpowers/specs/2026-10-24-rootfs-apps-design.md (§5.8 the local check, §5.2 the launch contract), docs/superpowers/plans/2026-10-24-rootfs-apps-1-ship.md (Task 11, the check), AGENTS.md (census, copy, stopping rules).
+
+You are an independent reviewer. Read the diff, then the code it names, and check every claim against that code.
+
+## The bug
+`carlos ship --check` made the data volume a local-driver tmpfs volume. Docker and Podman unmount it when no container holds it, so what the `release` container wrote (migrations into CARLOS_DB) was gone before `web` started; examples/rails-shop failed with a 500. Box witness after the fix (r10r, podman): release 2.9 s, web 200 after 2.8 s, worker running after 5 s, passed, no leftovers.
+
+## Fixed: do not re-argue
+- Controller's design: data volume a plain local named volume; run volume stays tmpfs; a one-shot prepare container running the CLI's own linux binary (mounted at checkProbeMount) with hidden verb `__rootfs-check-prepare`, as root with only CAP_CHOWN, chmods then chowns that one directory. Report only mechanisms that fail it.
+
+## What to check
+1. The prepare container's privileges: `--user 0:0 --read-only --network none --cap-drop ALL --cap-add CHOWN --security-opt no-new-privileges`, mounts limited to the data volume and the probe. Can the image under check influence what runs as root (entrypoint, env, working dir, the volume's content, a symlink planted at the mount point, image metadata like USER/ENTRYPOINT/HEALTHCHECK, an ONBUILD)? The verb Lstats and refuses a symlink, no recursion, mode before owner (no CAP_FOWNER): correct?
+2. Docker and Podman both (rootful and rootless podman, Docker Desktop VM): does a plain local named volume persist between containers, and does chown to 65534 inside the prepare container give the check's user write access in each? macOS/Windows hosts: the probe binary is a linux build already required by the check.
+3. Cleanup on every path (success, prepare failure, Ctrl-C between steps): every container, volume and image the check made is removed; the persisted data volume does not survive the check.
+4. The refactor of start/runRelease into launch/waitExit: release behaviour unchanged (timeouts, failure lines, report wording).
+5. User-visible strings: the diff should add none needing copy review (a failed prepare reports through existing runtimeFailed wording). Flag any new human text.
+6. Census: card docs/superpowers/notes/census-proposal-rootfs-check-volumes.md (new unit ship_check_probe.go:prepareCheckDir, +file:Lstat; envelope `.` re-pinned) and internal/provision/rootfs_check_volumes_census_test.go (main.go main re-pinned). Give a verdict for every unit and envelope on the card per AGENTS.md "Getting a change approved". Note: this code runs in the user's CLI and inside a throwaway container, never as root on a box.
+7. Tests: do the new tests and mutations (listed in the commit) actually pin 1-3?
+
+## Severity
+- **P1**: unsafe, would not compile, a test fails, or it would not work. Blocks merge.
+- **P2**: wrong or missing. Fixed without reopening this review.
+- **P3**: clarity or polish. Follow-up list only.
+
+A P1 states its failure scenario and the evidence (file:line).
+
+## Output
+Findings ranked P1, P2, P3, each with the problem, evidence (file:line, verified), failure scenario, concrete fix and the invariant it breaks. Census verdicts per unit/envelope (APPROVE or REJECT with lines read). End with exactly one verdict: READY, READY AFTER FIXES, or NOT READY.
+
+Do not edit files. Do not spawn Anthropic-model reviewers or subagents of your own. Do not run the full test suites.
diff --git a/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-rootfs-fleet-followups.md b/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-rootfs-fleet-followups.md
new file mode 100644
index 000000000..5d54cb7ae
--- /dev/null
+++ b/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-rootfs-fleet-followups.md
@@ -0,0 +1,29 @@
+# Review brief: rootfs-fleet-followups (process names in carlos logs, fleet HEALTH), round 1 of 3
+
+Repo carlos/platform, branch `rootfs-fleet-followups`, review the diff `1fa2a99b..<this brief's parent>`.
+Authorities on main: docs/superpowers/specs/2026-10-24-rootfs-apps-design.md, docs/superpowers/plans/2026-10-24-rootfs-apps-4-console-and-docs.md (row RFS-4-C99: "carlos logs shows all three processes"), AGENTS.md (census, request budget, tenant isolation, production-wired witnesses, stopping rules).
+
+You are an independent reviewer. Read the diff, then the code it names, and check every claim against that code.
+
+## The changes
+1. a19a0c42: rootfs app log lines carry Fields["process"] = web | release | <worker name> (applog.Sink.AppProcess via an optional processSink interface; the platform's value wins over the app's JSON key; stream stays `app`; binary instances unchanged).
+2. 7545ef9a: `carlos instances list` HEALTH for fleet-placed records comes from the fleet box's rollout view via join.rollout(host, acct, app) (fleetHealth after instanceHealth in handleAPIInstanceList); Unavailable/Transient views stay unknown; "failed" on AttemptDown. The console's Running tab is deliberately NOT changed (its remote facts come only from cached platform box reports; fleet reports are an uncached per-request read).
+3. b0d928c0: census proposal (card docs/superpowers/notes/census-proposal-rootfs-fleet-followups.md; record-write re-pin internal/provision/rootfs_fleet_followups_census_test.go).
+
+## What to check
+1. Tenant isolation for item 2: can a caller see HEALTH derived from another account's or app's fleet report, or from a box of a fleet its account does not own? (Task 9 / #155 tenant join rules; TestInstanceListWorkersStayInTheirTenant.)
+2. Item 2's health words: do they mirror the platform-remote branch exactly (always-on vs hibernating, crashed web, held build still serving)? Any row that now shows a misleading word?
+3. Item 1: can an app spoof another process's name, or inject a field that changes how the console or CLI filters or renders? Is every rootfs capture site covered (web generations including overlap swaps, workers including restarts, release including retries), and nothing else changed for binary instances?
+4. Request budget: do either change add S3 requests per list or per pass?
+5. Census: a verdict for every unit and envelope on the card and the re-pin, per AGENTS.md "Getting a change approved".
+6. Tests: production-wired, and do the stated mutations pin the behaviour?
+
+## Severity
+- **P1**: unsafe, would not compile, a test fails, or it would not work. Blocks merge.
+- **P2**: wrong or missing. Fixed without reopening this review.
+- **P3**: clarity or polish. Follow-up list only.
+
+## Output
+Findings ranked P1, P2, P3 with evidence (file:line), failure scenario, fix, invariant. Census verdicts. End with exactly one verdict: READY, READY AFTER FIXES, or NOT READY.
+
+Do not edit files. Do not spawn Anthropic-model reviewers or subagents of your own. Do not run the full test suites.
diff --git a/internal/activator/logsink.go b/internal/activator/logsink.go
index 431364dca..75944a932 100644
--- a/internal/activator/logsink.go
+++ b/internal/activator/logsink.go
@@ -12,6 +12,7 @@ import (
"regexp"
"strings"
+ "github.com/carlosframework/platform/internal/applog"
"github.com/carlosframework/platform/internal/cgroup"
"github.com/carlosframework/platform/internal/registry"
"github.com/carlosframework/platform/internal/release"
@@ -29,6 +30,31 @@ type EventSink interface {
Event(acct, app, host, level, msg string)
}
+// processSink is an EventSink that can name the process an app line came
+// from (applog.Sink.AppProcess). It is asked for by assertion, not added to
+// EventSink, so the package's EventSink fakes stay as they are; the
+// assertion below keeps the real sink holding it.
+type processSink interface {
+ AppProcess(acct, app, host, process, line string)
+}
+
+var _ processSink = (*applog.Sink)(nil)
+
+// appLineEmitter is the emit function for rt's app output, or nil when
+// sink is nil. A non-empty process (a rootfs instance's web, release or
+// worker name) is passed to a sink that can name it; otherwise the line
+// goes through App as before.
+func appLineEmitter(sink EventSink, rt registry.Route, process string) func(string) {
+ if sink == nil {
+ return nil
+ }
+ acct, app, host := release.RouteAccount(rt), rt.App, rt.Host
+ if ps, ok := sink.(processSink); ok && process != "" {
+ return func(line string) { ps.AppProcess(acct, app, host, process, line) }
+ }
+ return func(line string) { sink.App(acct, app, host, line) }
+}
+
// emitEvent publishes one platform event for rt's app, tolerating a nil
// sink. level is an applog.Level* value ("info"/"warn"/"error" — string
// here to keep the dependency one-way).
diff --git a/internal/activator/prepare.go b/internal/activator/prepare.go
index e921303f8..47c54aef9 100644
--- a/internal/activator/prepare.go
+++ b/internal/activator/prepare.go
@@ -179,7 +179,13 @@ func (b *ExecBackend) prepareKeyedAt(rt registry.Route, role instancectl.Role, s
var logs *logListener
if role != instancectl.RoleCmd {
var err error
- logs, err = listenLogs(b.logSocketFor(rt.Host, role, gen), b.logEmitter(rt))
+ // A rootfs row's run role is its web process; a binary row's
+ // lines name no process.
+ process := ""
+ if rt.Rootfs() && role == instancectl.RoleRun {
+ process = release.ProcessWeb
+ }
+ logs, err = listenLogs(b.logSocketFor(rt.Host, role, gen), b.logEmitter(rt, process))
if err != nil {
if ctl != nil {
ctl.Close()
@@ -222,7 +228,7 @@ func (b *ExecBackend) prepareWorker(rt registry.Route, name string) (instancePat
}
}
}
- logs, err := listenLogs(sock, b.logEmitter(rt))
+ logs, err := listenLogs(sock, b.logEmitter(rt, name))
if err != nil {
return p, nil, fmt.Errorf("log listener for %s worker %s: %w", rt.Host, name, err)
}
@@ -314,11 +320,10 @@ func (b *ExecBackend) logSocketNamed(host, name string) string {
}
// logEmitter is the same sink teeStd feeds, or nil when Logs is unset.
-func (b *ExecBackend) logEmitter(rt registry.Route) func(string) {
- if b.Logs == nil {
- return nil
- }
- return func(line string) { b.Logs.App(release.RouteAccount(rt), rt.App, rt.Host, line) }
+// process names the process the lines come from ("" for none):
+// appLineEmitter.
+func (b *ExecBackend) logEmitter(rt registry.Route, process string) func(string) {
+ return appLineEmitter(b.Logs, rt, process)
}
// writeLaunch is writeLaunchFor for the original templates.
diff --git a/internal/activator/rootfs_process_logs_test.go b/internal/activator/rootfs_process_logs_test.go
new file mode 100644
index 000000000..46695953a
--- /dev/null
+++ b/internal/activator/rootfs_process_logs_test.go
@@ -0,0 +1,112 @@
+package activator
+
+import (
+ "context"
+ "net"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/applog"
+ "github.com/carlosframework/platform/internal/instancectl"
+ "github.com/carlosframework/platform/internal/release"
+)
+
+// A rootfs instance's output reaches `carlos logs` naming the process that
+// wrote it (#366 Task 11 follow-up): web through the generation's log
+// listener, a worker through its own, the release through releaseAppLog.
+// Each line goes in at the socket or writer production hands the unit, and
+// comes out of a real applog.Sink, so the wiring at each capture site is
+// what is checked. A process key in the app's own JSON loses to the
+// platform's.
+func TestRootfsAppLinesNameTheirProcess(t *testing.T) {
+ t.Parallel()
+ b, ctl, rt, units := newWorkerBackend(t)
+ sink := applog.NewSink("box1", time.Now)
+ b.Logs = sink
+ web, g := startWorkerWeb(t, b, ctl, rt, units, "")
+ units.set(instancectl.WorkerUnitName(rt.Host, "jobs"), "active", "inv1", true)
+ wp, err := b.LaunchRootfsWorker(context.Background(), rt, "jobs", g, web)
+ if err != nil {
+ t.Fatalf("LaunchRootfsWorker: %v", err)
+ }
+ t.Cleanup(func() { stopWorker(t, wp) })
+
+ writeUnitLine(t, b.logSocketFor(rt.Host, instancectl.RoleRun, g.N), `{"msg":"web line","process":"spoof"}`)
+ writeUnitLine(t, b.workerLogSocket(rt.Host, "jobs"), "worker line")
+ a := &Service{Logs: sink}
+ if _, err := a.releaseAppLog(rt).Write([]byte("release line")); err != nil {
+ t.Fatal(err)
+ }
+
+ got := map[string]string{}
+ for _, r := range drainAppLines(t, sink, 3) {
+ got[r.Msg] = r.Fields["process"]
+ if r.Stream != applog.StreamApp {
+ t.Errorf("%q is on stream %q, want app", r.Msg, r.Stream)
+ }
+ }
+ want := map[string]string{"web line": release.ProcessWeb, "worker line": "jobs", "release line": release.ProcessRelease}
+ for msg, p := range want {
+ if got[msg] != p {
+ t.Errorf("%q has process %q, want %q (all: %v)", msg, got[msg], p, got)
+ }
+ }
+}
+
+// A binary instance's nested run role is unchanged: its lines carry no
+// process field.
+func TestBinaryAppLinesNameNoProcess(t *testing.T) {
+ t.Parallel()
+ b, _ := newRootfsBackend(t)
+ rt := rootfsRoute(b)
+ rt.Runtime = ""
+ sink := applog.NewSink("box1", time.Now)
+ b.Logs = sink
+ _, ctl, logs, _, _, err := b.prepareKeyedAt(rt, instancectl.RoleRun, rt.Socket, 0, nil)
+ if err != nil {
+ t.Fatalf("prepareKeyedAt: %v", err)
+ }
+ if ctl != nil {
+ t.Cleanup(func() { ctl.Close() })
+ }
+ t.Cleanup(func() { logs.Close() })
+ writeUnitLine(t, b.logSocketFor(rt.Host, instancectl.RoleRun, 0), "binary line")
+ for _, r := range drainAppLines(t, sink, 1) {
+ if p, ok := r.Fields["process"]; ok {
+ t.Errorf("%q carries process %q, want none", r.Msg, p)
+ }
+ }
+}
+
+// writeUnitLine is a unit's stdout: one connection to its log socket, one
+// line, closed.
+func writeUnitLine(t *testing.T, sock, line string) {
+ t.Helper()
+ c, err := net.Dial("unix", sock)
+ if err != nil {
+ t.Fatalf("dial %s: %v", sock, err)
+ }
+ defer c.Close()
+ if _, err := c.Write([]byte(line + "\n")); err != nil {
+ t.Fatal(err)
+ }
+}
+
+// drainAppLines drains sink until n app-stream records have arrived.
+func drainAppLines(t *testing.T, sink *applog.Sink, n int) []applog.Record {
+ t.Helper()
+ var out []applog.Record
+ for deadline := time.Now().Add(5 * time.Second); len(out) < n && time.Now().Before(deadline); time.Sleep(10 * time.Millisecond) {
+ for _, recs := range sink.Drain() {
+ for _, r := range recs {
+ if r.Stream == applog.StreamApp {
+ out = append(out, r)
+ }
+ }
+ }
+ }
+ if len(out) != n {
+ t.Fatalf("%d app lines arrived, want %d: %+v", len(out), n, out)
+ }
+ return out
+}
diff --git a/internal/activator/rootfsrelease.go b/internal/activator/rootfsrelease.go
index ee6376dbe..6244ca4d5 100644
--- a/internal/activator/rootfsrelease.go
+++ b/internal/activator/rootfsrelease.go
@@ -348,14 +348,10 @@ func releaseLeaseGone(held leaseWatch) bool {
}
// releaseAppLog is the writer a release's output goes through to the app
-// log, a line a Write (StartRelease's line writer feeds it whole lines);
-// nil Logs discards.
+// log, a line a Write (StartRelease's line writer feeds it whole lines),
+// each naming the release process; nil Logs discards.
func (a *Service) releaseAppLog(rt registry.Route) io.Writer {
- if a.Logs == nil {
- return lineEmitter(nil)
- }
- sink := a.Logs
- return lineEmitter(func(line string) { sink.App(release.RouteAccount(rt), rt.App, rt.Host, line) })
+ return lineEmitter(appLineEmitter(a.Logs, rt, release.ProcessRelease))
}
// runRelease runs id's release process for rt, if one is due, under held
diff --git a/internal/applog/record.go b/internal/applog/record.go
index 92ae49d69..ea153fdd6 100644
--- a/internal/applog/record.go
+++ b/internal/applog/record.go
@@ -23,6 +23,11 @@ const (
StreamRelease = "release" // ship/promote history join (stage 3)
)
+// FieldProcess is the field an app line carries naming the process that
+// wrote it, when the platform knows (Sink.AppProcess): a rootfs instance's
+// web, release or worker. `carlos logs --field process=web` filters on it.
+const FieldProcess = "process"
+
// ValidStream reports whether s names a known stream — the CLI/API's
// vocabulary check, kept here so there is exactly one list.
func ValidStream(s string) bool {
diff --git a/internal/applog/sink.go b/internal/applog/sink.go
index 19a3db172..e40b8eed7 100644
--- a/internal/applog/sink.go
+++ b/internal/applog/sink.go
@@ -129,7 +129,22 @@ func (s *Sink) Known() []AppKey {
// JSON lines at the door (ParseAppLine) so the bucket holds fields and
// honored levels rather than opaque text. Subject to both budgets.
func (s *Sink) App(acct, app, host, line string) {
+ s.AppProcess(acct, app, host, "", line)
+}
+
+// AppProcess is App for a line the platform knows the process of (a rootfs
+// instance's web, release or a named worker): a non-empty process is set
+// as Fields["process"] after parsing, over any "process" key in the app's
+// own JSON, so the name a member filters on is always the platform's. The
+// stream stays StreamApp; StreamRelease is the ship/promote history.
+func (s *Sink) AppProcess(acct, app, host, process, line string) {
msg, level, fields := ParseAppLine(line)
+ if process != "" {
+ if fields == nil {
+ fields = make(map[string]string, 1)
+ }
+ fields[FieldProcess] = process
+ }
s.mu.Lock()
defer s.mu.Unlock()
b := s.buf(AppKey{acct, app})
diff --git a/internal/applog/sink_test.go b/internal/applog/sink_test.go
index fcdaa2ac0..17068a9fd 100644
--- a/internal/applog/sink_test.go
+++ b/internal/applog/sink_test.go
@@ -162,3 +162,29 @@ func TestIsDropNotice(t *testing.T) {
}
}
}
+
+// AppProcess is App with the platform naming the process that wrote the
+// line (a rootfs instance's web, release or a worker): the name rides in
+// Fields["process"], on a plain line and on a structured one alike, and
+// the platform's value wins over a "process" key in the app's own JSON.
+// The stream stays app: "release" is the ship/promote history's stream.
+func TestSinkAppProcessNamesTheProcess(t *testing.T) {
+ now, _ := testClock(time.Date(2026, 10, 30, 12, 0, 0, 0, time.UTC))
+ sk := NewSink("box1", now)
+ sk.AppProcess("bab", "shop", "shop.bab.oncarlos.com", "web", "listening")
+ sk.AppProcess("bab", "shop", "shop.bab.oncarlos.com", "jobs", `{"msg":"tick","process":"web","n":3}`)
+ sk.AppProcess("bab", "shop", "shop.bab.oncarlos.com", "release", "migrated")
+ sk.App("bab", "shop", "shop.bab.oncarlos.com", `{"msg":"own","process":"mine"}`)
+ recs := sk.Drain()[AppKey{"bab", "shop"}]
+ if len(recs) != 4 {
+ t.Fatalf("records: %d, want 4", len(recs))
+ }
+ for i, want := range []struct{ msg, process, n string }{
+ {"listening", "web", ""}, {"tick", "jobs", "3"}, {"migrated", "release", ""}, {"own", "mine", ""},
+ } {
+ r := recs[i]
+ if r.Stream != StreamApp || r.Msg != want.msg || r.Fields["process"] != want.process || r.Fields["n"] != want.n {
+ t.Errorf("record %d = %+v, want app stream, msg %q, process %q, n %q", i, r, want.msg, want.process, want.n)
+ }
+ }
+}
diff --git a/internal/console/apiinstances.go b/internal/console/apiinstances.go
index e4f71c70e..4a46e84de 100644
--- a/internal/console/apiinstances.go
+++ b/internal/console/apiinstances.go
@@ -476,6 +476,44 @@ func (s *Server) instanceHealth(ctx context.Context, recs []provision.Record) ma
return out
}
+// fleetHealth fills in, from join, the health of each record placed on a
+// customer fleet that instanceHealth left unknown: the platform's boxes do
+// not report fleet-placed hosts, but the fleet's own boxes' rollout reports
+// do, and join (loadRolloutJoin) reads them for the caller's own fleets
+// only. join.rollout keeps its tenant rule: a report is used only when it
+// names this account and app. A view whose box could not arm its scheduler
+// (Unavailable, which also covers a refused view with no tenant to check)
+// or whose host is starting or stopping (Transient) says nothing about the
+// host's state, and the word stays unknown, as it does for a view whose
+// box generated its snapshot no later than the record was created: that
+// report may be about an earlier lifetime of the same host, account and
+// app (appFacts.host's rule for a platform-remote record). Otherwise the
+// word is the platform-remote one (instanceHealth): awake is Running, a
+// host held down after a failed hold-mode build is Failed.
+func fleetHealth(health map[string]string, recs []provision.Record, join boxJoin, acct, app string) {
+ for _, rec := range recs {
+ if health[rec.Host] != healthUnknown {
+ continue
+ }
+ if _, fleetPlaced := registry.FleetPlacement(rec.Region); !fleetPlaced {
+ continue
+ }
+ v := join.rollout(rec.Host, acct, app)
+ if v == nil || v.Unavailable != "" || v.Transient || !v.at.After(rec.CreatedAt) {
+ continue
+ }
+ kind := rec.Kind
+ if kind == "" {
+ kind = "instance"
+ }
+ st := "ready"
+ if v.Attempt == status.AttemptDown {
+ st = "failed"
+ }
+ health[rec.Host] = healthWord(kind, st, rec.HibernateOrDefault(), v.Awake, true)
+ }
+}
+
// healthByHost is the metrics half of a health answer, shared by
// instanceHealth (records joined to routes) and handleAPIRoutes (routes
// directly, issue #64) so the two — and the Running tab, which uses the
@@ -716,6 +754,11 @@ type rolloutView struct {
// refused marks a view built from an Unavailable box, which has no
// account or app to check (hosts are unique; the caller filtered by app).
refused bool
+ // at is when the reporting box generated its snapshot (status.Box's
+ // GeneratedAt). Not shown: fleetHealth uses a view only when it is
+ // later than the record's creation, so a report about an earlier
+ // lifetime of the same host never describes this one.
+ at time.Time
}
// workerView is one worker of a rootfs instance as a member sees it
@@ -1044,12 +1087,12 @@ func (j *boxJoin) foldRollout(b status.Box, override bool) {
if _, held := ro.Hosts[host]; held {
continue
}
- put(host, rolloutView{Box: b.Label, Installed: v, Unavailable: ro.Unavailable, refused: true})
+ put(host, rolloutView{Box: b.Label, Installed: v, Unavailable: ro.Unavailable, refused: true, at: b.GeneratedAt})
}
for host, hr := range ro.Hosts {
put(host, rolloutView{Box: b.Label, Installed: hr.Installed, Good: hr.Good, Attempt: hr.Attempt, AttemptBuild: hr.AttemptBuild,
HeldBy: hr.HeldBy, Reason: hr.Reason, Unavailable: ro.Unavailable, Workers: workerViews(hr.Workers),
- account: hr.Account, app: hr.App, heldEpoch: hr.HeldEpoch, heldBook: hr.HeldBook, retryV: hr.RetryV})
+ account: hr.Account, app: hr.App, heldEpoch: hr.HeldEpoch, heldBook: hr.HeldBook, retryV: hr.RetryV, at: b.GeneratedAt})
}
return
}
@@ -1072,6 +1115,7 @@ func (j *boxJoin) foldRollout(b status.Box, override bool) {
ConfigPending: hr.ConfigPending, Transient: hr.Transient, SchedulerIdle: a.Queued == 0 && a.Running == 0 && a.Settling == 0,
Workers: workerViews(hr.Workers),
account: hr.Account, app: hr.App, heldEpoch: hr.HeldEpoch, heldBook: hr.HeldBook, retryV: hr.RetryV,
+ at: b.GeneratedAt,
})
}
}
@@ -1193,6 +1237,7 @@ func (s *Server) handleAPIInstanceList(w http.ResponseWriter, r *http.Request) {
}
}
health := s.instanceHealth(ctx, recs)
+ fleetHealth(health, recs, join, acct.Sqid, app)
counts := map[string]int{}
matched := make([]instanceListRecord, 0, len(recs))
home, names := s.regionHome(), s.regionNames()
diff --git a/internal/console/billingchange.go b/internal/console/billingchange.go
index 9adf009a4..0ec40836f 100644
--- a/internal/console/billingchange.go
+++ b/internal/console/billingchange.go
@@ -67,9 +67,12 @@ type changeQuote struct {
}
// changeReply is a change's answer: a flash (kind and text), or a quote for
-// the confirm page.
+// the confirm page. Done is the success marker (donePacks, doneUpgrade) the
+// billing page is reached with after a raise or an upgrade the provider
+// applied, "" for none; the flash is then the screen's fallback.
type changeReply struct {
Kind, Text string
+ Done string
Quote *changeQuote
}
@@ -178,6 +181,9 @@ func (s *Server) handleBillingChange(w http.ResponseWriter, r *http.Request) {
return
}
s.setFlash(w, reply.Kind, reply.Text)
+ if reply.Done != "" {
+ back += "?done=" + reply.Done
+ }
http.Redirect(w, r, back, http.StatusSeeOther)
}
@@ -385,7 +391,7 @@ func (s *Server) packChangeLocked(h billingHold, ctx context.Context, acct *Acco
return changeReply{}, err
}
if chargeTo == 0 {
- return s.settleChangeLocked(h, ctx, acct, out, now), nil
+ return s.settleSuccessLocked(h, ctx, acct, out, now, packsDone()), nil
}
// The charge is computed only from a definite restore applied in the
// same period, on the item its answer names.
@@ -412,7 +418,7 @@ func (s *Server) packChangeLocked(h billingHold, ctx context.Context, acct *Acco
if err != nil {
return changeReply{}, err
}
- return s.settleChangeLocked(h, ctx, acct, out, now), nil
+ return s.settleSuccessLocked(h, ctx, acct, out, now, packsDone()), nil
}
// upgradeLocked is a plan upgrade (Call 4) on the fresh allowance read: one
@@ -471,7 +477,8 @@ func (s *Server) upgradeLocked(h billingHold, ctx context.Context, acct *Account
if err != nil {
return changeReply{}, err
}
- return s.settleChangeLocked(h, ctx, acct, out, now), nil
+ return s.settleSuccessLocked(h, ctx, acct, out, now, changeReply{Kind: "ok", Done: doneUpgrade,
+ Text: fmt.Sprintf(billingCopy["done.upgrade.flash"], planLabel(ask.Plan))}), nil
}
// configuredPrice is a yearly price from the configured book, known only when
@@ -524,11 +531,42 @@ func (s *Server) sendChangeLocked(h billingHold, ctx context.Context, acct *Acco
// the page shows what the provider holds, and answers the outcome's flash. A
// failed refresh only defers that to the next read: the outcome is recorded.
func (s *Server) settleChangeLocked(h billingHold, ctx context.Context, acct *Account, out opOutcome, now time.Time) changeReply {
- if _, _, err := s.refreshLocked(h, ctx, acct, now); err != nil {
+ reply, _ := s.settleRefreshLocked(h, ctx, acct, out, now)
+ return reply
+}
+
+// settleSuccessLocked is settleChangeLocked for a raise or an upgrade:
+// applied, with the refresh read, it answers done, the success screen's
+// marker and fallback flash. Anything else (pending, declined, uncertain)
+// keeps its flash. So does an applied change whose refresh failed or found
+// no subscription: the page would show the plan as it was before, and the
+// screen would name it.
+func (s *Server) settleSuccessLocked(h billingHold, ctx context.Context, acct *Account, out opOutcome, now time.Time, done changeReply) changeReply {
+ reply, refreshed := s.settleRefreshLocked(h, ctx, acct, out, now)
+ if out.State == opApplied && refreshed {
+ return done
+ }
+ return reply
+}
+
+// settleRefreshLocked is the refresh and outcome flash both settle
+// helpers share, and whether the refresh read the subscription: no error
+// and a subscription read. A provider with no subscription is no error
+// (refreshLocked records it as a problem and returns no read), and it
+// confirms nothing.
+func (s *Server) settleRefreshLocked(h billingHold, ctx context.Context, acct *Account, out opOutcome, now time.Time) (changeReply, bool) {
+ _, sub, err := s.refreshLocked(h, ctx, acct, now)
+ if err != nil {
log.Printf("console: billing change %s: refresh after the change: %v", acct.Sqid, err)
}
kind, key := outcomeCopy(out)
- return changeFlash(kind, key)
+ return changeFlash(kind, key), err == nil && sub != nil
+}
+
+// packsDone is the answer to a pack raise the provider applied: the packs
+// success screen, with its flash as the fallback.
+func packsDone() changeReply {
+ return changeReply{Kind: "ok", Text: billingCopy["done.packs.flash"], Done: donePacks}
}
// ---- renewal --------------------------------------------------------------
diff --git a/internal/console/billingchange_test.go b/internal/console/billingchange_test.go
index 6639fdb8d..7c45270a8 100644
--- a/internal/console/billingchange_test.go
+++ b/internal/console/billingchange_test.go
@@ -64,6 +64,15 @@ func (o *opsFixture) wantFlash(t *testing.T, r billingReply, kind, text string)
}
}
+// wantDone is a redirect to the billing page's success screen for marker
+// (packs or upgrade), with the plain flash text as its fallback.
+func (o *opsFixture) wantDone(t *testing.T, r billingReply, marker, text string) {
+ t.Helper()
+ if r.Status != http.StatusSeeOther || r.Loc != o.billingBase()+"?done="+marker || r.Flash != "ok" || r.FlashMsg != text {
+ t.Fatalf("reply = %d %q flash %s:%q, want ?done=%s and ok:%q", r.Status, r.Loc, r.Flash, r.FlashMsg, marker, text)
+ }
+}
+
// wantQuote is the confirm page for a charge, showing line.
func wantQuote(t *testing.T, r billingReply, line string) {
t.Helper()
@@ -204,7 +213,7 @@ func TestPackRaiseCharges(t *testing.T) {
o.stepUp(t)
o.reset()
r = o.change(t, "pack", "apps", "quantity", "3", "confirmed", "1")
- o.wantFlash(t, r, "ok", billingCopy["change.done"])
+ o.wantDone(t, r, "packs", billingCopy["done.packs.flash"])
wantCounts(t, o.counts(), map[string]int{"Subscription": 2, "Send": 1})
op := o.lastOp(t)
if op.Kind != opPack || op.State != opApplied || op.StartQuantity == nil || *op.StartQuantity != 1 ||
@@ -245,7 +254,7 @@ func TestPackReduceAndBuyBack(t *testing.T) {
// step-up, one write.
o.reset()
r = o.change(t, "pack", "apps", "quantity", "3")
- o.wantFlash(t, r, "ok", billingCopy["change.done"])
+ o.wantDone(t, r, "packs", billingCopy["done.packs.flash"])
wantCounts(t, o.counts(), map[string]int{"Subscription": 2, "Send": 1})
op = o.lastOp(t)
if body := changeBodyOf(t, op.Prepared); op.Kind != opRestore || op.State != opApplied || body.Proration != billing.ProrateNone ||
@@ -287,7 +296,7 @@ func TestDeletedPackRestoreThenCharge(t *testing.T) {
// answer names up to 4. S + (1) + (1) + S.
o.stepUp(t)
o.reset()
- o.wantFlash(t, o.change(t, "pack", "apps", "quantity", "4", "confirmed", "1"), "ok", billingCopy["change.done"])
+ o.wantDone(t, o.change(t, "pack", "apps", "quantity", "4", "confirmed", "1"), "packs", billingCopy["done.packs.flash"])
wantCounts(t, o.counts(), map[string]int{"Subscription": 2, "Send": 2})
all := o.ops(t)
if len(all) != 3 {
@@ -396,7 +405,7 @@ func TestRestoreIgnoresConsoleClock(t *testing.T) {
t.Fatal(err)
}
o.reset()
- o.wantFlash(t, o.change(t, "pack", "apps", "quantity", "2"), "ok", billingCopy["change.done"])
+ o.wantDone(t, o.change(t, "pack", "apps", "quantity", "2"), "packs", billingCopy["done.packs.flash"])
if op := o.lastOp(t); op.Kind != opRestore || op.State != opApplied {
t.Fatalf("restore = %+v", op)
}
@@ -485,7 +494,7 @@ func TestRetryAfterDeclineIsRefusedUntilSettled(t *testing.T) {
t.Fatal(err)
}
o.reset()
- o.wantFlash(t, o.change(t, "pack", "apps", "quantity", "2", "confirmed", "1"), "ok", billingCopy["change.done"])
+ o.wantDone(t, o.change(t, "pack", "apps", "quantity", "2", "confirmed", "1"), "packs", billingCopy["done.packs.flash"])
wantCounts(t, o.counts(), map[string]int{"Subscription": 3, "Send": 1})
if got := o.op(t, first.ID); got.State != opAbandoned {
t.Fatalf("first op = %+v, want abandoned", got)
@@ -501,14 +510,14 @@ func TestRetryAfterDeclineIsRefusedUntilSettled(t *testing.T) {
t.Fatalf("declined op = %+v", op)
}
o.reset()
- o.wantFlash(t, o.change(t, "pack", "apps", "quantity", "3", "confirmed", "1"), "ok", billingCopy["change.done"])
+ o.wantDone(t, o.change(t, "pack", "apps", "quantity", "3", "confirmed", "1"), "packs", billingCopy["done.packs.flash"])
wantCounts(t, o.counts(), map[string]int{"Subscription": 2, "Send": 1})
}
func TestChangeTwiceChargesOnce(t *testing.T) {
o := newChangeFixture(t, map[string]int64{"apps": 1})
o.stepUp(t)
- o.wantFlash(t, o.change(t, "pack", "apps", "quantity", "3", "confirmed", "1"), "ok", billingCopy["change.done"])
+ o.wantDone(t, o.change(t, "pack", "apps", "quantity", "3", "confirmed", "1"), "packs", billingCopy["done.packs.flash"])
// The double submit: the fresh read shows 3, so there is no step.
o.reset()
o.wantFlash(t, o.change(t, "pack", "apps", "quantity", "3", "confirmed", "1"), "err", billingCopy["change.none"])
@@ -535,7 +544,7 @@ func TestChangeComputesFromTheFreshRead(t *testing.T) {
o.stepUp(t)
// The provider moved the quantity since the console last read it.
o.setQuantity("sub_1", appsPrice(), 3)
- o.wantFlash(t, o.change(t, "pack", "apps", "quantity", "4", "confirmed", "1"), "ok", billingCopy["change.done"])
+ o.wantDone(t, o.change(t, "pack", "apps", "quantity", "4", "confirmed", "1"), "packs", billingCopy["done.packs.flash"])
op := o.lastOp(t)
if body := changeBodyOf(t, op.Prepared); op.Kind != opPack || *op.StartQuantity != 3 || body.Proration != billing.ProrateNow || body.Items[0].Quantity != 4 {
t.Fatalf("charge = %+v body %+v", op, body)
@@ -564,7 +573,7 @@ func TestChangeAfterDelayedRenewal(t *testing.T) {
wantQuote(t, o.change(t, "pack", "apps", "quantity", "3"), quoteLine("usd", prorateEstimate(1200, 2, o.providerClock(), periodEnd.AddDate(1, 0, 0))))
wantCounts(t, o.counts(), map[string]int{"Subscription": 1})
o.reset()
- o.wantFlash(t, o.change(t, "pack", "apps", "quantity", "3", "confirmed", "1"), "ok", billingCopy["change.done"])
+ o.wantDone(t, o.change(t, "pack", "apps", "quantity", "3", "confirmed", "1"), "packs", billingCopy["done.packs.flash"])
wantCounts(t, o.counts(), map[string]int{"Subscription": 2, "Send": 1})
op := o.lastOp(t)
if op.Kind != opPack || *op.StartQuantity != 1 || !op.PeriodEnd.Equal(periodEnd.AddDate(1, 0, 0)) || changeBodyOf(t, op.Prepared).Proration != billing.ProrateNow {
@@ -593,7 +602,7 @@ func TestChangeAfterReplacementSubscription(t *testing.T) {
o.stepUp(t)
o.reset()
// The old subscription's paid 3 does not carry: a charge on sub_2.
- o.wantFlash(t, o.change(t, "pack", "apps", "quantity", "3", "confirmed", "1"), "ok", billingCopy["change.done"])
+ o.wantDone(t, o.change(t, "pack", "apps", "quantity", "3", "confirmed", "1"), "packs", billingCopy["done.packs.flash"])
wantCounts(t, o.counts(), map[string]int{"Subscription": 2, "Send": 1})
op := o.lastOp(t)
if op.Subscription != "sub_2" || op.Kind != opPack || *op.StartQuantity != 1 || changeBodyOf(t, op.Prepared).Subscription != "sub_2" {
@@ -609,7 +618,7 @@ func TestChangeUnresolvedFinishedOnNextRequest(t *testing.T) {
o.unresolved(t, op)
o.setQuantity("sub_1", appsPrice(), 2)
o.reset()
- o.wantFlash(t, o.change(t, "pack", "apps", "quantity", "3", "confirmed", "1"), "ok", billingCopy["change.done"])
+ o.wantDone(t, o.change(t, "pack", "apps", "quantity", "3", "confirmed", "1"), "packs", billingCopy["done.packs.flash"])
// F (one read, no resend), then S + (1) + S.
wantCounts(t, o.counts(), map[string]int{"Subscription": 3, "Send": 1})
if got := o.op(t, "op_prior"); got.State != opApplied {
@@ -625,7 +634,7 @@ func TestChangeUnresolvedFinishedOnNextRequest(t *testing.T) {
op := o.packOp(t, "op_prior", "sub_1", "apps", 2, billing.ProrateNow, opPack)
o.unresolved(t, op)
o.reset()
- o.wantFlash(t, o.change(t, "pack", "apps", "quantity", "3", "confirmed", "1"), "ok", billingCopy["change.done"])
+ o.wantDone(t, o.change(t, "pack", "apps", "quantity", "3", "confirmed", "1"), "packs", billingCopy["done.packs.flash"])
wantCounts(t, o.counts(), map[string]int{"Subscription": 3, "Send": 2})
sent := o.sent()
if sent[0].Key != op.Prepared.Key || string(sent[0].Body) != string(op.Prepared.Body) {
@@ -659,7 +668,7 @@ func TestPlanUpgrade(t *testing.T) {
o.stepUp(t)
o.reset()
- o.wantFlash(t, o.change(t, "plan", "community", "confirmed", "1"), "ok", billingCopy["change.done"])
+ o.wantDone(t, o.change(t, "plan", "community", "confirmed", "1"), "upgrade", fmt.Sprintf(billingCopy["done.upgrade.flash"], "Community"))
wantCounts(t, o.counts(), map[string]int{"Subscription": 2, "Send": 1})
op := o.lastOp(t)
body := changeBodyOf(t, op.Prepared)
@@ -696,7 +705,7 @@ func TestUpgradeRefusedWhenPackNotOffered(t *testing.T) {
t.Fatal("a refused upgrade wrote")
}
// A plan that offers it is fine.
- o.wantFlash(t, o.change(t, "plan", "community", "confirmed", "1"), "ok", billingCopy["change.done"])
+ o.wantDone(t, o.change(t, "plan", "community", "confirmed", "1"), "upgrade", fmt.Sprintf(billingCopy["done.upgrade.flash"], "Community"))
// A pack reduced to 0 is still paid for until renewal, so it is still
// held: the upgrade is refused with nothing sent.
@@ -767,7 +776,7 @@ func TestChangeUsesTheSubscriptionsBook(t *testing.T) {
// The earlier book's amounts are not known here: no estimate.
wantQuote(t, o.change(t, "pack", "apps", "quantity", "2"), billingCopy["change.no_estimate"])
- o.wantFlash(t, o.change(t, "pack", "apps", "quantity", "2", "confirmed", "1"), "ok", billingCopy["change.done"])
+ o.wantDone(t, o.change(t, "pack", "apps", "quantity", "2", "confirmed", "1"), "packs", billingCopy["done.packs.flash"])
if op := o.lastOp(t); op.Target.Quantities[testPriceID("example-v0/pack/apps/usd")] != 2 {
t.Fatalf("pack change = %+v", op)
}
@@ -776,7 +785,7 @@ func TestChangeUsesTheSubscriptionsBook(t *testing.T) {
o.wantFlash(t, o.change(t, "pack", "email", "quantity", "1", "confirmed", "1"), "err", billingCopy["change.book"])
wantCounts(t, o.counts(), map[string]int{"Subscription": 1})
// An upgrade is priced from the subscription's book.
- o.wantFlash(t, o.change(t, "plan", "community", "confirmed", "1"), "ok", billingCopy["change.done"])
+ o.wantDone(t, o.change(t, "plan", "community", "confirmed", "1"), "upgrade", fmt.Sprintf(billingCopy["done.upgrade.flash"], "Community"))
if body := changeBodyOf(t, o.lastOp(t).Prepared); body.Items[0].PriceID != testPriceID("example-v0/community/usd") {
t.Fatalf("upgrade = %+v", body)
}
@@ -1013,3 +1022,84 @@ func TestChangeAndRenewalReturnUnderTimeout(t *testing.T) {
})
}
}
+
+// ---- the success screen after a change ---------------------------------------
+
+// TestChangeSuccessScreen: a pack raise or an upgrade the provider applied
+// redirects to the success screen for it (?done=packs, ?done=upgrade), which
+// replaces the billing page; a reduction and a renewal change keep their
+// flashes on the billing page, with no marker.
+func TestChangeSuccessScreen(t *testing.T) {
+ o := newChangeFixture(t, map[string]int64{"apps": 1})
+ o.stepUp(t)
+ follow := func(r billingReply) string {
+ t.Helper()
+ page := o.request(t, http.MethodGet, r.Loc, nil)
+ if page.Status != http.StatusOK {
+ t.Fatalf("GET %s = %d", r.Loc, page.Status)
+ }
+ return page.Body
+ }
+
+ // A charged pack raise.
+ r := o.change(t, "pack", "apps", "quantity", "3", "confirmed", "1")
+ o.wantDone(t, r, "packs", billingCopy["done.packs.flash"])
+ if screen := successScreen(follow(r)); !strings.Contains(screen, esc(billingCopy["done.packs.title"])) {
+ t.Fatalf("after a pack raise: no packs screen:\n%s", screen)
+ }
+
+ // A reduction: change.done on the billing page.
+ r = o.change(t, "pack", "apps", "quantity", "1")
+ o.wantFlash(t, r, "ok", billingCopy["change.done"])
+ if body := follow(r); successScreen(body) != "" {
+ t.Fatal("a reduction showed the success screen")
+ }
+
+ // Buying back what is already paid for is a raise too: the packs screen.
+ o.wantDone(t, o.change(t, "pack", "apps", "quantity", "2"), "packs", billingCopy["done.packs.flash"])
+
+ // An upgrade: the upgrade screen, naming the new plan.
+ r = o.change(t, "plan", "community", "confirmed", "1")
+ o.wantDone(t, r, "upgrade", fmt.Sprintf(billingCopy["done.upgrade.flash"], "Community"))
+ if screen := successScreen(follow(r)); !strings.Contains(screen, esc(fmt.Sprintf(billingCopy["done.upgrade.title"], "Community"))) {
+ t.Fatalf("after an upgrade: no upgrade screen:\n%s", screen)
+ }
+
+ // Renewal: its own flashes, no marker.
+ o.wantFlash(t, o.renewal(t, "stop"), "ok", fmt.Sprintf(billingCopy["renewal.stopped"], billingDate(periodEnd)))
+ o.wantFlash(t, o.renewal(t, "resume"), "ok", billingCopy["renewal.resumed"])
+}
+
+// TestChangeSuccessNeedsTheSubscription: an upgrade or a pack raise the
+// provider applied, whose refresh then finds no subscription (a missing
+// subscription is recorded as a problem, not an error), gets the generic
+// flash and no success marker: nothing confirmed the purchase's limits.
+func TestChangeSuccessNeedsTheSubscription(t *testing.T) {
+ for _, c := range []struct {
+ name string
+ kv []string
+ }{
+ {"packs", []string{"pack", "apps", "quantity", "3", "confirmed", "1"}},
+ {"upgrade", []string{"plan", "community", "confirmed", "1"}},
+ } {
+ t.Run(c.name, func(t *testing.T) {
+ o := newChangeFixture(t, map[string]int64{"apps": 1})
+ o.stepUp(t)
+ reads := 0
+ o.fake.BeforeSubscription = func(string) error {
+ // The change's own read succeeds; the refresh after the
+ // send finds nothing.
+ if reads++; reads > 1 {
+ return billing.ErrNotFound
+ }
+ return nil
+ }
+ r := o.change(t, c.kv...)
+ o.fake.BeforeSubscription = nil
+ if op := o.lastOp(t); op.State != opApplied {
+ t.Fatalf("op = %+v, want applied", op)
+ }
+ o.wantFlash(t, r, "ok", billingCopy["change.done"])
+ })
+ }
+}
diff --git a/internal/console/billingcheckout.go b/internal/console/billingcheckout.go
index 6b6fa603a..c6c3ab6e1 100644
--- a/internal/console/billingcheckout.go
+++ b/internal/console/billingcheckout.go
@@ -1078,9 +1078,9 @@ func (s *Server) continueLocked(h billingHold, ctx context.Context, acct *Accoun
// handleBillingDone is GET /a/{sqid}/billing/done?session=: the owner back
// from the payment page. The intent the session names is marked returned and
// observed (a completed session syncs its subscription), then the billing
-// page. A completed, paid return carries the thank-you marker (?welcome=1,
+// page. A completed, paid return carries the success marker (?done=checkout,
// which the page checks against the account's state again) and a flash
-// naming the plan, which the panel replaces.
+// naming the plan, which the success screen replaces.
func (s *Server) handleBillingDone(w http.ResponseWriter, r *http.Request) {
if s.billing == nil {
http.NotFound(w, r)
@@ -1107,7 +1107,7 @@ func (s *Server) handleBillingDone(w http.ResponseWriter, r *http.Request) {
s.setFlash(w, kind, text)
}
if kind == "ok" {
- back += "?welcome=1"
+ back += "?done=" + doneCheckout
}
http.Redirect(w, r, back, http.StatusSeeOther)
}
diff --git a/internal/console/billingcheckout_test.go b/internal/console/billingcheckout_test.go
index f2ec185e6..b84e6fee8 100644
--- a/internal/console/billingcheckout_test.go
+++ b/internal/console/billingcheckout_test.go
@@ -895,15 +895,15 @@ func TestCheckoutDoneSyncs(t *testing.T) {
}
wantCounts(t, o.counts(), map[string]int{})
r := o.request(t, http.MethodGet, o.billingBase()+"/done?session="+ci.Session, nil)
- // A completed, paid return: the billing page with the thank-you marker,
+ // A completed, paid return: the billing page with the success marker,
// and the plain flash as its fallback.
- if r.Status != http.StatusSeeOther || r.Loc != o.billingBase()+"?welcome=1" || r.Flash != "ok" || r.FlashMsg != fmt.Sprintf(billingCopy["checkout.done"], "Personal") {
+ if r.Status != http.StatusSeeOther || r.Loc != o.billingBase()+"?done=checkout" || r.Flash != "ok" || r.FlashMsg != fmt.Sprintf(billingCopy["checkout.done"], "Personal") {
t.Fatalf("done = %+v", r)
}
- // Following it shows the panel in the flash's place.
+ // Following it shows the success screen in the flash's place.
page := o.request(t, http.MethodGet, r.Loc, nil)
- if page.Status != http.StatusOK || welcomePanel(page.Body) == "" {
- t.Fatalf("the page after the return has no thank-you panel:\n%s", page.Body)
+ if page.Status != http.StatusOK || successScreen(page.Body) == "" {
+ t.Fatalf("the page after the return has no success screen:\n%s", page.Body)
}
// 1 session read + S.
wantCounts(t, o.counts(), map[string]int{"Checkout": 1, "Subscription": 1})
@@ -1309,7 +1309,7 @@ func TestCheckoutDoneResyncsAfterFailedSync(t *testing.T) {
}
o.reset()
r := o.request(t, http.MethodGet, o.billingBase()+"/done?session="+ci.Session, nil)
- if r.Loc != o.billingBase()+"?welcome=1" || r.Flash != "ok" || r.FlashMsg != fmt.Sprintf(billingCopy["checkout.done"], "Personal") {
+ if r.Loc != o.billingBase()+"?done=checkout" || r.Flash != "ok" || r.FlashMsg != fmt.Sprintf(billingCopy["checkout.done"], "Personal") {
t.Fatalf("done = %+v", r)
}
wantCounts(t, o.counts(), map[string]int{"Checkout": 1, "Subscription": 1})
@@ -1341,7 +1341,7 @@ func TestCheckoutDonePendingThenPaid(t *testing.T) {
o.fake.Unlock()
o.reset()
r := o.request(t, http.MethodGet, o.billingBase()+"/done?session="+ci.Session, nil)
- if r.Loc != o.billingBase()+"?welcome=1" || r.Flash != "ok" || r.FlashMsg != fmt.Sprintf(billingCopy["checkout.done"], "Personal") {
+ if r.Loc != o.billingBase()+"?done=checkout" || r.Flash != "ok" || r.FlashMsg != fmt.Sprintf(billingCopy["checkout.done"], "Personal") {
t.Fatalf("done = %+v", r)
}
wantCounts(t, o.counts(), map[string]int{"Checkout": 1, "Subscription": 1})
diff --git a/internal/console/billingpage.go b/internal/console/billingpage.go
index 0dfba71c2..b035c7df6 100644
--- a/internal/console/billingpage.go
+++ b/internal/console/billingpage.go
@@ -201,10 +201,11 @@ type billingView struct {
Plan string
Facts []string
Includes []string
+ limits *plans.Limits // the limits Includes lists, nil for none
Offers billingOffers
- // Welcome is the thank-you panel after a completed purchase, nil for
- // none (billingWelcomeFor).
- Welcome *billingWelcome
+ // Success is the screen that replaces the page after a completed
+ // purchase, nil for none (billingSuccessFor).
+ Success *billingSuccess
Buy *billingBuyView
Change *billingChangeView
StartOver []billingField // the open intent's own request, for Start over
@@ -218,13 +219,21 @@ type billingOffers struct {
type billingField struct{ Name, Value string }
-// billingWelcome is the thank-you panel: the line naming the account and
-// its plan, the room the plan gives ("" when the page names none), and
-// whether the page has packs to add and a plan to upgrade to, so each link
-// lands on a section that is there.
-type billingWelcome struct {
- Lede, Room string
- Packs, Upgrade bool
+// The success markers a completed purchase redirects to the billing page
+// with (?done=): a Checkout, an upgrade, a pack raise.
+const (
+ doneCheckout = "checkout"
+ doneUpgrade = "upgrade"
+ donePacks = "packs"
+)
+
+// billingSuccess is the success screen: the heading and line for the
+// purchase the marker names, the room the plan gives ("" when the screen
+// names none), and its links. PacksURL and UpgradeURL go to the billing
+// page's own sections, "" when the page has none to land on.
+type billingSuccess struct {
+ Title, Lede, Room string
+ PacksURL, UpgradeURL, AppsURL string
}
// billingBuyView is the first purchase: the paid plans, a quantity per
@@ -304,7 +313,9 @@ func (s *Server) billingPageInputFor(acct *Account, role string, now time.Time)
// handleBilling is GET /a/{sqid}/billing. Billing off answers the unrouted
// 404; the account gate answers a non-member with the same 404. Members
-// see the facts and notices, owners also the forms.
+// see the facts and notices, owners also the forms. An owner back from a
+// completed purchase (?done=) gets the success screen in its place
+// (billingSuccessFor).
func (s *Server) handleBilling(w http.ResponseWriter, r *http.Request) {
if s.billing == nil {
http.NotFound(w, r)
@@ -332,13 +343,12 @@ func (s *Server) handleBilling(w http.ResponseWriter, r *http.Request) {
}
st := decideBillingPage(in)
view := s.billingViewFor(r, in, st, members)
+ if view.Success = billingSuccessFor(r.URL.Query().Get("done"), acct, in, st, view); view.Success != nil {
+ s.renderBillingSuccess(w, r, view)
+ return
+ }
view.Eyebrow = fmt.Sprintf(billingCopy["page.eyebrow"], acct.Name)
p := s.accountPage(w, r, addr, raw, acct, role)
- if view.Welcome != nil {
- // The panel says what the return's plain flash said, and more.
- view.Welcome.Lede = fmt.Sprintf(billingCopy["welcome.lede"], acct.Name, view.Plan)
- p.Flash = ""
- }
p.Title = billingCopy["page.title"]
p.ActiveNav = "billing"
p.Billing = view
@@ -392,7 +402,6 @@ func (s *Server) billingViewFor(r *http.Request, in billingPageInput, st billing
plan, packs, sponsored, seats = in.Row.Plan, in.Row.Packs, in.Row.Sponsored, in.Row.Seats
}
v.Plan = planLabel(plan)
- var limits *plans.Limits
if p, ok := cat.Plans[plan]; ok {
held := map[string]int{}
for _, name := range heldPacks(packs) {
@@ -403,7 +412,7 @@ func (s *Server) billingViewFor(r *http.Request, in billingPageInput, st billing
limitedAt, _ := teamMembers(cat, plan, seats, func() (int, error) { return members, nil })
if l, err := cat.Effective(plan, held, sponsored, limitedAt); err == nil {
v.Includes = planIncludes(l, p.MaxMembers)
- limits = &l
+ v.limits = &l
}
}
// A line per pack held: "4 Apps packs".
@@ -415,7 +424,11 @@ func (s *Server) billingViewFor(r *http.Request, in billingPageInput, st billing
v.Facts = append(v.Facts, fmt.Sprintf(billingCopy[key], packs[name], planLabel(name)))
}
if p, ok := cat.Plans[plan]; ok && p.Team != nil && b != nil {
- v.Facts = append(v.Facts, fmt.Sprintf(billingCopy["team.members"], members, b.PaidSeats))
+ key := "team.members_many"
+ if members == 1 {
+ key = "team.members_one"
+ }
+ v.Facts = append(v.Facts, fmt.Sprintf(billingCopy[key], members, b.PaidSeats))
}
if b != nil && b.Currency != "" {
v.Facts = append(v.Facts, fmt.Sprintf(billingCopy["fact.currency"], strings.ToUpper(b.Currency)))
@@ -435,9 +448,6 @@ func (s *Server) billingViewFor(r *http.Request, in billingPageInput, st billing
if v.Offers.Change && b != nil {
v.Change = billingChange(cat, book, plan, packs, b.Currency)
}
- if r.URL.Query().Get("welcome") == "1" {
- v.Welcome = billingWelcomeFor(in, st, v, limits)
- }
if v.Offers.StartOver && in.Intent != nil {
ci := in.Intent
v.StartOver = []billingField{{"plan", ci.Plan}, {"currency", ci.Currency}}
@@ -449,29 +459,58 @@ func (s *Server) billingViewFor(r *http.Request, in billingPageInput, st billing
return v
}
-// billingWelcomeFor is the thank-you panel for a page load carrying the
-// completed return's marker (?welcome=1), or nil. The marker proves
-// nothing on its own, so a stale or hand-typed one shows nothing extra:
-// the panel needs an owner whose account, on this load, holds a live,
-// paid subscription the billing doors manage with nothing for the page to
-// say about it (no notice, so not settling, collecting or ending), which
-// is when the page offers the change forms the panel's links jump to.
-func billingWelcomeFor(in billingPageInput, st billingPageState, v *billingView, limits *plans.Limits) *billingWelcome {
+// billingSuccessFor is the success screen for a page load carrying a
+// completed purchase's marker (?done=checkout, upgrade or packs), or nil.
+// The marker proves nothing on its own, so a stale, unknown or hand-typed
+// one shows the billing page: the screen needs an owner whose account, on
+// this load, holds a live, paid subscription the billing doors manage with
+// nothing for the page to say about it (no notice, so not settling,
+// collecting, waiting for payment or ending), which is when the page
+// offers the change forms the screen's links go back to.
+func billingSuccessFor(marker string, acct *Account, in billingPageInput, st billingPageState, v *billingView) *billingSuccess {
+ if marker != doneCheckout && marker != doneUpgrade && marker != donePacks {
+ return nil
+ }
b := in.Billing
if !in.Owner || st.Notice != "" || v.Change == nil || b == nil || !b.Live || b.State != billing.StatePaid ||
in.Row == nil || in.Row.Source != PlanSourceBilling {
return nil
}
- w := &billingWelcome{Packs: len(v.Change.Packs) > 0, Upgrade: len(v.Change.Upgrades) > 0}
- if l := limits; l != nil && l.RunningThings > 0 && l.DiskBytes > 0 {
+ page := billingPagePath(acct.Sqid)
+ ok := &billingSuccess{AppsURL: "/a/" + url.PathEscape(acct.Sqid) + "/"}
+ switch marker {
+ case doneCheckout:
+ ok.Title, ok.Lede = billingCopy["welcome.title"], fmt.Sprintf(billingCopy["welcome.lede"], acct.Name, v.Plan)
+ case doneUpgrade:
+ ok.Title, ok.Lede = fmt.Sprintf(billingCopy["done.upgrade.title"], v.Plan), fmt.Sprintf(billingCopy["done.upgrade.lede"], acct.Name)
+ case donePacks:
+ ok.Title, ok.Lede = billingCopy["done.packs.title"], fmt.Sprintf(billingCopy["done.packs.lede"], acct.Name)
+ }
+ if len(v.Change.Packs) > 0 {
+ ok.PacksURL = page + "#packs-title"
+ }
+ if len(v.Change.Upgrades) > 0 {
+ ok.UpgradeURL = page + "#upgrade"
+ }
+ if l := v.limits; l != nil && l.RunningThings > 0 && l.DiskBytes > 0 {
key := "welcome.room"
if l.CustomDomains {
key = "welcome.room_domains"
}
running := fmt.Sprintf(billingCopy["limit.running"], billingCount(int64(l.RunningThings)))
- w.Room = fmt.Sprintf(billingCopy[key], running, billingBytes(l.DiskBytes))
+ ok.Room = fmt.Sprintf(billingCopy[key], running, billingBytes(l.DiskBytes))
}
- return w
+ return ok
+}
+
+// renderBillingSuccess answers the success screen in place of the billing
+// page: the message and its links, and none of the page's sections or the
+// account's chrome (no nav, switcher or plan banners), only the console's
+// name linking home. The flash the purchase left is taken unshown: the
+// screen says what it said, and more.
+func (s *Server) renderBillingSuccess(w http.ResponseWriter, r *http.Request, view *billingView) {
+ s.takeFlash(w, r)
+ s.render(w, http.StatusOK, "billing_done", page{Title: view.Success.Title, Billing: view})
}
// billingBuy is the purchase form. The currency: an account's fixed one
diff --git a/internal/console/billingpage_copy.go b/internal/console/billingpage_copy.go
index 797caa0b3..be796d5f0 100644
--- a/internal/console/billingpage_copy.go
+++ b/internal/console/billingpage_copy.go
@@ -9,7 +9,7 @@ package console
// here. The change.* keys below are the plan's drafts for Task 10, declared
// here because Confirm now and the refusals of this task use them.
var billingCopy = map[string]string{
- "change.done": "Done. Your new limits apply now.",
+ "change.done": "Your billing change is saved.",
"change.pending": "Your card didn't go through, so nothing changed. Pay from Payment and invoices to finish.",
"change.declined": "Your card was declined, so nothing changed.",
"change.uncertain": "We couldn't confirm this payment yet. Check again in a few minutes.",
@@ -86,7 +86,8 @@ var billingCopy = map[string]string{
"buy.title": "Choose a plan",
"buy.button": "Continue to payment",
"team.price": "%s per member a year, for at least %d members",
- "team.members": "%d members, paid for %d",
+ "team.members_one": "%d member, %d seats paid for",
+ "team.members_many": "%d members, %d seats paid for",
"renews": "Renews on %s",
"button.confirm": "Confirm now",
"button.continue": "Continue to payment",
@@ -141,10 +142,10 @@ var billingCopy = map[string]string{
"duration.hour": "%d hour",
"duration.hours": "%d hours",
- // The thank-you panel after a completed purchase (2026-10-28): the
- // heading, a line naming the account and its plan, the room the plan
- // gives (with or without custom domains), and its three links. DRAFTS
- // for copy review.
+ // The success screen after a completed Checkout (2026-10-28, approved):
+ // the heading, a line naming the account and its plan, the room the
+ // plan gives (with or without custom domains), and the three links
+ // every success screen carries.
"welcome.title": "Thank you for subscribing",
"welcome.lede": "%s is now on %s. Your new limits are ready to use.",
"welcome.room": "You have room for %s, with %s of disk each.",
@@ -152,4 +153,14 @@ var billingCopy = map[string]string{
"welcome.packs": "Add packs",
"welcome.upgrade": "Upgrade",
"welcome.apps": "Go to your apps",
+
+ // The success screen after an upgrade or a pack raise the provider
+ // applied (2026-10-29): its heading and line, and the flash the change
+ // leaves in case the page can't show the screen. copy approved by Paul 2026-10-29.
+ "done.upgrade.title": "You're now on %s",
+ "done.upgrade.lede": "The new limits for %s are ready to use.",
+ "done.upgrade.flash": "You're now on %s.",
+ "done.packs.title": "Your packs are ready",
+ "done.packs.lede": "Your packs are ready to use on %s.",
+ "done.packs.flash": "Your packs are ready to use.",
}
diff --git a/internal/console/billingpage_test.go b/internal/console/billingpage_test.go
index e2f380681..71aa259c5 100644
--- a/internal/console/billingpage_test.go
+++ b/internal/console/billingpage_test.go
@@ -110,7 +110,7 @@ func TestDecideBillingPage(t *testing.T) {
"notice.unresolved", "notice.operator_plan", "notice.confirming", "notice.settling", "notice.pending_payment",
"notice.checkout_open", "notice.collecting", "notice.ending", "notice.seat_drift", "notice.owners_only",
"currency.refused", "currency.refused_unshown", "currency.fixed", "buy.title", "buy.button", "team.price",
- "team.members", "renews", "button.confirm", "button.continue", "button.start_over", "button.match_seats",
+ "team.members_one", "team.members_many", "renews", "button.confirm", "button.continue", "button.start_over", "button.match_seats",
"button.portal", "upgrade.not_owner_title", "upgrade.not_owner", "pick.title",
// Task 8's own labels and messages (no wording outside the map).
"page.eyebrow", "page.read_failed", "upgrade.read_failed", "error.title", "upgrade.new_account"} {
@@ -444,7 +444,7 @@ func TestBillingPagePaidFacts(t *testing.T) {
_, body := pf.page(t, "")
base := `action="/a/` + pf.acct.Sqid + `/billing/`
for _, want := range []string{
- esc(fmt.Sprintf(billingCopy["team.members"], 1, 12)),
+ esc(fmt.Sprintf(billingCopy["team.members_one"], 1, 12)),
esc(fmt.Sprintf(billingCopy["renews"], periodEnd.UTC().Format("2 January 2006"))),
esc(fmt.Sprintf(billingCopy["fact.currency"], "GBP")),
base + `change"`, base + `renewal"`, base + `portal"`,
@@ -960,7 +960,7 @@ func TestBillingPageActionsInOrder(t *testing.T) {
}
}
-// ---- the thank-you panel ----------------------------------------------------
+// ---- the success screen ---------------------------------------------------
// payFor makes the fixture's account a live, paid subscriber to plan with
// packs, in usd; mod adjusts the billing state first.
@@ -983,10 +983,10 @@ func (pf *billingPageFixture) payFor(t *testing.T, plan string, packs map[string
}
}
-// welcomePanel is the thank-you panel's markup in body, "" when it is not
-// there.
-func welcomePanel(body string) string {
- i := strings.Index(body, `<section class="welcome"`)
+// successScreen is the success screen's markup in body, "" when the page is
+// not the success screen.
+func successScreen(body string) string {
+ i := strings.Index(body, `<section class="done"`)
if i < 0 {
return ""
}
@@ -994,75 +994,140 @@ func welcomePanel(body string) string {
return s[:strings.Index(s, "</section>")+len("</section>")]
}
-// TestBillingPageWelcome: ?welcome=1 (the completed return's marker) shows
-// the thank-you panel above the summary, naming the account, the plan and
-// the room it gives, with Add packs and Upgrade jumping to sections that
-// exist on the page and Go to your apps. The marker alone proves nothing:
-// the panel shows only to an owner whose account is live and paid on that
-// page load.
-func TestBillingPageWelcome(t *testing.T) {
+// billingPageParts are markers of the billing page's own sections and the
+// account chrome around it, none of which the success screen carries.
+var billingPageParts = []string{
+ `class="tile billing-now"`, `id="packs-title"`, `id="upgrade"`, `class="banner`, `class="pagehead"`,
+ `<form`, `<nav`, `class="switcher"`, `/billing/change"`, `/billing/portal"`,
+}
+
+// TestBillingPageSuccessScreen: ?done=checkout, ?done=upgrade and
+// ?done=packs (the markers a completed purchase redirects with) replace
+// the billing page with a screen of its own: the message for that
+// purchase, the room the plan gives, and Add packs, Upgrade and Go to your
+// apps, with nothing else of the billing page or the account's chrome.
+// Add packs and Upgrade go back to the billing page's own sections.
+func TestBillingPageSuccessScreen(t *testing.T) {
pf := newBillingPageFixture(t)
sqid := pf.acct.Sqid
-
- // A free account: a hand-typed marker shows nothing extra.
- if _, body := pf.page(t, "welcome=1"); welcomePanel(body) != "" || strings.Contains(body, esc(billingCopy["welcome.title"])) {
- t.Fatalf("free account showed the panel:\n%s", body)
- }
-
- pf.payFor(t, "personal", map[string]int{}, nil)
- // Without the marker, a paid account's page is as before.
- if _, body := pf.page(t, ""); welcomePanel(body) != "" {
- t.Fatalf("no marker, yet the panel shows:\n%s", body)
- }
- _, body := pf.page(t, "welcome=1")
- panel := welcomePanel(body)
- if panel == "" {
- t.Fatalf("paid account with the marker: no panel:\n%s", body)
- }
- l, err := pf.srv.cfg.PlanCatalog.Effective("personal", nil, nil, 1)
+ pf.payFor(t, "personal", map[string]int{"apps": 2}, nil)
+ l, err := pf.srv.cfg.PlanCatalog.Effective("personal", map[string]int{"apps": 2}, nil, 1)
if err != nil {
t.Fatal(err)
}
room := fmt.Sprintf(billingCopy["welcome.room_domains"],
fmt.Sprintf(billingCopy["limit.running"], billingCount(int64(l.RunningThings))), billingBytes(l.DiskBytes))
- for _, want := range []string{
- esc(billingCopy["welcome.title"]),
- esc(fmt.Sprintf(billingCopy["welcome.lede"], pf.acct.Name, "Personal")),
- esc(room),
- `href="#packs-title"`, esc(billingCopy["welcome.packs"]),
- `href="#upgrade"`, esc(billingCopy["welcome.upgrade"]),
- `href="/a/` + sqid + `/"`, esc(billingCopy["welcome.apps"]),
+
+ _, plain := pf.page(t, "")
+ for _, c := range []struct {
+ marker string
+ title, lede string
+ }{
+ {"checkout", billingCopy["welcome.title"], fmt.Sprintf(billingCopy["welcome.lede"], pf.acct.Name, "Personal")},
+ {"upgrade", fmt.Sprintf(billingCopy["done.upgrade.title"], "Personal"), fmt.Sprintf(billingCopy["done.upgrade.lede"], pf.acct.Name)},
+ {"packs", billingCopy["done.packs.title"], fmt.Sprintf(billingCopy["done.packs.lede"], pf.acct.Name)},
} {
- if !strings.Contains(panel, want) {
- t.Errorf("panel is missing %q:\n%s", want, panel)
- }
+ t.Run(c.marker, func(t *testing.T) {
+ status, body := pf.page(t, "done="+c.marker)
+ screen := successScreen(body)
+ if status != http.StatusOK || screen == "" {
+ t.Fatalf("paid account with ?done=%s: %d, no success screen:\n%s", c.marker, status, body)
+ }
+ for _, want := range []string{
+ `<h1 id="done-title">` + esc(c.title) + `</h1>`,
+ esc(c.lede), esc(room),
+ `href="/a/` + sqid + `/billing#packs-title"`, esc(billingCopy["welcome.packs"]),
+ `href="/a/` + sqid + `/billing#upgrade"`, esc(billingCopy["welcome.upgrade"]),
+ `href="/a/` + sqid + `/"`, esc(billingCopy["welcome.apps"]),
+ } {
+ if !strings.Contains(screen, want) {
+ t.Errorf("the screen is missing %q:\n%s", want, screen)
+ }
+ }
+ if !strings.Contains(body, "<title>"+esc(c.title)+" · ") {
+ t.Errorf("the document title is not the screen's:\n%s", body[:strings.Index(body, "</title>")+8])
+ }
+ // Nothing of the billing page, and none of the account's
+ // chrome: no nav, no switcher, no forms at all.
+ for _, part := range billingPageParts {
+ if strings.Contains(body, part) {
+ t.Errorf("the success screen carries %q", part)
+ }
+ }
+ // Each link lands on an id the billing page itself has, without
+ // the marker (which would show this screen again).
+ for _, m := range regexp.MustCompile(`href="/a/[^"/]+/billing([^"]*)"`).FindAllStringSubmatch(screen, -1) {
+ frag, ok := strings.CutPrefix(m[1], "#")
+ if !ok || frag == "" {
+ t.Errorf("a link to the billing page carries %q, want only a fragment", m[1])
+ continue
+ }
+ if !strings.Contains(plain, `id="`+frag+`"`) {
+ t.Errorf("the screen links #%s, which the billing page has no id for", frag)
+ }
+ }
+ })
}
- // Every anchor the panel links lands on an id the page has.
- for _, m := range regexp.MustCompile(`href="#([^"]+)"`).FindAllStringSubmatch(panel, -1) {
- if !strings.Contains(body, `id="`+m[1]+`"`) {
- t.Errorf("the panel links #%s, which the page has no id for", m[1])
+
+ // An unknown marker, or the old one, is the billing page.
+ for _, q := range []string{"done=1", "done=refund", "welcome=1", "done="} {
+ if _, body := pf.page(t, q); successScreen(body) != "" || !strings.Contains(body, `class="tile billing-now"`) {
+ t.Errorf("?%s: want the billing page, no success screen", q)
}
}
- // The panel leads: above the summary tile.
- if i, j := strings.Index(body, `<section class="welcome"`), strings.Index(body, `class="tile billing-now"`); i > j {
- t.Error("the panel renders below the summary")
- }
- // It carries no form, so it adds nothing a CSRF check would have to cover.
- if strings.Contains(panel, "<form") {
- t.Errorf("the panel has a form:\n%s", panel)
+
+ // Without a marker, a paid account's page is the billing page.
+ if successScreen(plain) != "" || !strings.Contains(plain, `class="tile billing-now"`) {
+ t.Fatalf("no marker, yet the success screen shows:\n%s", plain)
}
// The top plan: nothing higher, so no Upgrade.
pf.payFor(t, "business", map[string]int{}, nil)
- _, body = pf.page(t, "welcome=1")
- if panel := welcomePanel(body); panel == "" || strings.Contains(panel, `href="#upgrade"`) || strings.Contains(panel, esc(billingCopy["welcome.upgrade"])) {
- t.Errorf("top plan: want the panel without Upgrade:\n%s", panel)
+ _, body := pf.page(t, "done=upgrade")
+ if screen := successScreen(body); screen == "" || strings.Contains(screen, `#upgrade"`) || strings.Contains(screen, esc(billingCopy["welcome.upgrade"])) {
+ t.Errorf("top plan: want the screen without Upgrade:\n%s", screen)
}
- if strings.Contains(body, `id="upgrade"`) {
- t.Error("top plan: an upgrades section with nothing in it")
+
+ // A plan with no packs: no Add packs.
+ cat := pf.srv.cfg.PlanCatalog
+ business := cat.Plans["business"]
+ business.Packs = nil
+ cat.Plans["business"] = business
+ _, body = pf.page(t, "done=checkout")
+ if screen := successScreen(body); screen == "" || strings.Contains(screen, `#packs-title"`) || strings.Contains(screen, esc(billingCopy["welcome.packs"])) {
+ t.Errorf("no packs: want the screen without Add packs:\n%s", screen)
}
- // Settling or collecting: the marker shows nothing extra, and the page
+ // The marker's flash steps aside: the screen says more.
+ pf.payFor(t, "personal", map[string]int{}, nil)
+ u, _ := url.Parse(pf.ts.URL)
+ done := fmt.Sprintf(billingCopy["checkout.done"], "Personal")
+ pf.owner.Jar.SetCookies(u, []*http.Cookie{{Name: flashCookie, Value: url.QueryEscape("ok|" + done), Path: "/"}})
+ _, body = pf.page(t, "done=checkout")
+ if successScreen(body) == "" || strings.Contains(body, esc(done)) {
+ t.Errorf("with the return's flash: want the screen and no flash:\n%s", body)
+ }
+ // ... and is taken, so it doesn't turn up on the next page either.
+ if _, body = pf.page(t, ""); strings.Contains(body, esc(done)) {
+ t.Error("the flash the screen replaced showed on the next page")
+ }
+}
+
+// TestBillingPageSuccessScreenRefused: the marker proves nothing on its own.
+// A free, settling, collecting or ending account, and a member, get the
+// billing page with no success screen, whatever the marker says.
+func TestBillingPageSuccessScreenRefused(t *testing.T) {
+ pf := newBillingPageFixture(t)
+ markers := []string{"checkout", "upgrade", "packs"}
+
+ // A free account: a hand-typed marker shows nothing extra.
+ for _, m := range markers {
+ if _, body := pf.page(t, "done="+m); successScreen(body) != "" || !strings.Contains(body, `class="tile billing-now"`) {
+ t.Errorf("free account, ?done=%s: want the billing page:\n%s", m, body)
+ }
+ }
+
+ // Settling, collecting, ending, or a plan an operator set: the page
// keeps its notice.
for _, c := range []struct {
name, notice string
@@ -1070,31 +1135,59 @@ func TestBillingPageWelcome(t *testing.T) {
}{
{"settling", "notice.settling", func(b *billingAccount) { b.State = billing.StatePending }},
{"collecting", "notice.collecting", func(b *billingAccount) { b.Collecting = true }},
+ {"unpaid", "notice.pending_payment", func(b *billingAccount) { b.PendingUpdate = true }},
} {
pf.payFor(t, "personal", map[string]int{}, c.mod)
- _, body := pf.page(t, "welcome=1")
- if welcomePanel(body) != "" || !strings.Contains(body, esc(billingCopy[c.notice])) {
- t.Errorf("%s: want its notice and no panel:\n%s", c.name, body)
+ for _, m := range markers {
+ _, body := pf.page(t, "done="+m)
+ if successScreen(body) != "" || !strings.Contains(body, esc(billingCopy[c.notice])) {
+ t.Errorf("%s, ?done=%s: want its notice and no screen:\n%s", c.name, m, body)
+ }
}
}
+ pf.payFor(t, "personal", map[string]int{}, func(b *billingAccount) { b.CancelAtPeriodEnd = true })
+ if _, body := pf.page(t, "done=upgrade"); successScreen(body) != "" || !strings.Contains(body, `class="tile billing-now"`) {
+ t.Errorf("renewal stopped, ?done=upgrade: want the billing page:\n%s", body)
+ }
- // A member never sees a purchase thank-you.
+ // A member never sees a purchase's success screen.
pf.payFor(t, "personal", map[string]int{}, nil)
if err := pf.st.AddMember(pf.acct.ID, "member@example.com", RoleMember, time.Now()); err != nil {
t.Fatal(err)
}
- member, _ := signInAs(t, pf.consoleFixture, "member@example.com", "code-billing-welcome-member")
- if _, _, body := get(t, member, pf.ts.URL+pf.billingPath("welcome=1")); welcomePanel(body) != "" {
- t.Errorf("a member saw the panel:\n%s", body)
+ member, _ := signInAs(t, pf.consoleFixture, "member@example.com", "code-billing-done-member")
+ for _, m := range markers {
+ if _, _, body := get(t, member, pf.ts.URL+pf.billingPath("done="+m)); successScreen(body) != "" || !strings.Contains(body, `class="tile billing-now"`) {
+ t.Errorf("a member, ?done=%s: want the billing page:\n%s", m, body)
+ }
}
+}
- // The return's plain flash steps aside for the panel.
- u, _ := url.Parse(pf.ts.URL)
- done := fmt.Sprintf(billingCopy["checkout.done"], "Personal")
- pf.owner.Jar.SetCookies(u, []*http.Cookie{{Name: flashCookie, Value: url.QueryEscape("ok|" + done), Path: "/"}})
- _, body = pf.page(t, "welcome=1")
- if welcomePanel(body) == "" || strings.Contains(body, esc(done)) {
- t.Errorf("with the return's flash: want the panel and no flash:\n%s", body)
+// TestBillingPageMembersPlural: the summary counts a team's members as
+// "1 member" and "2 members".
+func TestBillingPageMembersPlural(t *testing.T) {
+ pf := newBillingPageFixture(t)
+ pf.payFor(t, "community", map[string]int{}, nil)
+ summary := func() string {
+ _, body := pf.page(t, "")
+ i := strings.Index(body, `class="tile billing-now"`)
+ if i < 0 {
+ t.Fatalf("no summary:\n%s", body)
+ }
+ s := body[i:]
+ return s[:strings.Index(s, "</section>")]
+ }
+ seats := pf.srv.cfg.PlanCatalog.Plans["community"].Team.MinMembers
+ one := fmt.Sprintf(billingCopy["team.members_one"], 1, seats)
+ if s := summary(); !strings.Contains(s, esc(one)) || !strings.HasPrefix(one, "1 member,") {
+ t.Errorf("one member: want %q:\n%s", one, s)
+ }
+ if err := pf.st.AddMember(pf.acct.ID, "second@example.com", RoleMember, time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ two := fmt.Sprintf(billingCopy["team.members_many"], 2, seats)
+ if s := summary(); !strings.Contains(s, esc(two)) || !strings.HasPrefix(two, "2 members,") {
+ t.Errorf("two members: want %q:\n%s", two, s)
}
}
diff --git a/internal/console/fleethealth_test.go b/internal/console/fleethealth_test.go
new file mode 100644
index 000000000..83c9a5405
--- /dev/null
+++ b/internal/console/fleethealth_test.go
@@ -0,0 +1,124 @@
+package console
+
+import (
+ "context"
+ "encoding/json"
+ "net/http"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/provision"
+ "github.com/carlosframework/platform/internal/registry"
+ "github.com/carlosframework/platform/internal/release"
+ "github.com/carlosframework/platform/internal/status"
+)
+
+// writeFleetRolloutBox registers fleet to owner and writes, under the
+// fleet's own prefix, a box named machine reporting ro (and versions as its
+// route versions, which an Unavailable report's hosts come from), generated
+// at at.
+func writeFleetRolloutBox(t *testing.T, fx *consoleFixture, fleet, owner, machine string, at time.Time, ro *status.RolloutReport, versions map[string]string) {
+ t.Helper()
+ reg, err := registry.Open(fx.regPath)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer reg.Close()
+ if err := reg.UpsertFleet(registry.Fleet{Name: fleet, Account: owner, Bucket: fleet + "-bucket"}); err != nil {
+ t.Fatal(err)
+ }
+ box := status.CollectBox(nil, status.Probes{MachineID: machine}, at)
+ box.Metrics = &status.BoxMetrics{Rollout: ro, RouteVersions: versions}
+ if err := status.WriteBox(context.Background(), release.NewPrefixStore(fx.rel, "fleets/"+fleet+"/"), box); err != nil {
+ t.Fatal(err)
+ }
+}
+
+// listHealth is the instance list's health word per host.
+func listHealth(t *testing.T, fx *consoleFixture, token, app string) map[string]string {
+ t.Helper()
+ code, _, out := rawReq(t, http.MethodGet, fx.ts.URL+"/api/cli/apps/"+fx.sqid+"/"+app+"/instances", token, "")
+ if code != http.StatusOK {
+ t.Fatalf("list = %d %s", code, out)
+ }
+ var list struct {
+ Instances []struct {
+ Host string `json:"host"`
+ Health string `json:"health"`
+ } `json:"instances"`
+ }
+ if err := json.Unmarshal([]byte(out), &list); err != nil {
+ t.Fatal(err)
+ }
+ got := map[string]string{}
+ for _, r := range list.Instances {
+ got[r.Host] = r.Health
+ }
+ return got
+}
+
+// #366 Task 11 follow-up: a record placed on the caller's own fleet takes
+// its health word from that fleet box's rollout report (the join the
+// list's rollout column reads), as a platform-remote record takes its word
+// from its box: awake is Running, a hibernating instance not awake is
+// Asleep, a host held down is Failed. Everything the join cannot vouch for
+// stays "Can't tell right now": a host starting or stopping, a report
+// naming another app, a box that could not arm its scheduler, a host no
+// box reports, another account's fleet box naming this app's host, and a
+// report generated before the record was created (an earlier lifetime of
+// the same host, account and app; the platform-remote rule, appFacts.host).
+// Every other report here is generated after the records, the control.
+func TestFleetPlacedHealthComesFromItsFleetBox(t *testing.T) {
+ fx := newConsoleFixture(t)
+ const app = "kass"
+ host := func(slug string) string { return slug + ".kass.carlosapp.dev" }
+ asleep := true
+ now := time.Now().UTC()
+ created := now.Add(-10 * time.Second)
+ for _, slug := range []string{"run", "nap", "down", "busy", "other", "gone", "stranger", "unavail", "reborn"} {
+ place := registry.PlacementTarget("pi")
+ if slug == "stranger" {
+ place = registry.PlacementTarget("stranger")
+ }
+ if err := provision.CreateRecord(context.Background(), fx.rel, provision.Record{
+ Schema: 1, Host: host(slug), Slug: slug, App: app, Account: fx.sqid, Region: place,
+ Channel: "stable", Hibernate: &asleep, CreatedAt: created, CreatedBy: "paul@keymail.dev",
+ }); err != nil {
+ t.Fatal(err)
+ }
+ }
+ mine := func(hr status.HostRollout) status.HostRollout {
+ hr.Account, hr.App, hr.Installed = fx.sqid, app, "v1"
+ return hr
+ }
+ writeFleetRolloutBox(t, fx, "pi", fx.sqid, "pi-box", now, &status.RolloutReport{Hosts: map[string]status.HostRollout{
+ host("run"): mine(status.HostRollout{Awake: true}),
+ host("nap"): mine(status.HostRollout{}),
+ host("down"): mine(status.HostRollout{Attempt: status.AttemptDown, AttemptBuild: "v1"}),
+ host("busy"): mine(status.HostRollout{Transient: true}),
+ host("other"): {Account: fx.sqid, App: "other", Installed: "v1", Awake: true},
+ }}, nil)
+ writeFleetRolloutBox(t, fx, "pi", fx.sqid, "pi-box-2", now, &status.RolloutReport{Unavailable: "flag-off"},
+ map[string]string{host("unavail"): "v1"})
+ writeFleetRolloutBox(t, fx, "stranger", "zzz", "stranger-box", now, &status.RolloutReport{Hosts: map[string]status.HostRollout{
+ host("stranger"): mine(status.HostRollout{Awake: true}),
+ }}, nil)
+ // Fresh (well inside the staleness window) but from before the record.
+ writeFleetRolloutBox(t, fx, "pi", fx.sqid, "pi-box-old", created.Add(-10*time.Second), &status.RolloutReport{Hosts: map[string]status.HostRollout{
+ host("reborn"): mine(status.HostRollout{Awake: true}),
+ }}, nil)
+ token := cliToken(t, fx, "paul@keymail.dev", "code-fleet-health")
+
+ got := listHealth(t, fx, token, app)
+ want := map[string]string{
+ host("run"): "Running", host("nap"): "Asleep", host("down"): "Failed",
+ host("busy"): healthUnknown, host("other"): healthUnknown, host("gone"): healthUnknown,
+ host("stranger"): healthUnknown, host("unavail"): healthUnknown, host("reborn"): healthUnknown,
+ }
+ for h, w := range want {
+ if got[h] != w {
+ t.Errorf("%s health = %q, want %q", strings.SplitN(h, ".", 2)[0], got[h], w)
+ }
+ }
+}
diff --git a/internal/console/templates/billing.html b/internal/console/templates/billing.html
index cecc780b8..bc195aff5 100644
--- a/internal/console/templates/billing.html
+++ b/internal/console/templates/billing.html
@@ -6,18 +6,6 @@
<h1>{{billingText "page.title"}}</h1>
</div>
{{with .Billing}}
-{{with .Welcome}}<section class="welcome" aria-labelledby="welcome-title">
- <span class="welcome-mark">{{icon "check"}}</span>
- <div>
- <h2 id="welcome-title">{{billingText "welcome.title"}}</h2>
- <p>{{.Lede}}{{if .Room}} {{.Room}}{{end}}</p>
- <p class="welcome-actions">
- {{if .Packs}}<a class="btn btn-secondary" href="#packs-title">{{billingText "welcome.packs"}}</a>
- {{end}}{{if .Upgrade}}<a class="btn btn-secondary" href="#upgrade">{{billingText "welcome.upgrade"}}</a>
- {{end}}<a class="btn" href="{{$.Base}}/">{{billingText "welcome.apps"}}</a>
- </p>
- </div>
-</section>{{end}}
{{if .Notice}}<p class="banner">{{.Notice}}</p>{{end}}
{{if .OwnersOnly}}<p class="banner">{{.OwnersOnly}}</p>{{end}}
{{if .CurrencyNotice}}<p class="banner error">{{.CurrencyNotice}}</p>{{end}}
diff --git a/internal/console/templates/billing_done.html b/internal/console/templates/billing_done.html
new file mode 100644
index 000000000..3962409f2
--- /dev/null
+++ b/internal/console/templates/billing_done.html
@@ -0,0 +1,17 @@
+{{define "billing_done"}}{{template "top" .}}
+{{/* The success screen after a completed purchase: it replaces the billing
+ page, so it carries the message and its links and nothing else. The
+ page is rendered without the account's chrome (renderBillingSuccess):
+ the header holds only the console's name. */}}
+{{with .Billing.Success}}<section class="done" aria-labelledby="done-title">
+ <span class="done-mark">{{icon "check"}}</span>
+ <h1 id="done-title">{{.Title}}</h1>
+ <p class="done-lede">{{.Lede}}</p>
+ {{if .Room}}<p class="done-room">{{.Room}}</p>
+ {{end}}<p class="done-actions">
+ {{if .PacksURL}}<a class="btn btn-secondary" href="{{.PacksURL}}">{{billingText "welcome.packs"}}</a>
+ {{end}}{{if .UpgradeURL}}<a class="btn btn-secondary" href="{{.UpgradeURL}}">{{billingText "welcome.upgrade"}}</a>
+ {{end}}<a class="btn" href="{{.AppsURL}}">{{billingText "welcome.apps"}}</a>
+ </p>
+</section>{{end}}
+{{template "bottom" .}}{{end}}
diff --git a/internal/console/templates/layout.html b/internal/console/templates/layout.html
index 31cda574c..ac5827eeb 100644
--- a/internal/console/templates/layout.html
+++ b/internal/console/templates/layout.html
@@ -785,44 +785,41 @@
.buy-foot { margin: 1.75rem 0 0; }
.buy-foot button { padding: 0.7rem 1.5rem; }
.billing-upgrades { margin-top: 1.25rem; }
- /* The thank-you panel after a completed purchase: the one moment on
- this page that gets a flourish. A check that draws itself once in an
- accent disc, a heading with room to breathe, the plan's room in a
- sentence, and three links (Add packs and Upgrade jump down the page).
- It sits on the page's own background inside an accent edge, so it
- reads apart from the tinted summary tile beneath it. */
- .welcome {
- display: grid; grid-template-columns: auto minmax(0, 1fr); gap: 0 1.1rem;
- margin: 0 0 1.5rem; padding: 1.4rem 1.5rem 1.5rem;
- border: 1px solid color-mix(in srgb, var(--accent) 45%, var(--rule));
- border-radius: 0.75rem; background: var(--bg);
- }
- .welcome-mark {
- display: grid; place-items: center; width: 2.6rem; height: 2.6rem; border-radius: 50%;
- background: var(--accent); color: var(--bg);
- }
- .welcome-mark .icon { width: 1.35rem; height: 1.35rem; stroke-width: 2.6; }
- .welcome h2 { margin: 0.35rem 0 0.4rem; font-size: 1.45rem; line-height: 1.25; letter-spacing: -0.01em; text-wrap: balance; }
- .welcome p { margin: 0; max-width: 62ch; text-wrap: pretty; overflow-wrap: anywhere; }
- .welcome .welcome-actions { display: flex; flex-wrap: wrap; gap: 0.6rem; margin: 1.15rem 0 0; max-width: none; }
- .welcome-actions .btn { padding: 0.55rem 1.1rem; }
- .welcome-actions .btn:not(.btn-secondary) { border: 1px solid transparent; }
- /* The links land on headings, a little clear of the window's top. */
+ /* The success screen after a completed purchase (billing_done.html):
+ it replaces the billing page, so it stands alone in the middle of an
+ otherwise empty page. A check that draws itself once in an accent
+ disc, the heading, the plan's room in a sentence, and its links:
+ Add packs and Upgrade go back to the billing page's sections, Go to
+ your apps is the way on. */
+ .done { max-width: 36rem; margin: clamp(1rem, 9vh, 5.5rem) auto 0; text-align: center; }
+ .done-mark {
+ display: inline-grid; place-items: center; width: 3.25rem; height: 3.25rem; border-radius: 50%;
+ margin: 0 0 1.4rem; background: var(--accent); color: var(--bg);
+ }
+ .done-mark .icon { width: 1.6rem; height: 1.6rem; stroke-width: 2.6; }
+ .done h1 { margin: 0 0 0.8rem; font-size: clamp(1.65rem, 1.2rem + 1.6vw, 2.15rem); line-height: 1.15; letter-spacing: -0.015em; text-wrap: balance; overflow-wrap: anywhere; }
+ .done-lede, .done-room { margin: 0 auto; max-width: 32rem; text-wrap: pretty; overflow-wrap: anywhere; }
+ .done-lede { font-size: 1.05rem; }
+ .done-room { margin-top: 0.5rem; color: var(--muted); }
+ .done-actions { display: flex; flex-wrap: wrap; justify-content: center; gap: 0.6rem; margin: 2rem 0 0; }
+ .done-actions .btn { padding: 0.6rem 1.25rem; }
+ .done-actions .btn:not(.btn-secondary) { border: 1px solid transparent; }
+ .done-actions .btn:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
+ /* Its links land on these headings, a little clear of the window's top. */
#packs-title, #upgrade { scroll-margin-top: 1.5rem; }
@media (prefers-reduced-motion: no-preference) {
- .welcome-mark { animation: welcome-pop 520ms cubic-bezier(0.16, 1, 0.3, 1) both; }
- .welcome-mark path { stroke-dasharray: 24; animation: welcome-draw 480ms 200ms cubic-bezier(0.16, 1, 0.3, 1) both; }
+ .done-mark { animation: done-pop 520ms cubic-bezier(0.16, 1, 0.3, 1) both; }
+ .done-mark path { stroke-dasharray: 24; animation: done-draw 480ms 200ms cubic-bezier(0.16, 1, 0.3, 1) both; }
}
- @keyframes welcome-pop { from { transform: scale(0.7); } }
- @keyframes welcome-draw { from { stroke-dashoffset: 24; } to { stroke-dashoffset: 0; } }
+ @keyframes done-pop { from { transform: scale(0.7); } }
+ @keyframes done-draw { from { stroke-dashoffset: 24; } to { stroke-dashoffset: 0; } }
@media (min-width: 46rem) {
.billing-includes { grid-template-columns: repeat(2, auto); }
}
@media (max-width: 40rem) {
.billing-now { padding: 1rem 1.1rem 1.1rem; }
- .welcome { grid-template-columns: minmax(0, 1fr); padding: 1.2rem 1.15rem 1.25rem; }
- .welcome h2 { margin-top: 0.8rem; font-size: 1.3rem; }
- .welcome-actions .btn { flex: 1 1 8rem; text-align: center; }
+ .done-actions { flex-direction: column; align-items: stretch; margin-top: 1.75rem; }
+ .done-actions .btn { text-align: center; }
.packs tr {
display: grid; grid-template-columns: minmax(0, 1fr) auto; align-items: center;
gap: 0.6rem 1rem; padding: 0.8rem 0; border-bottom: 1px solid var(--rule);
diff --git a/internal/provision/plan9_b8_census_test.go b/internal/provision/plan9_b8_census_test.go
index 4527593f2..0098f6133 100644
--- a/internal/provision/plan9_b8_census_test.go
+++ b/internal/provision/plan9_b8_census_test.go
@@ -366,7 +366,7 @@ func TestPlan9B8RecordWriteCensus(t *testing.T) {
if len(got) < 100 {
t.Fatalf("census found only %d units under %s; the walk is broken", len(got), root)
}
- inventory := fleetSecretsKeyWriteCensusInventory()
+ inventory := rootfsFleetFollowupsWriteCensusInventory()
problems := append(censusDiff(inventory, got), censusPolicy(inventory)...)
if len(problems) > 0 {
t.Fatalf("record-write census rejected %d site(s); update the explicit inventory only after reviewing the source:\n %s", len(problems), strings.Join(problems, "\n "))
diff --git a/internal/provision/rootfs_check_volumes_census_test.go b/internal/provision/rootfs_check_volumes_census_test.go
new file mode 100644
index 000000000..79496b2cb
--- /dev/null
+++ b/internal/provision/rootfs_check_volumes_census_test.go
@@ -0,0 +1,37 @@
+package provision
+
+// Record-write census entries for the ship --check data volume fix (#366,
+// branch rootfs-check-volumes), layered on fleetSecretsKeyWriteCensusInventory
+// (main's newest at the branch's base 1fa2a99b). Reviewed by the branch
+// author against the source; the census approval is recorded on #280 with
+// the root-read card
+// (docs/superpowers/notes/census-proposal-rootfs-check-volumes.md).
+//
+// One re-pin, no new unit:
+// - main.go main (key-site): dispatches __rootfs-check-prepare, the
+// carlos ship --check verb that makes the check's data volume its user's
+// inside a container on the person's machine, beside
+// __rootfs-check-probe and before the command switch; its instances and
+// sidecars literals are unchanged. It writes no record.
+func rootfsCheckVolumesWriteCensusInventory() []censusEntry {
+ entries := append([]censusEntry(nil), fleetSecretsKeyWriteCensusInventory()...)
+ repins := []censusEntry{
+ // rootfs-check-volumes: the __rootfs-check-prepare dispatch beside __rootfs-check-probe; the same literals.
+ {"main.go", "main", "key-site", "lit:instances,lit:sidecars", "9ce797683088785d55882487096e45cdbbd664fc692ccfe67c4eaea76c1be863"},
+ }
+ for _, r := range repins {
+ found := false
+ for i, e := range entries {
+ if e.File == r.File && e.Unit == r.Unit {
+ if e.Class != r.Class || e.Kinds != r.Kinds {
+ panic("rootfs-check-volumes re-pin changes the class or kinds of " + r.File + ":" + r.Unit)
+ }
+ entries[i], found = r, true
+ }
+ }
+ if !found {
+ panic("rootfs-check-volumes re-pin of an unlisted unit " + r.File + ":" + r.Unit)
+ }
+ }
+ return entries
+}
diff --git a/internal/provision/rootfs_fleet_followups_census_test.go b/internal/provision/rootfs_fleet_followups_census_test.go
new file mode 100644
index 000000000..b8c263799
--- /dev/null
+++ b/internal/provision/rootfs_fleet_followups_census_test.go
@@ -0,0 +1,38 @@
+package provision
+
+// Record-write census entries for the rootfs fleet follow-ups (#366,
+// branch rootfs-fleet-followups), layered on
+// rootfsCheckVolumesWriteCensusInventory (main's newest at 43c8677a, merged
+// into the branch; it layers on fleetSecretsKeyWriteCensusInventory, the
+// newest at the branch's base 1fa2a99b). Reviewed by the branch author against the source; the census
+// approval is recorded on #280 with the root-read card
+// (docs/superpowers/notes/census-proposal-rootfs-fleet-followups.md).
+//
+// One re-pin, no new unit:
+// - internal/console/apiinstances.go Server.handleAPIInstanceList
+// (key-site): after instanceHealth, fleetHealth fills the health word of
+// a fleet-placed record still unknown from the rollout join the handler
+// already loads (join.rollout, its tenant rule kept). The record listing
+// and its literal are unchanged; it writes no record.
+func rootfsFleetFollowupsWriteCensusInventory() []censusEntry {
+ entries := append([]censusEntry(nil), rootfsCheckVolumesWriteCensusInventory()...)
+ repins := []censusEntry{
+ // rootfs-fleet-followups: fleetHealth after instanceHealth; the same listing and literal.
+ {"internal/console/apiinstances.go", "Server.handleAPIInstanceList", "key-site", "lit:instances", "fc3da89d5a32eeed50e4a5c4811d2f90e0a2bce9a49bd2d71694844d5b1009d3"},
+ }
+ for _, r := range repins {
+ found := false
+ for i, e := range entries {
+ if e.File == r.File && e.Unit == r.Unit {
+ if e.Class != r.Class || e.Kinds != r.Kinds {
+ panic("rootfs-fleet-followups re-pin changes the class or kinds of " + r.File + ":" + r.Unit)
+ }
+ entries[i], found = r, true
+ }
+ }
+ if !found {
+ panic("rootfs-fleet-followups re-pin of an unlisted unit " + r.File + ":" + r.Unit)
+ }
+ }
+ return entries
+}
diff --git a/internal/provision/testdata/plan14-root-reads-chain.tsv b/internal/provision/testdata/plan14-root-reads-chain.tsv
index dbafce313..21ea3b3ad 100644
--- a/internal/provision/testdata/plan14-root-reads-chain.tsv
+++ b/internal/provision/testdata/plan14-root-reads-chain.tsv
@@ -34,4 +34,6 @@ plan14-root-reads-static-dir-slash.tsv fb7cd756f7c3eb2dc019c8fd55fea5475e2df7ee3
plan14-root-reads-named-unit-delivery-114.tsv d92c9d40eb2a9e66c859e2fe6df3af10a1b9d3a83b1d717ec928cb432eebb1aa
plan14-root-reads-fleet-secrets-key.tsv 9df7f5aca9a502966c9643b7062829c1c25bfbd86fa20e92d764d66f676d2cd6
plan14-root-reads-static-headers.tsv 94b8ccf921f64be24a4773f72d55a8e24ceba3acfb40eefe3b56af6f5b008138
-plan14-root-reads-region-ha-p1b2.tsv b8341530f4a5e8101746f610ee8eb25bd273bed6f45bf6a2ff279e9b8c20c0b1
+plan14-root-reads-rootfs-check-volumes.tsv 042684bf5af6f61ce8b87f10b68a42b08d131ba4cb5bcab16320c7b032a724e6
+plan14-root-reads-rootfs-fleet-followups.tsv 78b7e7e30ad3ada44388a4ee16f3950ef888ae03e552477dcbfbb07c51ffb83e
+plan14-root-reads-region-ha-p1b2.tsv f8190d29dc824bfb15be305c0363f95709239d1711df7fbe4fb86bb5a423985c
diff --git a/internal/provision/testdata/plan14-root-reads-region-ha-p1b2.tsv b/internal/provision/testdata/plan14-root-reads-region-ha-p1b2.tsv
index ab83fbc33..9ef385e37 100644
--- a/internal/provision/testdata/plan14-root-reads-region-ha-p1b2.tsv
+++ b/internal/provision/testdata/plan14-root-reads-region-ha-p1b2.tsv
@@ -27,5 +27,5 @@ internal/activator/haforward.go noteNoHolder legacy accepted-legacy accepted-leg
internal/edge/forwardha.go Edge.frontForwardHA legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p1b2;basis=new (region HA P1b-2): the agent's edge decides at the front door whether to forward a visitor request: reads the route's HA flag and host from the box's own registry row and asks the activator; forwards only to a box in view over the existing signed hop; root never calls it registry:HA@225,registry:Host@501,whole:Route@228,whole:Route@407,whole:Route@504 2c9936721e996db822dca79af3597ed2c0fd29aa29e40fa6fc1f7512b3867106
internal/activator/activator.go Service.serveWakeError diagnostic C,J4 rev3=PROPOSED-seed; incarnation-keyed missing-files diagnostics and indexed retry results; throttles output only and grants no retry, stop or launch;rev3=census-ruling-region-ha-p1a;basis=the agent as carlos: one more case, errLeaseRefused (a born-HA host outside the nested layout or an HA acquire's refusal): logged at most once per diagnostic window (allowFilesDiagnostic(rt.Host, ...)) and answered 503 with Retry-After: 10; the other cases unchanged; +registry:Host x2 are rt.Host in that call and the log line; it only answers;rev3=census-ruling-rootfs-apps-3;basis=rootfs Plan 3 Tasks 7 and 8: two new answers, a resident inside its backoff gets 503 with Retry-After (RFS-3-C16), and a rootfs row refused before the lease (errRootfsNotAdmitted) gets the existing wake-failed 503; no read added;rev3=census-ruling-region-ha-p1b2;basis=region HA P1b-2: for a verified HA hop, a held lease answers 503 Retry-After 1 with X-Carlos-Holder (answerForwarded) and every other refusal adds X-Carlos-Holder: none (noteNoHolder); legacy routes and cancellation unchanged; same reads registry:Host@1070,registry:Host@1134,registry:Host@2836,registry:Host@2900,whole:Route@204 a8834927132e29ac5cdf44b5caced8dc010d538f6552979f90b226a09fd13c2f
internal/activator/activator.go Service.serve legacy accepted-legacy accepted-legacy;rev3=census-ruling-hotfix281;basis=Startup repeats the existing Kind and Hibernate checks; error logging moved to serveWakeError. A request held through startup re-reads its own route's Socket and Addr and can only refuse (wake-timeout 503) when recovery moved them; agent-side, deny-only, no root decision.;rev3=census-ruling-edge-request-records;basis=passes the member request r to begin's new req parameter; no read added;rev3=census-ruling-rootfs-apps-3;basis=rootfs Plan 3 Task 5: the activator-managed test is Route.ActivatorOwned instead of Kind and Hibernate inline, so a resident rootfs instance is the activator's; same deploy-safety for binary rows;rev3=census-ruling-region-ha-p1b2;basis=region HA P1b-2: a verified HA hop this box cannot serve gets the holder diagnostic; two new whole:Route sites pass the route to answerForwarded/noteNoHolder; no new kind of read registry:Addr@934,registry:Addr@948,registry:Host@1059,registry:Host@859,registry:Socket@905,registry:Socket@921,whole:Route@1127,whole:Route@2676,whole:Route@2777,whole:Route@329,whole:Route@3497,whole:Route@3560,whole:Route@884,whole:Route@993 d788f023e71cf3bc6bdadf106da3ed981b96e06a2a3408220b48dcf65fba419d
-@coverage internal/activator d5e9cdd31f858c89c15724600c2363663349cbf387bfb65a37dedc7773d38437
+@coverage internal/activator 3d191c062bd8b8938d742e0fe6e98088e07d9016f42d83ff9362d1e4f8352997
@coverage internal/edge fa1a9346be25056af127a10080582c20bae1407c7fba98ddce52e79b99c0b8de
diff --git a/internal/provision/testdata/plan14-root-reads-rootfs-check-volumes.tsv b/internal/provision/testdata/plan14-root-reads-rootfs-check-volumes.tsv
new file mode 100644
index 000000000..714a190c3
--- /dev/null
+++ b/internal/provision/testdata/plan14-root-reads-rootfs-check-volumes.tsv
@@ -0,0 +1,8 @@
+# Census overlay rootfs-check-volumes, written by census-propose (#369). census-ruling-rootfs-check-volumes, approved on #280 before the merge; the approval card is docs/superpowers/notes/census-proposal-rootfs-check-volumes.md.
+# 1 body, 0 sites, 1 envelope: each changed unit re-frozen at its existing disposition with its claim appended.
+# 1 new dispositions: 0 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 055963a9e0d8e690476664799c9ab21df3fcd3ab42960247a6abe38fbf2baa17 ship_check.go rootfsCheck.runArgs legacy accepted-legacy accepted-legacy;rev3=census-ruling-rootfs-apps-1;basis=root-input (J4, as main's db.go units); the carlos CLI on a person's machine, as the person (no box unit): new (rootfs Plan 1), builds the docker or podman run argv for one check container; the scanner matches the word Command, here a field of release.Process (a process's argv), not os/exec; reads no file; decides nothing for root;rev3=census-ruling-rootfs-check-volumes;basis=R2 P1: the data and run volume mounts (-v) now carry :nocopy through rootfsCheck.volumeMount, so Docker and Podman never fill an empty check volume from the image directory at the mount point (which would reset the prepared owner and mode); same volumes, same paths, same probe mount, nothing else in the argv changed. Runs on the person's machine as the person; no box unit; no read added. file:Command@764,file:Command@848 a7bd986343e647262402a363cfb374c34bdd3ecf35cbb452d9e8816d88d4a02c
+@legacy b88e56ecd81527322832b883453084fda8bde581689e0e13fbe3a79170889c2e ship_check_probe.go prepareCheckDir legacy accepted-legacy accepted-legacy;rev3=census-ruling-rootfs-check-volumes;basis=new: __rootfs-check-prepare (carlos ship --check), run only inside the check's prepare container on the person's machine (as 0:0 with CAP_CHOWN alone, no network, read-only root), never by a box: Lstats the one directory it is given (the check's data volume at /data/instances/check), refuses a symlink or non-directory, then chmod 0700 and lchown to --uid:--uid; no recursion. Read added: file:Lstat of that path. R1 P2: the chmod and lchown go through package vars checkChmod/checkLchown (os.Chmod, os.Lchown; only tests change them) so a test pins the order; same calls, same arguments. main.go dispatches the verb before the command switch beside __rootfs-check-probe; no root unit calls it. file:Lstat@67 8633a0299cf2abee0b320ba4701137f31ada646c0d6c8310b6052054d5dad87f
+ship_check.go rootfsCheck.runArgs legacy accepted-legacy accepted-legacy;rev3=census-ruling-rootfs-apps-1;basis=root-input (J4, as main's db.go units); the carlos CLI on a person's machine, as the person (no box unit): new (rootfs Plan 1), builds the docker or podman run argv for one check container; the scanner matches the word Command, here a field of release.Process (a process's argv), not os/exec; reads no file; decides nothing for root;rev3=census-ruling-rootfs-check-volumes;basis=R2 P1: the data and run volume mounts (-v) now carry :nocopy through rootfsCheck.volumeMount, so Docker and Podman never fill an empty check volume from the image directory at the mount point (which would reset the prepared owner and mode); same volumes, same paths, same probe mount, nothing else in the argv changed. Runs on the person's machine as the person; no box unit; no read added. file:Command@764,file:Command@848 a7bd986343e647262402a363cfb374c34bdd3ecf35cbb452d9e8816d88d4a02c
+ship_check_probe.go prepareCheckDir legacy accepted-legacy accepted-legacy;rev3=census-ruling-rootfs-check-volumes;basis=new: __rootfs-check-prepare (carlos ship --check), run only inside the check's prepare container on the person's machine (as 0:0 with CAP_CHOWN alone, no network, read-only root), never by a box: Lstats the one directory it is given (the check's data volume at /data/instances/check), refuses a symlink or non-directory, then chmod 0700 and lchown to --uid:--uid; no recursion. Read added: file:Lstat of that path. R1 P2: the chmod and lchown go through package vars checkChmod/checkLchown (os.Chmod, os.Lchown; only tests change them) so a test pins the order; same calls, same arguments. main.go dispatches the verb before the command switch beside __rootfs-check-probe; no root unit calls it. file:Lstat@67 8633a0299cf2abee0b320ba4701137f31ada646c0d6c8310b6052054d5dad87f
+@coverage . b86ad1c792b5fb3a92985bad439972463cdec87b3f066fe5e37f0beb32954d7d
diff --git a/internal/provision/testdata/plan14-root-reads-rootfs-fleet-followups.tsv b/internal/provision/testdata/plan14-root-reads-rootfs-fleet-followups.tsv
new file mode 100644
index 000000000..7fbb80339
--- /dev/null
+++ b/internal/provision/testdata/plan14-root-reads-rootfs-fleet-followups.tsv
@@ -0,0 +1,15 @@
+# Census overlay rootfs-fleet-followups, written by census-propose (#369). census-ruling-rootfs-fleet-followups, approved on #280 before the merge; the approval card is docs/superpowers/notes/census-proposal-rootfs-fleet-followups.md.
+# 2 body, 2 sites, 2 envelope: each changed unit re-frozen at its existing disposition with its claim appended.
+# 1 new dispositions: 0 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 d82ca4f88546b2b29b8e9619c60118f3b3f1c492c071d39f7ae63f334d9ed6cb internal/activator/prepare.go ExecBackend.prepareKeyedAt legacy accepted-legacy accepted-legacy;rev3=census-ruling-carlos-run;basis=Re-digested at the pre-land merge: the body includes main's own change under census ruling zddr4, with no further change from this branch beyond carrying main's new early return into the six-value signature. the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): body of the frozen prepareAt, which is now its wrapper; it also returns the instance key's layer and reads no env for the cmd role; same reads, same nested launch paths;rev3=census-ruling-wake-latency-2;basis=takes an optional timer and marks its steps with time.Now() (dirs, admin token, instance key, env, control socket, key gate, logs); no read added or moved;rev3=census-ruling-region-ha-p1a;basis=the agent as carlos, run and seed roles only, under a 30 s context (haSecretsBudget): the token producer is ensureAdminTokenFor(hctx, rt, p) (on this nested path the same beneath producer, EnsureAdminTokenBeneath's, plus the HA mint decision inside it); ensureInstanceKeyFor now gets hctx instead of context.Background(), so the key's bucket read is bounded by 30 s as well as configReadTimeout; the env is launchEnvLayer(hctx, rt) (instanceEnvLayer for a non-HA host; for an HA host one capture, published and acknowledged); a test seam (haLaunchHooks.afterGate, nil in production) is called before the producers. The separate haMintGate and haSecretsReady calls are gone (final fix F2). Sites against main: -registry:Host (the rt.Host+".env" argument EnsureAdminTokenBeneath took) and +whole:Route (rt to launchEnvLayer); the cmd role and a non-HA host are unchanged;rev3=census-ruling-rootfs-fleet-followups;basis=names the process for the role log listener: release.ProcessWeb when rt.Rootfs() and the role is run, else none, passed to logEmitter; reads rt.Runtime through Rootfs(); no file, path or env read added or moved file:ReadDir@2929,registry:Host@1770,registry:Host@1982,registry:Host@5787,registry:Host@5985,registry:Host@612,whole:Route@1661,whole:Route@1872,whole:Route@2103,whole:Route@320,whole:Route@4642,whole:Route@5170,whole:Route@5821 0c049e8ff1256f466b0f6e770d65c9e0ba6943f03c377924481e0210c723da30
+@legacy 2467c84503328707bba08f52e54cc3498f611783447a44511b49a4df0b1ea58d internal/activator/prepare.go ExecBackend.prepareWorker legacy accepted-legacy accepted-legacy;rev3=census-ruling-rootfs-apps-3-workers;basis=rootfs Plan 3 Group W, W1: prepare for a worker: the instance's two directories and the worker log socket's, the worker's stale exit records cleared by its name prefix (another worker's and every generation's kept), its log listener bound where root's worker drop-in points StandardOutput=; reads no environment file; binds no control listener; asks no replica gate;rev3=census-ruling-rootfs-fleet-followups;basis=passes the worker name (already checked by release.ValidWorkerName at the top) to logEmitter as the process; no read added or moved file:ReadDir@563,registry:Host@224,registry:Host@440,registry:Host@902,whole:Route@124,whole:Route@809 a22180a3d5c23b92e9c227a45e90e482fc5789baec5345f1151e37773b5941f8
+@legacy 5e26653fcccbee1e5f20286530b4789cd53e32d7984fabcbff14824667457077 internal/activator/logsink.go appLineEmitter legacy accepted-legacy accepted-legacy;rev3=census-ruling-rootfs-fleet-followups;basis=new: the app-line emit function for rt: nil for a nil sink; reads the route account (release.RouteAccount), app and host; a sink holding AppProcess (applog.Sink) gets the process name, otherwise App as before; in-memory log sink only, no file, path or env read registry:App@166,registry:Host@174,whole:Route@161 d3af8b263f021bcba5926116366bf4a4e853a21ef7c14bcaced53dbd75247324
+@legacy d765f7a7dd9ac5f10ac545c84454e8ae9046dc36142c9a3b88e6634613b5fa6b internal/activator/prepare.go ExecBackend.logEmitter legacy accepted-legacy accepted-legacy;rev3=J1;basis=root-route;rev3=census-ruling-rootfs-fleet-followups;basis=takes a process name and returns appLineEmitter(b.Logs, rt, process); the route account, app and host reads moved into appLineEmitter; no file read whole:Route@114 171f5bc4eca79f08dc335fccac8cd11385b72ce27bded922a71e639b8a8a6ce0
+@legacy 4ed1b4930a5a677b33ea8194fba90f4b9e9c56702129a055be0fb584e008e16d internal/activator/rootfsrelease.go Service.releaseAppLog legacy accepted-legacy accepted-legacy;rev3=census-ruling-rootfs-apps-3-release;basis=rootfs Plan 3 Group R, R1 [pf R1.5]: new; the writer a release's output goes through: each line to the instance's own app log (a.Logs.App(account, app, host, line)); reads the route's account, app and host for the log's key; no file read;rev3=census-ruling-rootfs-fleet-followups;basis=returns lineEmitter(appLineEmitter(a.Logs, rt, release.ProcessRelease)); the route reads moved into appLineEmitter; no file read whole:Route@106 20871e7bd6d22cf8a1bf733fe8b8f34e9702b2b2f6d661d1ef8140963518ed70
+internal/activator/prepare.go ExecBackend.prepareKeyedAt legacy accepted-legacy accepted-legacy;rev3=census-ruling-carlos-run;basis=Re-digested at the pre-land merge: the body includes main's own change under census ruling zddr4, with no further change from this branch beyond carrying main's new early return into the six-value signature. the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): body of the frozen prepareAt, which is now its wrapper; it also returns the instance key's layer and reads no env for the cmd role; same reads, same nested launch paths;rev3=census-ruling-wake-latency-2;basis=takes an optional timer and marks its steps with time.Now() (dirs, admin token, instance key, env, control socket, key gate, logs); no read added or moved;rev3=census-ruling-region-ha-p1a;basis=the agent as carlos, run and seed roles only, under a 30 s context (haSecretsBudget): the token producer is ensureAdminTokenFor(hctx, rt, p) (on this nested path the same beneath producer, EnsureAdminTokenBeneath's, plus the HA mint decision inside it); ensureInstanceKeyFor now gets hctx instead of context.Background(), so the key's bucket read is bounded by 30 s as well as configReadTimeout; the env is launchEnvLayer(hctx, rt) (instanceEnvLayer for a non-HA host; for an HA host one capture, published and acknowledged); a test seam (haLaunchHooks.afterGate, nil in production) is called before the producers. The separate haMintGate and haSecretsReady calls are gone (final fix F2). Sites against main: -registry:Host (the rt.Host+".env" argument EnsureAdminTokenBeneath took) and +whole:Route (rt to launchEnvLayer); the cmd role and a non-HA host are unchanged;rev3=census-ruling-rootfs-fleet-followups;basis=names the process for the role log listener: release.ProcessWeb when rt.Rootfs() and the role is run, else none, passed to logEmitter; reads rt.Runtime through Rootfs(); no file, path or env read added or moved file:ReadDir@2929,registry:Host@1770,registry:Host@1982,registry:Host@5787,registry:Host@5985,registry:Host@612,whole:Route@1661,whole:Route@1872,whole:Route@2103,whole:Route@320,whole:Route@4642,whole:Route@5170,whole:Route@5821 0c049e8ff1256f466b0f6e770d65c9e0ba6943f03c377924481e0210c723da30
+internal/activator/prepare.go ExecBackend.prepareWorker legacy accepted-legacy accepted-legacy;rev3=census-ruling-rootfs-apps-3-workers;basis=rootfs Plan 3 Group W, W1: prepare for a worker: the instance's two directories and the worker log socket's, the worker's stale exit records cleared by its name prefix (another worker's and every generation's kept), its log listener bound where root's worker drop-in points StandardOutput=; reads no environment file; binds no control listener; asks no replica gate;rev3=census-ruling-rootfs-fleet-followups;basis=passes the worker name (already checked by release.ValidWorkerName at the top) to logEmitter as the process; no read added or moved file:ReadDir@563,registry:Host@224,registry:Host@440,registry:Host@902,whole:Route@124,whole:Route@809 a22180a3d5c23b92e9c227a45e90e482fc5789baec5345f1151e37773b5941f8
+internal/activator/logsink.go appLineEmitter legacy accepted-legacy accepted-legacy;rev3=census-ruling-rootfs-fleet-followups;basis=new: the app-line emit function for rt: nil for a nil sink; reads the route account (release.RouteAccount), app and host; a sink holding AppProcess (applog.Sink) gets the process name, otherwise App as before; in-memory log sink only, no file, path or env read registry:App@166,registry:Host@174,whole:Route@161 d3af8b263f021bcba5926116366bf4a4e853a21ef7c14bcaced53dbd75247324
+internal/activator/prepare.go ExecBackend.logEmitter legacy accepted-legacy accepted-legacy;rev3=J1;basis=root-route;rev3=census-ruling-rootfs-fleet-followups;basis=takes a process name and returns appLineEmitter(b.Logs, rt, process); the route account, app and host reads moved into appLineEmitter; no file read whole:Route@114 171f5bc4eca79f08dc335fccac8cd11385b72ce27bded922a71e639b8a8a6ce0
+internal/activator/rootfsrelease.go Service.releaseAppLog legacy accepted-legacy accepted-legacy;rev3=census-ruling-rootfs-apps-3-release;basis=rootfs Plan 3 Group R, R1 [pf R1.5]: new; the writer a release's output goes through: each line to the instance's own app log (a.Logs.App(account, app, host, line)); reads the route's account, app and host for the log's key; no file read;rev3=census-ruling-rootfs-fleet-followups;basis=returns lineEmitter(appLineEmitter(a.Logs, rt, release.ProcessRelease)); the route reads moved into appLineEmitter; no file read whole:Route@106 20871e7bd6d22cf8a1bf733fe8b8f34e9702b2b2f6d661d1ef8140963518ed70
+@coverage internal/activator 0debca01a10c2e37b744daed7b60c23788e9dca7d50086cb33eb0bf25e57ad75
+@coverage internal/applog 0f5d06983a3e8b949179ce74443aba0747cdc0a3d730e6189c9cfee4c808f59b
diff --git a/logs_e2e_test.go b/logs_e2e_test.go
index d0939784f..13d0b8352 100644
--- a/logs_e2e_test.go
+++ b/logs_e2e_test.go
@@ -20,65 +20,7 @@ import (
)
func TestE2ELogsThroughConsole(t *testing.T) {
- useTempCredentials(t)
- clearDeploymentEnv(t)
- checkNoRegistry := requireNoRegistryTouch(t)
-
- tmp := t.TempDir()
- relStore := release.NewDirStore(filepath.Join(tmp, "store"))
- seed, pubB64, err := release.GenerateKey()
- if err != nil {
- t.Fatal(err)
- }
- priv, err := release.ParseSigningKey(seed, "e2e")
- if err != nil {
- t.Fatal(err)
- }
- pub, err := release.ParsePublicKey(pubB64, "e2e")
- if err != nil {
- t.Fatal(err)
- }
- cst, err := console.Open(filepath.Join(tmp, "console.db"))
- if err != nil {
- t.Fatal(err)
- }
- t.Cleanup(func() { cst.Close() })
-
- var srv *console.Server
- ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- srv.ServeHTTP(w, r)
- }))
- t.Cleanup(ts.Close)
- srv, err = console.NewServer(console.Config{
- Origin: ts.URL,
- Keymail: "http://keymail.invalid", // never dialled — see e2eDeviceLogin
- Registry: filepath.Join(tmp, "registry.db"),
- Releases: relStore,
- ReleasePub: pub,
- Key: priv,
- AppScheme: "http",
- AppsDomain: "oncarlos.test",
- }, cst)
- if err != nil {
- t.Fatal(err)
- }
-
- const addr = "paul@keymail.dev"
- if err := cst.AddMember(console.OpsAccountID, addr, console.RoleOwner, time.Now()); err != nil {
- t.Fatal(err)
- }
- if _, err := cst.CreateAppIn(console.OpsAccountID, "titogo", addr, time.Now()); err != nil {
- t.Fatal(err)
- }
- token, expiresAt := e2eDeviceLogin(t, ts.URL, cst, addr, "e2e@laptop")
- credFile, err := loadCredentials()
- if err != nil {
- t.Fatal(err)
- }
- credFile.put(credential{Console: ts.URL, Address: addr, Token: token, ExpiresAt: expiresAt})
- if err := credFile.save(); err != nil {
- t.Fatal(err)
- }
+ checkNoRegistry, relStore := startLogsE2E(t)
// A box shipped two chunks: routine output, then a wake failure — the
// #131 case, as the shipping loop would have written it.
@@ -160,3 +102,122 @@ func TestE2ELogsThroughConsole(t *testing.T) {
// a local registry.
checkNoRegistry()
}
+
+// startLogsE2E is a real console.Server over a DirStore, an ops app
+// titogo and a device-flow login for its owner. It returns the
+// no-registry check and the store boxes ship chunks into.
+func startLogsE2E(t *testing.T) (checkNoRegistry func(), relStore *release.DirStore) {
+ t.Helper()
+ useTempCredentials(t)
+ clearDeploymentEnv(t)
+ checkNoRegistry = requireNoRegistryTouch(t)
+
+ tmp := t.TempDir()
+ relStore = release.NewDirStore(filepath.Join(tmp, "store"))
+ seed, pubB64, err := release.GenerateKey()
+ if err != nil {
+ t.Fatal(err)
+ }
+ priv, err := release.ParseSigningKey(seed, "e2e")
+ if err != nil {
+ t.Fatal(err)
+ }
+ pub, err := release.ParsePublicKey(pubB64, "e2e")
+ if err != nil {
+ t.Fatal(err)
+ }
+ cst, err := console.Open(filepath.Join(tmp, "console.db"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { cst.Close() })
+
+ var srv *console.Server
+ ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ srv.ServeHTTP(w, r)
+ }))
+ t.Cleanup(ts.Close)
+ srv, err = console.NewServer(console.Config{
+ Origin: ts.URL,
+ Keymail: "http://keymail.invalid", // never dialled — see e2eDeviceLogin
+ Registry: filepath.Join(tmp, "registry.db"),
+ Releases: relStore,
+ ReleasePub: pub,
+ Key: priv,
+ AppScheme: "http",
+ AppsDomain: "oncarlos.test",
+ }, cst)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ const addr = "paul@keymail.dev"
+ if err := cst.AddMember(console.OpsAccountID, addr, console.RoleOwner, time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := cst.CreateAppIn(console.OpsAccountID, "titogo", addr, time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ token, expiresAt := e2eDeviceLogin(t, ts.URL, cst, addr, "e2e@laptop")
+ credFile, err := loadCredentials()
+ if err != nil {
+ t.Fatal(err)
+ }
+ credFile.put(credential{Console: ts.URL, Address: addr, Token: token, ExpiresAt: expiresAt})
+ if err := credFile.save(); err != nil {
+ t.Fatal(err)
+ }
+
+ return checkNoRegistry, relStore
+}
+
+// A rootfs instance's lines name their process end to end (#366 Task 11
+// follow-up): a real applog.Sink tags them as the activator's capture
+// sites do, the drain is shipped as the agent's logshipFlush writes a
+// chunk, and the member reads them through the console with the real
+// runLogs. --field process=<name> narrows to one process; every line stays
+// on the app stream, never "release" (the ship/promote history's).
+func TestE2ELogsNameTheProcess(t *testing.T) {
+ checkNoRegistry, relStore := startLogsE2E(t)
+
+ const host = "titogo.bab.oncarlos.test"
+ sink := applog.NewSink("box1", time.Now)
+ sink.AppProcess(release.OpsAccount, "titogo", host, release.ProcessWeb, `{"msg":"web says hi","process":"spoof"}`)
+ sink.AppProcess(release.OpsAccount, "titogo", host, "jobs", "worker tick")
+ sink.AppProcess(release.OpsAccount, "titogo", host, release.ProcessRelease, "migrations ran")
+ for k, recs := range sink.Drain() {
+ body, err := applog.EncodeChunk(recs)
+ if err != nil {
+ t.Fatal(err)
+ }
+ key, err := applog.ChunkKey(k.Acct, k.App, recs[0].Box, applog.HourOf(recs[0].TS), recs[0].Seq, len(body))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := relStore.Put(context.Background(), key, body, ""); err != nil {
+ t.Fatal(err)
+ }
+ }
+
+ buf := captureStdout(t)
+ runLogs([]string{"-app", "titogo", "-account", "ops"})
+ out := buf.String()
+ for _, want := range []string{"web says hi process=web", "worker tick process=jobs", "migrations ran process=release"} {
+ if !strings.Contains(out, want) {
+ t.Errorf("logs stdout missing %q:\n%s", want, out)
+ }
+ }
+ if strings.Contains(out, "spoof") || strings.Contains(out, "[release]") || strings.Count(out, "[app]") != 3 {
+ t.Errorf("want three [app] lines and the platform's process names only:\n%s", out)
+ }
+
+ for _, c := range []struct{ process, want string }{{"web", "web says hi"}, {"jobs", "worker tick"}, {"release", "migrations ran"}} {
+ buf.Reset()
+ runLogs([]string{"-app", "titogo", "-account", "ops", "-field", "process=" + c.process})
+ out := buf.String()
+ if !strings.Contains(out, c.want) || strings.Count(out, "[app]") != 1 {
+ t.Errorf("--field process=%s: want %q alone:\n%s", c.process, c.want, out)
+ }
+ }
+ checkNoRegistry()
+}
diff --git a/main.go b/main.go
index cd4d1ecaf..62f138eb2 100644
--- a/main.go
+++ b/main.go
@@ -45,6 +45,10 @@ func main() {
if cmd == "__rootfs-check-probe" {
os.Exit(runRootfsCheckProbe(args))
}
+ // And the container that makes the check's data volume its user's.
+ if cmd == "__rootfs-check-prepare" {
+ os.Exit(runRootfsCheckPrepare(args))
+ }
switch cmd {
// Asking for help is not an error: it prints on stdout and exits 0, so
// `carlos help | less` works. A bare `carlos` still fails (stderr, 2).
diff --git a/ship_check.go b/ship_check.go
index 0cec4f41f..2e3abe4fb 100644
--- a/ship_check.go
+++ b/ship_check.go
@@ -29,6 +29,9 @@ const (
checkHost = "shop.example.com"
workerSettle = 5 * time.Second
checkLogLines = 20
+ // checkPrepareTimeout bounds the prepare container, which changes one
+ // directory's owner and mode, even under emulation.
+ checkPrepareTimeout = 60 * time.Second
)
// The instance's paths in every check container, as a box lays them out.
@@ -95,8 +98,8 @@ type checkProbeResult struct {
Ports []int `json:"ports"`
}
-// runRootfsCheck runs b's image with rt: release, if declared, to its end;
-// then web, probed with the binary at probe; then each worker, after a
+// runRootfsCheck runs b's image with rt: a container that makes the data
+// volume the check user's; release, if declared, to its end; then web, probed with the binary at probe; then each worker, after a
// healthy web. console is never started (spec §5.10). It writes each line
// of its report to out as it goes. Every container, volume and image it
// made is removed before it returns, on every path, and a removal that
@@ -137,7 +140,7 @@ func (c *rootfsCheck) check(ctx context.Context) {
c.say(fmt.Sprintf("the %s process runs %s, which needs a JIT, and this release does not declare one. it passes here but stops at start on a box. ship it with --jit", name, prog))
}
}
- if !c.checkArch(ctx) || !c.makeImageAndVolumes(ctx) {
+ if !c.checkArch(ctx) || !c.makeImageAndVolumes(ctx) || !c.prepareData(ctx) {
return
}
if _, ok := c.b.procs[release.ProcessRelease]; ok && !c.runRelease(ctx) {
@@ -166,25 +169,92 @@ func (c *rootfsCheck) checkArch(ctx context.Context) bool {
}
// makeImageAndVolumes imports the tree and makes the instance's two
-// directories, each a tmpfs volume owned by the check's user. Each name is
-// recorded before the runtime is asked, so a call cut short is cleaned up.
+// directories as volumes. The data volume is a plain local volume, so what
+// release writes there (a migrated CARLOS_DB) is still there for web and
+// the workers, as on a box's disk: Docker and Podman unmount a tmpfs
+// volume, and so empty it, whenever no container holds it. It starts out
+// root's; prepareData gives it to the check's user. The run volume holds
+// only the socket, which web makes afresh, so it stays a tmpfs volume
+// owned by the check's user. Each name is recorded before the runtime is
+// asked, so a call cut short is cleaned up.
func (c *rootfsCheck) makeImageAndVolumes(ctx context.Context) bool {
c.image = c.prefix + ":latest"
if err := c.rt.importTree(ctx, c.b.tree, c.image); err != nil {
return c.runtimeFailed(ctx, "import", err)
}
- for _, v := range []string{c.prefix + "-data", c.prefix + "-run"} {
- c.volumes = append(c.volumes, v)
- _, err := c.rt.run(ctx, nil, "volume", "create", "--label", "carlos-check="+c.id, "--driver", "local",
- "--opt", "type=tmpfs", "--opt", "device=tmpfs",
- "--opt", fmt.Sprintf("o=uid=%d,gid=%d,mode=0700", checkUID, checkUID), v)
- if err != nil {
+ for _, v := range []struct {
+ name string
+ opts []string
+ }{
+ {c.prefix + "-data", nil},
+ {c.prefix + "-run", []string{"--opt", "type=tmpfs", "--opt", "device=tmpfs",
+ "--opt", fmt.Sprintf("o=uid=%d,gid=%d,mode=0700", checkUID, checkUID)}},
+ } {
+ c.volumes = append(c.volumes, v.name)
+ args := append([]string{"volume", "create", "--label", "carlos-check=" + c.id, "--driver", "local"}, v.opts...)
+ if _, err := c.rt.run(ctx, nil, append(args, v.name)...); err != nil {
return c.runtimeFailed(ctx, "volume create", err)
}
}
return true
}
+// prepareData makes the data volume's root the check user's, mode 0700, as
+// a box makes an instance's directory, before any process runs. A
+// container of its own runs the probe binary's __rootfs-check-prepare as
+// root with CAP_CHOWN alone, no new privileges, no network, a read-only
+// root, and nothing mounted but the data volume and the probe; the check
+// waits for it to exit 0. It is recorded like every container, so the
+// cleanup removes it.
+func (c *rootfsCheck) prepareData(ctx context.Context) bool {
+ // A process's container is <prefix>-<name>, and a worker may be named
+ // prepare (release.ValidWorkerName). The helper's "_" is outside that
+ // grammar, and inside the runtimes' container names
+ // ([a-zA-Z0-9][a-zA-Z0-9_.-]*), so the two never meet. Volumes and the
+ // image are named in namespaces of their own.
+ ctr := c.prefix + "_prepare"
+ args := []string{"run", "-d", "--name", ctr,
+ "--read-only", "--network", "none",
+ "--cap-drop", "ALL", "--cap-add", "CHOWN", "--security-opt", "no-new-privileges",
+ "--platform", "linux/arm64", "--user", "0:0",
+ "-v", c.volumeMount(0, checkDataDir),
+ "-v", c.probe + ":" + checkProbeMount + ":ro",
+ "--entrypoint", checkProbeMount,
+ "--label", "carlos-check=" + c.id,
+ c.image,
+ "__rootfs-check-prepare", "--dir", checkDataDir, "--uid", strconv.Itoa(checkUID),
+ }
+ if !c.launch(ctx, ctr, args) {
+ return false
+ }
+ code, _, err := c.waitExit(ctx, ctr, checkPrepareTimeout)
+ if err != nil {
+ return c.runtimeFailed(ctx, "wait", err)
+ }
+ if code == 0 {
+ return true
+ }
+ logs := c.logs(ctx, ctr)
+ if execFormatError(logs...) {
+ return c.fail(checkNoEmulation)
+ }
+ c.runtimeFailed(ctx, "run", fmt.Errorf("__rootfs-check-prepare exited with status %d", code))
+ c.sayLogs(logs)
+ return false
+}
+
+// volumeMount is the -v value that mounts the check's volume i at path,
+// with nocopy, which Docker and Podman both take for a named volume.
+// Without it both fill an empty volume from the image's directory at path
+// each time a container starts, the directory's owner and mode included:
+// an image holding an empty /data/instances/check would hand the prepared
+// data volume back to root when release or web started, and the run
+// volume, a tmpfs volume emptied whenever no container holds it, would be
+// re-owned the same way at every start. Every mount of either says nocopy.
+func (c *rootfsCheck) volumeMount(i int, path string) string {
+ return c.volumes[i] + ":" + path + ":nocopy"
+}
+
// processVars is process name's environment in the check: its own env,
// then --env's values, then the instance's CARLOS_* values (validation keeps CARLOS_ names out of
// a process's env). There is no CARLOS_CONTROL_SOCKET or CARLOS_PURGE:
@@ -225,8 +295,8 @@ func (c *rootfsCheck) runArgs(ctr, name string) []string {
"--memory", mem, "--memory-swap", mem,
"--cap-drop", "ALL", "--security-opt", "no-new-privileges",
"--platform", "linux/arm64", "--user", user,
- "-v", c.volumes[0] + ":" + checkDataDir,
- "-v", c.volumes[1] + ":" + checkRunDir,
+ "-v", c.volumeMount(0, checkDataDir),
+ "-v", c.volumeMount(1, checkRunDir),
"-v", c.probe + ":" + checkProbeMount + ":ro",
}
vars := c.processVars(name)
@@ -242,19 +312,41 @@ func (c *rootfsCheck) runArgs(ctr, name string) []string {
return append(args, p.Command[1:]...)
}
-// start runs process name detached and answers its container. A run the
-// runtime refused is reported: an arm64 program this machine cannot run is
-// RFS-1-C62.
+// start runs process name detached and answers its container.
func (c *rootfsCheck) start(ctx context.Context, name string) (string, bool) {
ctr := c.prefix + "-" + name
+ return ctr, c.launch(ctx, ctr, c.runArgs(ctr, name))
+}
+
+// launch records container ctr, then asks the runtime to run args, which
+// name it. A run the runtime refused is reported: an arm64 program this
+// machine cannot run is RFS-1-C62.
+func (c *rootfsCheck) launch(ctx context.Context, ctr string, args []string) bool {
c.containers = append(c.containers, ctr)
- if _, err := c.rt.run(ctx, nil, c.runArgs(ctr, name)...); err != nil {
+ if _, err := c.rt.run(ctx, nil, args...); err != nil {
if ctx.Err() == nil && execFormatError(err.Error()) {
- return ctr, c.fail(checkNoEmulation)
+ return c.fail(checkNoEmulation)
}
- return ctr, c.runtimeFailed(ctx, "run", err)
+ return c.runtimeFailed(ctx, "run", err)
+ }
+ return true
+}
+
+// waitExit waits up to timeout for ctr to exit and answers its status.
+// timedOut says the wait ran out of time rather than ctx ending.
+func (c *rootfsCheck) waitExit(ctx context.Context, ctr string, timeout time.Duration) (code int, timedOut bool, err error) {
+ wctx, cancel := context.WithTimeout(ctx, timeout)
+ out, err := c.rt.run(wctx, nil, "wait", ctr)
+ timedOut = wctx.Err() != nil && ctx.Err() == nil
+ cancel()
+ if err != nil {
+ return 0, timedOut, err
+ }
+ code, err = strconv.Atoi(lastLine(string(out)))
+ if err != nil {
+ return 0, false, fmt.Errorf("%q is not an exit status", strings.TrimSpace(string(out)))
}
- return ctr, true
+ return code, false, nil
}
// runRelease runs release to its end, under its timeout. A failure stops
@@ -269,20 +361,13 @@ func (c *rootfsCheck) runRelease(ctx context.Context) bool {
if s := c.b.procs[release.ProcessRelease].TimeoutSec; s > 0 {
timeout = time.Duration(s) * time.Second
}
- wctx, cancel := context.WithTimeout(ctx, timeout)
- out, err := c.rt.run(wctx, nil, "wait", ctr)
- timedOut := wctx.Err() != nil
- cancel()
+ code, timedOut, err := c.waitExit(ctx, ctr, timeout)
if err != nil {
- if ctx.Err() == nil && timedOut {
+ if timedOut {
return c.fail(fmt.Sprintf("release did not finish within %s", checkDuration(timeout)))
}
return c.runtimeFailed(ctx, "wait", err)
}
- code, err := strconv.Atoi(lastLine(string(out)))
- if err != nil {
- return c.runtimeFailed(ctx, "wait", fmt.Errorf("%q is not an exit status", strings.TrimSpace(string(out))))
- }
if code == 0 {
c.say(fmt.Sprintf("release finished in %s", checkDuration(time.Since(began))))
return true
diff --git a/ship_check_prepare_test.go b/ship_check_prepare_test.go
new file mode 100644
index 000000000..d0cbc331f
--- /dev/null
+++ b/ship_check_prepare_test.go
@@ -0,0 +1,210 @@
+//go:build unix
+
+package main
+
+import (
+ "errors"
+ "fmt"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "slices"
+ "strconv"
+ "strings"
+ "syscall"
+ "testing"
+)
+
+// __rootfs-check-prepare makes one directory the given user's, mode 0700:
+// that directory alone, never what is in it, and never through a symlink.
+// The test chowns to its own user and group, which needs no privilege.
+func TestPrepareCheckDir(t *testing.T) {
+ uid, gid := os.Getuid(), os.Getgid()
+ owner := func(t *testing.T, p string) (os.FileMode, int, int) {
+ t.Helper()
+ fi, err := os.Lstat(p)
+ if err != nil {
+ t.Fatal(err)
+ }
+ st := fi.Sys().(*syscall.Stat_t)
+ return fi.Mode().Perm(), int(st.Uid), int(st.Gid)
+ }
+
+ dir := filepath.Join(t.TempDir(), "check")
+ if err := os.Mkdir(dir, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ inside := filepath.Join(dir, "shop.db")
+ if err := os.WriteFile(inside, nil, 0o644); err != nil {
+ t.Fatal(err)
+ }
+ if err := prepareCheckDir(dir, uid, gid); err != nil {
+ t.Fatalf("prepareCheckDir: %v", err)
+ }
+ if mode, u, g := owner(t, dir); mode != 0o700 || u != uid || g != gid {
+ t.Errorf("dir is %v %d:%d, want 0700 %d:%d", mode, u, g, uid, gid)
+ }
+ if mode, _, _ := owner(t, inside); mode != 0o644 {
+ t.Errorf("a file inside became %v: prepare recursed", mode)
+ }
+
+ // A symlink is refused, and its target is left as it was.
+ target := filepath.Join(t.TempDir(), "elsewhere")
+ if err := os.Mkdir(target, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ link := filepath.Join(t.TempDir(), "check")
+ if err := os.Symlink(target, link); err != nil {
+ t.Fatal(err)
+ }
+ if err := prepareCheckDir(link, uid, gid); err == nil {
+ t.Error("prepareCheckDir followed a symlink")
+ }
+ if mode, _, _ := owner(t, target); mode != 0o755 {
+ t.Errorf("the symlink's target became %v", mode)
+ }
+
+ // A file, and a path that is not there, are refused.
+ if err := prepareCheckDir(inside, uid, gid); err == nil {
+ t.Error("prepareCheckDir took a file")
+ }
+ if mode, _, _ := owner(t, inside); mode != 0o644 {
+ t.Errorf("a refused file became %v", mode)
+ }
+ if err := prepareCheckDir(filepath.Join(dir, "missing"), uid, gid); err == nil {
+ t.Error("prepareCheckDir took a missing path")
+ }
+}
+
+// prepareCheckDir sets the mode, then the owner, with exactly the
+// arguments the check needs. The order is the property: in the prepare
+// container root holds CAP_CHOWN alone, so once the directory is 65534's it
+// could no longer chmod it (that needs CAP_FOWNER). CI has no root to give
+// a directory away, so this pins the calls through the checkChmod and
+// checkLchown seams; the capabilities themselves are witnessed by the
+// rootful Podman run on a dev box (rootfs Plan 4 Task 11, 2026-10-29).
+func TestPrepareCheckDirSetsModeThenOwner(t *testing.T) {
+ var calls []string
+ oldChmod, oldLchown := checkChmod, checkLchown
+ t.Cleanup(func() { checkChmod, checkLchown = oldChmod, oldLchown })
+ checkChmod = func(name string, mode os.FileMode) error {
+ calls = append(calls, fmt.Sprintf("chmod %s %#o", name, mode))
+ return nil
+ }
+ checkLchown = func(name string, uid, gid int) error {
+ calls = append(calls, fmt.Sprintf("lchown %s %d:%d", name, uid, gid))
+ return nil
+ }
+
+ dir := filepath.Join(t.TempDir(), "check")
+ if err := os.Mkdir(dir, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ if err := prepareCheckDir(dir, 65534, 65534); err != nil {
+ t.Fatalf("prepareCheckDir: %v", err)
+ }
+ want := []string{"chmod " + dir + " 0700", "lchown " + dir + " 65534:65534"}
+ if !slices.Equal(calls, want) {
+ t.Errorf("calls %q, want %q", calls, want)
+ }
+
+ // The verb gives --uid as the group too.
+ calls = nil
+ if got := runRootfsCheckPrepare([]string{"--dir", dir, "--uid", "65534"}); got != 0 || !slices.Equal(calls, want) {
+ t.Errorf("the verb: exit %d, calls %q, want 0 and %q", got, calls, want)
+ }
+
+ // A refused path is never changed; a chmod that fails stops the chown.
+ link := filepath.Join(t.TempDir(), "link")
+ if err := os.Symlink(dir, link); err != nil {
+ t.Fatal(err)
+ }
+ calls = nil
+ if err := prepareCheckDir(link, 65534, 65534); err == nil || len(calls) != 0 {
+ t.Errorf("a symlink: %v, calls %q", err, calls)
+ }
+ checkChmod = func(string, os.FileMode) error { return errors.New("operation not permitted") }
+ calls = nil
+ if err := prepareCheckDir(dir, 65534, 65534); err == nil || len(calls) != 0 {
+ t.Errorf("a failed chmod: %v, calls %q", err, calls)
+ }
+}
+
+// The verb's exit statuses: 0 done, 1 refused, 2 a flag error.
+func TestRunRootfsCheckPrepareExits(t *testing.T) {
+ dir := filepath.Join(t.TempDir(), "check")
+ if err := os.Mkdir(dir, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ link := filepath.Join(t.TempDir(), "link")
+ if err := os.Symlink(dir, link); err != nil {
+ t.Fatal(err)
+ }
+ // The verb gives --uid as both user and group, so run it with the group
+ // it would set only when this user's group has the same number.
+ if os.Getuid() == os.Getgid() {
+ if got := runRootfsCheckPrepare([]string{"--dir", dir, "--uid", strconv.Itoa(os.Getuid())}); got != 0 {
+ t.Errorf("a directory: exit %d, want 0", got)
+ }
+ }
+ if got := runRootfsCheckPrepare([]string{"--dir", link, "--uid", strconv.Itoa(os.Getuid())}); got != 1 {
+ t.Errorf("a symlink: exit %d, want 1", got)
+ }
+ for _, args := range [][]string{
+ nil,
+ {"--uid", "65534"},
+ {"--dir", dir},
+ {"--dir", dir, "--uid", "-1"},
+ {"--dir", dir, "--uid", "x"},
+ {"--dir", dir, "--uid", "65534", "extra"},
+ {"--nope"},
+ } {
+ if got := runRootfsCheckPrepare(args); got != 2 {
+ t.Errorf("%q: exit %d, want 2", args, got)
+ }
+ }
+}
+
+// The binary dispatches the verb before its command switch, as it does
+// __rootfs-check-probe: the prepare container runs it by that name.
+func TestRootfsCheckPrepareThroughTheBinary(t *testing.T) {
+ if testing.Short() {
+ t.Skip("runs the carlos binary")
+ }
+ if os.Getuid() != os.Getgid() {
+ t.Skip("the verb sets --uid as the group too, which this user may not")
+ }
+ bin := buildCarlos(t)
+ dir := filepath.Join(t.TempDir(), "check")
+ if err := os.Mkdir(dir, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ link := filepath.Join(t.TempDir(), "link")
+ if err := os.Symlink(dir, link); err != nil {
+ t.Fatal(err)
+ }
+ run := func(args ...string) (int, string) {
+ cmd := exec.Command(bin, append([]string{"__rootfs-check-prepare"}, args...)...)
+ cmd.Env = carlosTestEnv(t)
+ cmd.Dir = t.TempDir()
+ out, err := cmd.CombinedOutput()
+ var ee *exec.ExitError
+ if errors.As(err, &ee) {
+ return ee.ExitCode(), string(out)
+ }
+ if err != nil {
+ t.Fatal(err)
+ }
+ return 0, string(out)
+ }
+ uid := strconv.Itoa(os.Getuid())
+ if code, out := run("--dir", link, "--uid", uid); code != 1 || !strings.Contains(out, "is not a directory") {
+ t.Errorf("a symlink: exit %d, %q; want 1 and the reason", code, out)
+ }
+ if code, out := run("--dir", dir, "--uid", uid); code != 0 {
+ t.Fatalf("a directory: exit %d, %q", code, out)
+ }
+ if fi, err := os.Lstat(dir); err != nil || fi.Mode().Perm() != 0o700 {
+ t.Errorf("after the verb the directory is %v (%v), want 0700", fi.Mode().Perm(), err)
+ }
+}
diff --git a/ship_check_probe.go b/ship_check_probe.go
index 0be29f778..96184ff4c 100644
--- a/ship_check_probe.go
+++ b/ship_check_probe.go
@@ -100,6 +100,53 @@ func runRootfsCheckProbe(args []string) int {
}
}
+// runRootfsCheckPrepare is __rootfs-check-prepare, run in the check's
+// prepare container as root with CAP_CHOWN alone: it makes the directory at
+// --dir mode 0700 and owned by --uid, as user and group (prepareCheckDir).
+// Exit 0 when done, 1 when refused or failed (the reason on stderr, which
+// the check shows as the container's last lines), 2 on a flag error.
+func runRootfsCheckPrepare(args []string) int {
+ fs := flag.NewFlagSet("__rootfs-check-prepare", flag.ContinueOnError)
+ fs.SetOutput(io.Discard)
+ dir := fs.String("dir", "", "the directory to prepare")
+ uid := fs.Int("uid", -1, "its owner, as user and group")
+ if err := fs.Parse(args); err != nil || *dir == "" || *uid < 0 || fs.NArg() > 0 {
+ return 2
+ }
+ if err := prepareCheckDir(*dir, *uid, *uid); err != nil {
+ fmt.Fprintln(os.Stderr, err)
+ return 1
+ }
+ return 0
+}
+
+// checkChmod and checkLchown are prepareCheckDir's two changes. Vars so a
+// test can pin their order and arguments: CI has no root to give a
+// directory away. Production never changes them.
+var (
+ checkChmod = os.Chmod
+ checkLchown = os.Lchown
+)
+
+// prepareCheckDir makes dir mode 0700 and owned by uid:gid: dir alone,
+// never what is in it, and never through a symlink, which Lstat refuses
+// with anything else that is not a directory. The mode goes first: once
+// the directory is another user's, root without CAP_FOWNER could no longer
+// change it.
+func prepareCheckDir(dir string, uid, gid int) error {
+ fi, err := os.Lstat(dir)
+ if err != nil {
+ return err
+ }
+ if !fi.IsDir() {
+ return fmt.Errorf("%s is not a directory", dir)
+ }
+ if err := checkChmod(dir, 0o700); err != nil {
+ return err
+ }
+ return checkLchown(dir, uid, gid)
+}
+
// checkProbeGet asks GET / once, for the check's host, and answers the
// status.
func checkProbeGet(ctx context.Context, client *http.Client) (int, error) {
diff --git a/ship_check_test.go b/ship_check_test.go
index 95cf367a0..cd59958b2 100644
--- a/ship_check_test.go
+++ b/ship_check_test.go
@@ -27,7 +27,9 @@ import (
// objects the check made, which must end empty.
// checkName is the shape of every name the check gives the runtime.
-var checkName = regexp.MustCompile(`^carlos-check-[0-9a-f]{8}(-[a-z][a-z0-9-]*|:latest)$`)
+// A process's container is <prefix>-<process>; the check's own helper is
+// <prefix>_<helper>, a form no process name can take.
+var checkName = regexp.MustCompile(`^carlos-check-[0-9a-f]{8}(-[a-z][a-z0-9-]*|_[a-z]+|:latest)$`)
type fakeCheck struct {
t *testing.T
@@ -39,8 +41,9 @@ type fakeCheck struct {
cleaning bool
arch string
- waitOut string
- waitHang bool
+ waitOut string // every wait's answer, unless waitBy has the process
+ waitBy map[string]string // wait's answer, by process
+ waitHang string // the process whose wait never returns
probeOut string
probeErr error
runErr map[string]error // by process
@@ -60,6 +63,7 @@ func newFakeCheck(t *testing.T) *fakeCheck {
t: t, made: map[string]bool{}, live: map[string]bool{},
arch: "aarch64", waitOut: "0\n", probeOut: `{"status":200,"after_ms":42}` + "\n",
runErr: map[string]error{}, state: map[string]string{}, logs: map[string]string{},
+ waitBy: map[string]string{},
failAt: -1, cancelAt: -1, out: &bytes.Buffer{},
removeErr: map[string]error{},
}
@@ -67,9 +71,10 @@ func newFakeCheck(t *testing.T) *fakeCheck {
func (f *fakeCheck) rt() containerRuntime { return containerRuntime{name: "docker", run: f.run} }
-// procOf is the process a container is named for.
+// procOf is the process a container is named for, or "_" and the helper's
+// name for one of the check's own (<prefix>_prepare is "_prepare").
func procOf(ctr string) string {
- return strings.TrimPrefix(ctr, ctr[:len("carlos-check-")+9])
+ return strings.TrimPrefix(ctr[len("carlos-check-")+8:], "-")
}
func flagValue(args []string, flag string) string {
@@ -129,9 +134,14 @@ func (f *fakeCheck) run(ctx context.Context, stdin io.Reader, args ...string) ([
makes = "container:" + ctr
}
if makes != "" {
- if name := makes[strings.IndexByte(makes, ':')+1:]; !checkName.MatchString(name) {
+ name := makes[strings.IndexByte(makes, ':')+1:]
+ if !checkName.MatchString(name) {
f.t.Errorf("%v names %q", args, name)
}
+ // Docker and Podman refuse a second container by a name in use.
+ if args[0] == "run" && f.made[makes] {
+ return nil, fmt.Errorf(`Error: creating container storage: the container name %q is already in use`, name)
+ }
f.made[makes] = true
}
if args[0] == "import" {
@@ -160,10 +170,14 @@ func (f *fakeCheck) run(ctx context.Context, stdin io.Reader, args ...string) ([
case "run":
return []byte("0123abcd\n"), f.runErr[procOf(flagValue(args, "--name"))]
case "wait":
- if f.waitHang {
+ proc := procOf(last)
+ if f.waitHang == proc {
<-ctx.Done()
return nil, ctx.Err()
}
+ if out, ok := f.waitBy[proc]; ok {
+ return []byte(out), nil
+ }
return []byte(f.waitOut), nil
case "exec":
return []byte(f.probeOut), f.probeErr
@@ -295,8 +309,9 @@ func TestRootfsCheckHappyPath(t *testing.T) {
want := []string{
"info", "import", "volume create data", "volume create run",
+ "run _prepare", "wait _prepare",
"run release", "wait release", "run web", "exec web", "run jobs", "inspect jobs",
- "rm -f release", "rm -f web", "rm -f jobs", "volume rm data", "volume rm run", "rmi",
+ "rm -f _prepare", "rm -f release", "rm -f web", "rm -f jobs", "volume rm data", "volume rm run", "rmi",
}
if got := f.summary(); !slices.Equal(got, want) {
t.Errorf("calls:\n got %q\nwant %q", got, want)
@@ -401,8 +416,8 @@ func TestRootfsCheckRunArgs(t *testing.T) {
}
}
wantMounts := []string{
- prefix + "-data:/data/instances/check",
- prefix + "-run:/run/carlos/instances/check",
+ prefix + "-data:/data/instances/check:nocopy",
+ prefix + "-run:/run/carlos/instances/check:nocopy",
"/probe/carlos:/opt/carlos/carlos:ro",
}
if !slices.Equal(mounts, wantMounts) {
@@ -457,12 +472,30 @@ func TestRootfsCheckRunArgs(t *testing.T) {
if want := []string{"exec", name, "/opt/carlos/carlos", "__rootfs-check-probe", "--socket", "/run/carlos/instances/check/app.sock", "--timeout", "120s"}; !slices.Equal(exec, want) {
t.Errorf("exec = %q, want %q", exec, want)
}
- // Volumes are tmpfs, owned by the check's user.
- if want := []string{"volume", "create", "--label", "carlos-check=" + id, "--driver", "local", "--opt", "type=tmpfs", "--opt", "device=tmpfs", "--opt", "o=uid=65534,gid=65534,mode=0700", prefix + "-data"}; !slices.Equal(f.calls[2], want) {
- t.Errorf("volume create = %q, want %q", f.calls[2], want)
+ // The data volume is a plain local volume, so what release writes is
+ // still there for web, as on a box's disk: a tmpfs volume is emptied
+ // whenever no container holds it. The run volume, the socket's, is
+ // tmpfs, owned by the check's user.
+ creates := map[string][]string{}
+ for _, c := range f.calls {
+ if c[0] == "volume" && c[1] == "create" {
+ creates[procOf(c[len(c)-1])] = c
+ }
+ }
+ if want := []string{"volume", "create", "--label", "carlos-check=" + id, "--driver", "local", prefix + "-data"}; !slices.Equal(creates["data"], want) {
+ t.Errorf("data volume create = %q, want %q", creates["data"], want)
}
- if want := []string{"inspect", "--format", "{{json .State}}", prefix + "-jobs"}; !slices.Equal(f.calls[9], want) {
- t.Errorf("inspect = %q, want %q", f.calls[9], want)
+ if want := []string{"volume", "create", "--label", "carlos-check=" + id, "--driver", "local", "--opt", "type=tmpfs", "--opt", "device=tmpfs", "--opt", "o=uid=65534,gid=65534,mode=0700", prefix + "-run"}; !slices.Equal(creates["run"], want) {
+ t.Errorf("run volume create = %q, want %q", creates["run"], want)
+ }
+ var inspect []string
+ for _, c := range f.calls {
+ if c[0] == "inspect" {
+ inspect = c
+ }
+ }
+ if want := []string{"inspect", "--format", "{{json .State}}", prefix + "-jobs"}; !slices.Equal(inspect, want) {
+ t.Errorf("inspect = %q, want %q", inspect, want)
}
}
@@ -535,7 +568,7 @@ func TestRootfsCheckReleaseFailureStopsTheCheck(t *testing.T) {
noSettle(t)
t.Run("an exit", func(t *testing.T) {
f := newFakeCheck(t)
- f.waitOut = "3\n"
+ f.waitBy["release"] = "3\n"
f.logs["release"] = "migrating\nno such table: orders\n"
r := runRootfsCheck(context.Background(), f.rt(), shopBuild(t, shopProcs()), "/probe/carlos", f.out)
want := []string{"release exited with status 3. its last lines:", " migrating", " no such table: orders", checkC75}
@@ -549,7 +582,7 @@ func TestRootfsCheckReleaseFailureStopsTheCheck(t *testing.T) {
})
t.Run("a timeout", func(t *testing.T) {
f := newFakeCheck(t)
- f.waitHang = true
+ f.waitHang = release.ProcessRelease
procs := shopProcs()
procs[release.ProcessRelease] = release.Process{Command: []string{"/srv/migrate"}, TimeoutSec: 1}
r := runRootfsCheck(context.Background(), f.rt(), shopBuild(t, procs), "/probe/carlos", f.out)
@@ -564,6 +597,175 @@ func TestRootfsCheckReleaseFailureStopsTheCheck(t *testing.T) {
})
}
+// The data volume is a new local volume, so root's: before any process
+// runs, one container of its own makes it the check user's, mode 0700, as
+// root with CAP_CHOWN alone, no network, and only that volume and the
+// probe binary mounted.
+func TestRootfsCheckPreparesTheDataVolume(t *testing.T) {
+ noSettle(t)
+ for _, c := range []struct {
+ name string
+ procs map[string]release.Process
+ first string // the first process after prepare
+ }{
+ {"with release", shopProcs(), "run release"},
+ {"web alone", map[string]release.Process{release.ProcessWeb: shopProcs()[release.ProcessWeb]}, "run web"},
+ } {
+ t.Run(c.name, func(t *testing.T) {
+ f := newFakeCheck(t)
+ r := runRootfsCheck(context.Background(), f.rt(), shopBuild(t, c.procs), "/probe/carlos", f.out)
+ if r.failed {
+ t.Fatalf("report = %q", r.lines)
+ }
+ sum := f.summary()
+ at := slices.Index(sum, "run _prepare")
+ if at < 0 || at+2 >= len(sum) || sum[at+1] != "wait _prepare" || sum[at+2] != c.first {
+ t.Fatalf("calls %q: want run _prepare, wait _prepare, then %s", sum, c.first)
+ }
+ if create := slices.Index(sum, "volume create data"); create < 0 || create > at {
+ t.Errorf("calls %q: prepare before the data volume exists", sum)
+ }
+ prep := f.runOf("_prepare")
+ name := flagValue(prep, "--name")
+ prefix := strings.TrimSuffix(name, "_prepare")
+ id := strings.TrimPrefix(prefix, "carlos-check-")
+ want := []string{"run", "-d", "--name", name,
+ "--read-only", "--network", "none",
+ "--cap-drop", "ALL", "--cap-add", "CHOWN", "--security-opt", "no-new-privileges",
+ "--platform", "linux/arm64", "--user", "0:0",
+ "-v", prefix + "-data:/data/instances/check:nocopy",
+ "-v", "/probe/carlos:/opt/carlos/carlos:ro",
+ "--entrypoint", "/opt/carlos/carlos",
+ "--label", "carlos-check=" + id,
+ prefix + ":latest",
+ "__rootfs-check-prepare", "--dir", "/data/instances/check", "--uid", "65534",
+ }
+ if !slices.Equal(prep, want) {
+ t.Errorf("prepare's argv\n got %q\nwant %q", prep, want)
+ }
+ var caps []string
+ for i, a := range prep {
+ if a == "--cap-add" {
+ caps = append(caps, prep[i+1])
+ }
+ }
+ if !slices.Equal(caps, []string{"CHOWN"}) {
+ t.Errorf("prepare adds %q, want CHOWN alone", caps)
+ }
+ if !slices.Contains(sum, "rm -f _prepare") {
+ t.Errorf("calls %q: the prepare container is never removed", sum)
+ }
+ f.checkLeftNothing(t)
+ })
+ }
+}
+
+// The helper's container is named outside the process names' grammar, so a
+// release may declare a worker named prepare, and it runs as any worker.
+func TestRootfsCheckWorkerNamedLikeTheHelper(t *testing.T) {
+ noSettle(t)
+ if !release.ValidWorkerName("prepare") {
+ t.Fatal("prepare is no longer a valid worker name; pick another of the helper's names")
+ }
+ f := newFakeCheck(t)
+ procs := shopProcs()
+ procs["prepare"] = release.Process{Command: []string{"/srv/jobs", "prepare"}}
+ r := runRootfsCheck(context.Background(), f.rt(), shopBuild(t, procs), "/probe/carlos", f.out)
+ if r.failed {
+ t.Fatalf("report = %q", r.lines)
+ }
+ if !slices.Contains(r.lines, "prepare is still running after 5.0 s") {
+ t.Errorf("report = %q, want the prepare worker running", r.lines)
+ }
+ if w := f.runOf("prepare"); w == nil || flagValue(w, "--entrypoint") != "/srv/jobs" {
+ t.Errorf("the prepare worker ran as %q", w)
+ }
+ if h := f.runOf("_prepare"); h == nil || flagValue(h, "--entrypoint") != "/opt/carlos/carlos" {
+ t.Errorf("the helper ran as %q", h)
+ }
+ f.checkLeftNothing(t)
+}
+
+// Docker and Podman fill an empty named volume from the image's directory
+// at the mount point each time a container starts, owner and mode
+// included. The data volume stays empty after prepare, so an image with an
+// empty /data/instances/check would hand it back to root at release's or
+// web's start; the run volume, tmpfs, is empty at every start. So every
+// mount of either volume, in every container the check runs, says nocopy.
+func TestRootfsCheckVolumesNeverCopyUp(t *testing.T) {
+ noSettle(t)
+ f := newFakeCheck(t)
+ if r := runRootfsCheck(context.Background(), f.rt(), shopBuild(t, shopProcs()), "/probe/carlos", f.out); r.failed {
+ t.Fatalf("report = %q", r.lines)
+ }
+ runs := 0
+ for _, c := range f.calls {
+ if c[0] != "run" {
+ continue
+ }
+ runs++
+ name := flagValue(c, "--name")
+ prefix := name[:len("carlos-check-")+8]
+ var vols []string
+ for i, a := range c {
+ if a == "-v" && strings.HasPrefix(c[i+1], prefix+"-") {
+ vols = append(vols, c[i+1])
+ }
+ }
+ want := []string{prefix + "-data:/data/instances/check:nocopy", prefix + "-run:/run/carlos/instances/check:nocopy"}
+ if procOf(name) == "_prepare" {
+ want = want[:1]
+ }
+ if !slices.Equal(vols, want) {
+ t.Errorf("%s mounts %q, want %q", procOf(name), vols, want)
+ }
+ }
+ if runs != 4 {
+ t.Errorf("%d runs, want prepare, release, web and jobs", runs)
+ }
+}
+
+// A prepare that does not exit 0 fails the check before any process runs,
+// and the check still removes everything it made.
+func TestRootfsCheckPrepareFailureStopsTheCheck(t *testing.T) {
+ noSettle(t)
+ for _, c := range []struct {
+ name string
+ setup func(f *fakeCheck)
+ want []string
+ }{
+ {"an exit", func(f *fakeCheck) {
+ f.waitBy["_prepare"] = "1\n"
+ f.logs["_prepare"] = "chown /data/instances/check: operation not permitted\n"
+ }, []string{"docker run: __rootfs-check-prepare exited with status 1", " chown /data/instances/check: operation not permitted", checkC75}},
+ {"an amd64 probe", func(f *fakeCheck) {
+ f.waitBy["_prepare"] = "255\n"
+ f.logs["_prepare"] = `exec /opt/carlos/carlos: exec format error` + "\n"
+ }, []string{checkNoEmulation, checkC75}},
+ {"not an exit status", func(f *fakeCheck) {
+ f.waitBy["_prepare"] = "gone\n"
+ }, []string{`docker wait: "gone" is not an exit status`, checkC75}},
+ } {
+ t.Run(c.name, func(t *testing.T) {
+ f := newFakeCheck(t)
+ c.setup(f)
+ r := runRootfsCheck(context.Background(), f.rt(), shopBuild(t, shopProcs()), "/probe/carlos", f.out)
+ if !r.failed || !slices.Equal(r.lines[1:], c.want) {
+ t.Errorf("report = %q (failed %v), want C60 then %q", r.lines, r.failed, c.want)
+ }
+ for _, s := range f.summary() {
+ if s == "run release" || s == "run web" || s == "run jobs" {
+ t.Errorf("%q after prepare failed", s)
+ }
+ }
+ if !slices.Contains(f.summary(), "rm -f _prepare") {
+ t.Errorf("calls %q: the prepare container is never removed", f.summary())
+ }
+ f.checkLeftNothing(t)
+ })
+ }
+}
+
func TestRootfsCheckWorkerThatExits(t *testing.T) {
noSettle(t)
f := newFakeCheck(t)
@@ -787,6 +989,7 @@ run) env | LC_ALL=C sort > "$work/env-run"
done
find "$TMPDIR" -name '*.env' >> "$log" ;;
exec) echo "$FAKE_PROBE"; exit "$FAKE_PROBE_EXIT" ;;
+wait) echo 0 ;;
inspect) echo '{"Running":true}' ;;
esac
exit 0
@@ -833,7 +1036,8 @@ exit 0
}
log, _ := os.ReadFile(logPath)
for _, want := range []string{"rm -f carlos-check-", "volume rm carlos-check-", "rmi carlos-check-",
- " -e HTTP_PROXY=http://proxy.example.com:3128 ", " -e docker_host=tcp://example.com:2375 "} {
+ " -e HTTP_PROXY=http://proxy.example.com:3128 ", " -e docker_host=tcp://example.com:2375 ",
+ " --cap-add CHOWN ", " __rootfs-check-prepare --dir /data/instances/check --uid 65534\n"} {
if !strings.Contains(string(log), want) {
t.Errorf("the runtime never saw %q:\n%s", want, log)
}
@@ -947,8 +1151,8 @@ func TestShipCheckWithoutEnvUnchanged(t *testing.T) {
"--memory", "1073741824", "--memory-swap", "1073741824",
"--cap-drop", "ALL", "--security-opt", "no-new-privileges",
"--platform", "linux/arm64", "--user", "65534:65534",
- "-v", prefix + "-data:/data/instances/check",
- "-v", prefix + "-run:/run/carlos/instances/check",
+ "-v", prefix + "-data:/data/instances/check:nocopy",
+ "-v", prefix + "-run:/run/carlos/instances/check:nocopy",
"-v", "/probe/carlos:/opt/carlos/carlos:ro",
"-e", "A_FIRST=1",
"-e", "CARLOS_DB=/data/instances/check/shop.example.com.db",
@@ -1148,6 +1352,7 @@ run) env | LC_ALL=C sort > "$work/env-run"
prev=$a
done ;;
exec) echo '{"status":200,"after_ms":7}' ;;
+wait) echo 0 ;;
inspect) echo '{"Running":true}' ;;
esac
exit 0
diff --git a/ship_rootfs_unix_test.go b/ship_rootfs_unix_test.go
index f85f9197b..18d1ad00a 100644
--- a/ship_rootfs_unix_test.go
+++ b/ship_rootfs_unix_test.go
@@ -111,6 +111,7 @@ func TestShipRootfsCheckCleansUpOnInterrupt(t *testing.T) {
case "$1" in
info) echo aarch64 ;;
import) cat > /dev/null ;;
+wait) echo 0 ;;
exec) : > "$FAKE_READY"; exec sleep 60 ;;
esac
exit 0