carlos / platform Public

feat: expose replica health and command targeting

Stateless replicas Plan 4, Task 3 as trimmed by R17: the live copy view
only. Command targeting (--box, signed target grants, per-box logs and
metrics, run/session record writes) is deferred; this commit pins that a
run and a TTY already start exactly once with two assigned boxes.

- replicaViews joins the hub's live copy table, read from the agent's
  private snapshot socket, to the records by account, app, host,
  lifetime, fleet, box and assignment revision. No reading means unknown,
  never healthy; a slot no box holds is a missing copy with no label.
- Access decision (D6): the socket keeps its 0700/0600 modes. The console
  runs as the agent's user and checks directory and socket ownership and
  SO_PEERCRED before trusting a byte; any other uid reads unknown.
- The list door carries copies and desired_copies on the one host object,
  and a replicated record's health word comes from the live view only.
- carlos instances list prints a second table, one row per copy (box,
  build, state, health, workers). copies=1 output is unchanged.
- The app overview shows "N of M copies running": desired minus missing
  or unhealthy copies. A down or missing copy needs attention.
- F2: carlos restart --app, --environment and the app page's restart
  refuse while an app has more than one copy, since every box would cycle
  its copy on the same serial move.
- Docs: per-copy rows, per-copy page cache and purges, the restart rule.
- Copy rows SR-4-C47..C53 provisional, pending Paul's copy review.
- Census: root-read proposal stateless-replicas-4-task3 (envelope only),
  record-write layer for the two re-digested list/restart handlers.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev fb1d0904382dfae18a4b8db940d878fa096a66cd parent 99b1a53
23 files changed, +1,258 −4
  • apimode.go +9 −0
  • docs/site/cli.md +6 −0
  • docs/superpowers/notes/census-proposal-stateless-replicas-4-task3.md +11 −0
  • docs/superpowers/plans/2026-11-01-stateless-replicas-copy.md +7 −0
  • instances_cli.go +1 −0
  • instances_copies.go +105 −0
  • instances_copies_test.go +102 −0
  • internal/console/apicli.go +4 −0
  • internal/console/apiinstances.go +17 −1
  • internal/console/apirestartscope.go +9 −0
  • internal/console/browserrestart.go +9 −0
  • internal/console/overview.go +27 −1
  • internal/console/replicaview.go +246 −0
  • internal/console/replicaview_linux.go +134 −0
  • internal/console/replicaview_linux_test.go +75 −0
  • internal/console/replicaview_other.go +15 −0
  • internal/console/replicaview_test.go +423 −0
  • internal/console/server.go +12 −1
  • internal/console/templates/app_overview.html +4 −0
  • internal/provision/plan9_b8_census_test.go +1 −1
  • internal/provision/stateless_replicas_4_task3_census_test.go +37 −0
  • internal/provision/testdata/plan14-root-reads-chain.tsv +1 −0
  • internal/provision/testdata/plan14-root-reads-stateless-replicas-4-task3.tsv +3 −0

CI failed — run details

Intent

Human

<task-notification> <task-id>a4621592a91bafe83</task-id> <tool-use-id>toolu_01RKzL7GhiJfkhbwgZe6SFAU</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/72128d15-58b8-452f-9f7e-8e864e8854d2/tasks/a4621592a91bafe83.output</output-file> <status>completed</status> <summary>Agent "Implement Plan 4 Task 2" finished</summary> <note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note> <result>- **Status:** DONE_WITH_CONCERNS - **Commit:** 99b1a539 fix: bound replica worker proof; baseline before adopt on retry, on top of 6bae56b5. Local only; the tree is clean. - **Tests:** RED against 6bae56b5's code: all 4 new cases fail (no shims were needed this round). GREEN on all Task 2 tests across six packages (replicas, provision, rollout, activator, host, console), plus the targeted activator and host runs, census, HA guards, copy checks, the darwin, windows and linux/arm64 builds, vet and gofmt. All 3 mutations were killed. - **Worker proof timing:** the step now stays open with no answer while a worker start is in flight. A start refused by a gate is still waiting, not failed. A worker that never started is judged only after residentPoll + workerStartBound from its registration (a new registration timestamp). A crash or restart still answers "switched, workers failed" at once. - **Requested retry:** a box now checks its own baseline before the adopt path, so a completed box under a requested retry restarts on the target with no release and no refusal. The escrow recovery step for the passed target still runs. - **Concerns:** - Task 2 now has 21 mutations, against the plan's 10. - A worker that never starts holds the step open for up to about 32 s before the deploy halts. - **Census:** proposal stateless-replicas-4-task2-fix3 is written (seal bd253671…). Nothing is posted to #280. - **Cleanup:** my scratch and `/tmp/g` leftovers are deleted. - **Report:** /home/paulca/amadan.net/carlos/platform/.claude/worktrees/stateless-replicas-4/.superpowers/sdd/2026-11-01-stateless-replicas-4-deploy-and-drill/task-2-report.md (the "Fix round 3" section)</result> <usage><subagent_tokens>728821</subagent_tokens><tool_uses>22</tool_uses><duration_ms>775828</duration_ms></usage> </task-notification>

Human

<task-notification> <task-id>bwv91cr83</task-id> <tool-use-id>toolu_014DHFGb8oqgCx8s8ATqQ49P</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/72128d15-58b8-452f-9f7e-8e864e8854d2/tasks/bwv91cr83.output</output-file> <status>completed</status> <summary>Background command "Astra final re-review of Task 2" completed (exit code 0)</summary> </task-notification>

Attributed to this commit: 20.7 g CO₂e (2,571,389 tokens). This is an attribution, not a measurement — usage counted from this commit's own marker forward to the next one on stateless-replicas-4, 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/apimode.go b/apimode.go
index 9759a2b59..f8e0ce005 100644
--- a/apimode.go
+++ b/apimode.go
@@ -45,6 +45,7 @@ import (
"github.com/carlosframework/platform/internal/ratelimit"
"github.com/carlosframework/platform/internal/registrar"
"github.com/carlosframework/platform/internal/release"
+ "github.com/carlosframework/platform/internal/replicas"
"github.com/carlosframework/platform/internal/schedule"
"github.com/carlosframework/platform/internal/telemetry"
"github.com/carlosframework/platform/internal/updatewords"
@@ -3523,6 +3524,14 @@ type apiInstanceRecord struct {
// (release, then one box at a time). Absent from an older console and
// for an instance without a copy assignment.
DeployStatus string `json:"deploy_status,omitempty"`
+ // DesiredCopies and Copies are the console's live view of an instance
+ // with more than one copy (replicaViews): one entry per assigned box,
+ // then one "missing" entry per slot no box holds. Absent from an older
+ // console and for an instance with one copy. The record stays one host:
+ // copies expand only when printed (instances_copies.go), so set and
+ // delete still name the host.
+ DesiredCopies int `json:"desired_copies,omitempty"`
+ Copies []replicas.Copy `json:"copies,omitempty"`
}
// apiConfigRefusal mirrors the console's configRefusalView
diff --git a/docs/site/cli.md b/docs/site/cli.md
index d6fe3849f..721585e3f 100644
--- a/docs/site/cli.md
+++ b/docs/site/cli.md
@@ -671,6 +671,8 @@ stop within seconds and respawn on their next request, which for an idle app
may be a while. Nothing is stuck: the instance comes back with the next
request that needs it. Hibernating instances are left asleep.
+An app that runs more than one copy of an instance refuses `carlos restart --app` and `--environment`, because every copy would restart at the same time. Deploy a new build instead: its copies switch one box at a time.
+
#### Restarting less than the whole app
An app is not always a small thing. One app can own a relay, a router, a
@@ -1116,6 +1118,8 @@ build that failed there is tried again, as a canary:
carlos instances retry --app hello shop-1.hello.example.com
```
+For an instance with more than one copy, `carlos instances list` prints a second table with one row per copy: its box, build, state, health and workers. These come from the router's live check of each copy, not from the boxes' five-minute reports. A copy with no live reading shows as unknown, and a copy that no box holds yet shows as missing. The app's overview page counts the copies running out of the copies wanted.
+
When a box refuses an instance's config, REASON in `carlos instances list` says why and what to do. A box without a secrets key needs `CARLOS_SECRETS_KEY` in its `host.env` and a restart with `systemctl restart carlos-edge`. A box that cannot open a secret needs its key compared with the fleet's using `carlos secrets fingerprint` and `carlos fleets ls`. If the keys match, run `carlos secrets set` for the listed values and rotate any credential the console minted.
For a rootfs app, RUNTIME says `rootfs`, or `rootfs, hibernates` for an instance that sleeps when idle. WORKERS counts the instance's running workers out of the ones it declares, and names a worker that keeps crashing. A binary instance shows `binary` and a dash.
@@ -1212,6 +1216,8 @@ Copies are kept only for visitors who send no cookies and no `Authorization` hea
A page is kept only when your app answers with status 200, no `Set-Cookie`, no `Vary` other than `Accept-Encoding`, an uncompressed body of at most 8 MiB, and a path outside your release's asset folders. Instances that run as `carlos-app@` systemd units are not cached yet.
+An instance with more than one copy keeps a separate page cache on each copy's box. A purge clears only the cache of the copy that sent it, so another copy can serve its own saved page until it expires or that copy purges it too.
+
Clear copies with the `Carlos-Purge` header or `CARLOS_CONTROL_SOCKET`, as you would for the response cache. In the header, `*` clears one host, a path clears that path with any query, `/path?query` clears one address, and `all` clears every host of the instance, including its aliases and custom domains. On the socket, `{"path": "*"}` and `{"path": "all"}` work the same way, and any other `path` with its `query` clears exactly that one address. Each response says what happened in a `Carlos-Cache` header, in the same words as for asset files.
Once a page has been marked, the instance's other responses are no longer kept in the five-minute response cache, so mark every page you want cached.
diff --git a/docs/superpowers/notes/census-proposal-stateless-replicas-4-task3.md b/docs/superpowers/notes/census-proposal-stateless-replicas-4-task3.md
new file mode 100644
index 000000000..109690147
--- /dev/null
+++ b/docs/superpowers/notes/census-proposal-stateless-replicas-4-task3.md
@@ -0,0 +1,11 @@
+# Census approval: stateless-replicas-4-task3
+
+Ruling `census-ruling-stateless-replicas-4-task3`. The independent reviewer approves or rejects every change below, 0 with a new disposition; nothing goes to the census owner (Paul, #280, 2026-10-26).
+
+Envelopes re-pinned: `.`.
+
+Review: a model from the other family than the author reads the branch's diff against main on the amadan.net remote (`origin` or `amadan`, whichever points at amadan.net) and gives a verdict for every unit and every re-pinned envelope above. For a unit, compare the change with its recorded disposition and basis below; for an envelope, read every changed function in the package and what it reaches. Reject if the change lets root open, run, query or follow anything it did not before from a path or input a tenant, an app or a box agent can create, write or name; if it weakens a check, refusal, validation, argument or environment the basis relies on; or if the diff cannot settle either. Otherwise approve. Record each verdict on #280 with the tip. A rejected unit goes back to the author to correct; nothing escalates to the census owner.
+
+Seal: `bd25367161555e8a9c5b0df079ad2d8eb648ebaeae3f407e6c638f2f7f01605b` → `bd25367161555e8a9c5b0df079ad2d8eb648ebaeae3f407e6c638f2f7f01605b`.
+
+Overlay: `internal/provision/testdata/plan14-root-reads-stateless-replicas-4-task3.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`.
diff --git a/docs/superpowers/plans/2026-11-01-stateless-replicas-copy.md b/docs/superpowers/plans/2026-11-01-stateless-replicas-copy.md
index 272fac039..fdb4d3f7e 100644
--- a/docs/superpowers/plans/2026-11-01-stateless-replicas-copy.md
+++ b/docs/superpowers/plans/2026-11-01-stateless-replicas-copy.md
@@ -118,3 +118,10 @@ copy too. Internal wire enums are not an excuse to expose unreviewed text.
| SR-4-C44 | internal/activator/replicadeploy.go | copies above 1 switch builds with an overlap swap, so this release's hold swap was refused. the current build keeps serving | pending (added by Plan 4 Task 2 for a hold demand or hold policy on a replicated instance; awaiting Paul's copy review) |
| SR-4-C45 | internal/rollout/replicas.go | this copy waits for a release to pass before it starts | pending (added by Plan 4 Task 2 for a copy's wake when its record names no build that passed a release; awaiting Paul's copy review) |
| SR-4-C46 | internal/console/replicadeploy.go | the new build's workers failed on <box>, so the deploy stopped. other copies keep serving | pending (added by Plan 4 Task 2 fix round 2 for a switch whose workers failed, which halts the deploy; awaiting Paul's copy review) |
+| SR-4-C47 | internal/console/replicaview.go | this app runs more than one copy of an instance, so a restart would cycle every copy at the same time. deploy a new build instead: its copies switch one box at a time | pending (added by Plan 4 Task 3 for the F2 restart refusal at copies above 1; awaiting Paul's copy review) |
+| SR-4-C48 | internal/console/replicaview.go | This app runs more than one copy of an instance, so a restart would cycle every copy at the same time. Deploy a new build instead: its copies switch one box at a time. | pending (added by Plan 4 Task 3: SR-4-C47 as the app page's restart flash; awaiting Paul's copy review) |
+| SR-4-C49 | instances_copies.go | healthy | pending (added by Plan 4 Task 3 for the copies table's HEALTH cell; awaiting Paul's copy review) |
+| SR-4-C50 | instances_copies.go | unhealthy | pending (added by Plan 4 Task 3 for the copies table's HEALTH cell; awaiting Paul's copy review) |
+| SR-4-C51 | docs/site/cli.md | For an instance with more than one copy, `carlos instances list` prints a second table with one row per copy: its box, build, state, health and workers. These come from the router's live check of each copy, not from the boxes' five-minute reports. A copy with no live reading shows as unknown, and a copy that no box holds yet shows as missing. The app's overview page counts the copies running out of the copies wanted. | pending (added by Plan 4 Task 3; the view-only part of SR-4-C28, whose --box sentence is deferred with --box; awaiting Paul's copy review) |
+| SR-4-C52 | docs/site/cli.md | An instance with more than one copy keeps a separate page cache on each copy's box. A purge clears only the cache of the copy that sent it, so another copy can serve its own saved page until it expires or that copy purges it too. | pending (added by Plan 4 Task 3 per ruling D6; awaiting Paul's copy review) |
+| SR-4-C53 | docs/site/cli.md | An app that runs more than one copy of an instance refuses `carlos restart --app` and `--environment`, because every copy would restart at the same time. Deploy a new build instead: its copies switch one box at a time. | pending (added by Plan 4 Task 3 for the F2 restart refusal; awaiting Paul's copy review) |
diff --git a/instances_cli.go b/instances_cli.go
index 9d766cacd..0552209b4 100644
--- a/instances_cli.go
+++ b/instances_cli.go
@@ -756,6 +756,7 @@ func printInstancesList(out io.Writer, recs []apiInstanceRecord) {
egressCell(r.Egress), r.CreatedAt, r.CreatedBy, reason, seedCell(r), runtimeCell(r), workersCell(r))
}
w.Flush()
+ printCopiesTable(out, recs)
}
func runInstancesList(args []string) {
diff --git a/instances_copies.go b/instances_copies.go
new file mode 100644
index 000000000..516472263
--- /dev/null
+++ b/instances_copies.go
@@ -0,0 +1,105 @@
+package main
+
+// The copies table under `carlos instances list` (stateless replicas Plan
+// 4, Task 3): one row per copy of an instance with more than one copy, from
+// the console's live view (the list's copies key). The main table keeps one
+// row per host, its columns unchanged, so set and delete still name a host
+// and a list with no such instance prints exactly what it always did.
+
+import (
+ "fmt"
+ "io"
+
+ "github.com/carlosframework/platform/internal/replicas"
+)
+
+// The copies table's heading and words. Copy: pending Paul's copy review.
+const (
+ copiesColBox = "BOX" // copy SR-4-C02 (provisional)
+ copiesColBuild = "BUILD" // copy SR-4-C03 (provisional)
+ copiesColState = "STATE" // copy SR-4-C04 (provisional)
+ copiesColHealth = "HEALTH" // copy SR-4-C05 (provisional)
+ copyRunning = "running" // copy SR-4-C07 (provisional)
+ copyDown = "down" // copy SR-4-C08 (provisional)
+ copyFailed = "failed" // copy SR-4-C09 (provisional)
+ copyUnknown = "unknown" // copy SR-4-C10 (provisional)
+ copyMissing = "missing" // copy SR-4-C11 (provisional)
+ copyHealthy = "healthy" // copy SR-4-C49 (provisional)
+ copyUnhealthy = "unhealthy" // copy SR-4-C50 (provisional)
+ copyCellMaxBytes = 128
+)
+
+// replicaCopyRow is one printed copy. It is for printing only: nothing addresses
+// a copy by it.
+type replicaCopyRow struct {
+ Host, Box, Build, State, Health, Workers string
+}
+
+// copyRows expands r's copies into printed rows, in the console's order:
+// assigned boxes, then missing slots. Every cell is checked before it is
+// printed: a state word this client does not know reads unknown, and a box
+// label or build unfit for a terminal reads as a dash.
+func copyRows(r apiInstanceRecord) []replicaCopyRow {
+ rows := make([]replicaCopyRow, 0, len(r.Copies))
+ for _, c := range r.Copies {
+ row := replicaCopyRow{Host: r.Host, Box: copyCell(c.Box), Build: copyCell(c.Version), State: copyState(c), Health: "-", Workers: "-"}
+ switch row.State {
+ case copyMissing:
+ row.Box, row.Build = "-", "-"
+ case copyRunning:
+ row.Health = copyHealthy
+ case copyDown, copyFailed:
+ row.Health = copyUnhealthy
+ default:
+ row.Health = copyUnknown
+ }
+ if (row.State == copyRunning || row.State == copyDown || row.State == copyFailed) &&
+ c.WorkersDeclared > 0 && c.WorkersRunning >= 0 && c.WorkersRunning <= c.WorkersDeclared {
+ row.Workers = fmt.Sprintf("%d/%d", c.WorkersRunning, c.WorkersDeclared)
+ }
+ rows = append(rows, row)
+ }
+ return rows
+}
+
+// copyState is a copy's state word: the console's, when it is one this
+// client knows. A copy is running only when the console also calls it
+// healthy.
+func copyState(c replicas.Copy) string {
+ switch c.State {
+ case copyRunning:
+ if c.Healthy {
+ return copyRunning
+ }
+ case copyDown, copyFailed, copyMissing:
+ return c.State
+ }
+ return copyUnknown
+}
+
+func copyCell(s string) string {
+ if v := cleanConsoleText(s, copyCellMaxBytes); v != "" {
+ return v
+ }
+ return "-"
+}
+
+// printCopiesTable prints the copies table under the main one, after a
+// blank line, when any listed instance has more than one copy; otherwise
+// nothing at all.
+func printCopiesTable(out io.Writer, recs []apiInstanceRecord) {
+ var rows []replicaCopyRow
+ for _, r := range recs {
+ rows = append(rows, copyRows(r)...)
+ }
+ if len(rows) == 0 {
+ return
+ }
+ fmt.Fprintln(out)
+ w := newTable(out)
+ fmt.Fprintln(w, "HOST\t"+copiesColBox+"\t"+copiesColBuild+"\t"+copiesColState+"\t"+copiesColHealth+"\t"+instancesColWorkers)
+ for _, r := range rows {
+ fmt.Fprintf(w, "%s\t%s\t%s\t%s\t%s\t%s\n", r.Host, r.Box, r.Build, r.State, r.Health, r.Workers)
+ }
+ w.Flush()
+}
diff --git a/instances_copies_test.go b/instances_copies_test.go
new file mode 100644
index 000000000..2832ceebb
--- /dev/null
+++ b/instances_copies_test.go
@@ -0,0 +1,102 @@
+package main
+
+import (
+ "bytes"
+ "strings"
+ "testing"
+
+ "github.com/carlosframework/platform/internal/replicas"
+)
+
+// copiesTable is everything printInstancesList printed after the main
+// table's last row, or "" when it printed nothing more.
+func copiesTable(t *testing.T, out string) string {
+ t.Helper()
+ i := strings.Index(out, "\n\n")
+ if i < 0 {
+ return ""
+ }
+ return out[i+2:]
+}
+
+// One host row in the main table, then one row per copy, each with its own
+// box, build, state, health and workers. A missing slot has no box label.
+func TestReplicaCopyListRowsPerBox(t *testing.T) {
+ no := false
+ recs := []apiInstanceRecord{{Host: "shop.example.com", Channel: "edge", Health: "Running", Runtime: "rootfs-v1", Hibernate: &no,
+ DesiredCopies: 3, Copies: []replicas.Copy{
+ {Box: "b1", Version: "v2", State: "running", Healthy: true, WorkersRunning: 2, WorkersDeclared: 2},
+ {Box: "b2", Version: "v1", State: "down", WorkersRunning: 0, WorkersDeclared: 2},
+ {State: "missing"},
+ }}}
+ var buf bytes.Buffer
+ printInstancesList(&buf, recs)
+ out := buf.String()
+ main, _, _ := strings.Cut(out, "\n\n")
+ if n := strings.Count(main, "shop.example.com"); n != 1 {
+ t.Fatalf("the main table names the host %d times, want once:\n%s", n, out)
+ }
+ table := copiesTable(t, out)
+ lines := strings.Split(strings.TrimRight(table, "\n"), "\n")
+ if len(lines) != 4 {
+ t.Fatalf("copies table, want a heading and three rows:\n%s", out)
+ }
+ if got := strings.Fields(lines[0]); strings.Join(got, " ") != "HOST BOX BUILD STATE HEALTH WORKERS" {
+ t.Fatalf("heading %q", lines[0])
+ }
+ for i, want := range [][]string{
+ {"shop.example.com", "b1", "v2", "running", "healthy", "2/2"},
+ {"shop.example.com", "b2", "v1", "down", "unhealthy", "0/2"},
+ {"shop.example.com", "-", "-", "missing", "-", "-"},
+ } {
+ if got := strings.Fields(lines[i+1]); strings.Join(got, " ") != strings.Join(want, " ") {
+ t.Errorf("row %d = %q, want %q", i+1, got, want)
+ }
+ }
+}
+
+// A hub word this client does not know, or bytes unfit for a terminal, are
+// never printed as they came.
+func TestReplicaCopyListCleansCells(t *testing.T) {
+ recs := []apiInstanceRecord{{Host: "shop.example.com", DesiredCopies: 2, Copies: []replicas.Copy{
+ {Box: "b1\x1b[2J", Version: "v\x07", State: "exploded", Healthy: true},
+ {Box: "b2", Version: "v1", State: "unknown"},
+ }}}
+ var buf bytes.Buffer
+ printInstancesList(&buf, recs)
+ out := buf.String()
+ if strings.ContainsAny(out, "\x1b\x07") || strings.Contains(out, "exploded") {
+ t.Fatalf("an unclean cell was printed:\n%q", out)
+ }
+ lines := strings.Split(strings.TrimRight(copiesTable(t, out), "\n"), "\n")
+ if len(lines) != 3 {
+ t.Fatalf("copies table, want a heading and two rows:\n%s", out)
+ }
+ if got := strings.Join(strings.Fields(lines[1]), " "); got != "shop.example.com - - unknown unknown -" {
+ t.Fatalf("unclean row = %q", got)
+ }
+ if got := strings.Join(strings.Fields(lines[2]), " "); got != "shop.example.com b2 v1 unknown unknown -" {
+ t.Fatalf("unknown row = %q", got)
+ }
+}
+
+// copies=1, and every console that predates copies: the list is exactly what
+// it was, RUNTIME and WORKERS included, and no second table.
+func TestReplicaVisibilityLegacyColumnsUnchanged(t *testing.T) {
+ no := false
+ recs := []apiInstanceRecord{{Host: "shop.example.com", Channel: "edge", Health: "running", Runtime: "rootfs-v1", Hibernate: &no,
+ Rollout: &apiRollout{Box: "pi-1", Installed: "r1", Workers: []apiWorker{{Name: "worker", State: "running"}}}}}
+ var buf bytes.Buffer
+ printInstancesList(&buf, recs)
+ out := buf.String()
+ if strings.Contains(out, "\n\n") || strings.Contains(out, "BOX") {
+ t.Fatalf("a one-copy list printed a copies table:\n%s", out)
+ }
+ lines := strings.Split(strings.TrimRight(out, "\n"), "\n")
+ if len(lines) != 2 || !strings.HasSuffix(strings.Join(strings.Fields(lines[0]), "\t"), "\tREASON\tSEED\tRUNTIME\tWORKERS") {
+ t.Fatalf("one-copy list:\n%s", out)
+ }
+ if f := strings.Fields(lines[1]); f[len(f)-2] != "rootfs" || f[len(f)-1] != "1/1" {
+ t.Fatalf("one-copy row %q, want rootfs and 1/1 last", lines[1])
+ }
+}
diff --git a/internal/console/apicli.go b/internal/console/apicli.go
index 3a06e848b..88be6aa72 100644
--- a/internal/console/apicli.go
+++ b/internal/console/apicli.go
@@ -1578,6 +1578,10 @@ func (s *Server) handleAPIRestart(w http.ResponseWriter, r *http.Request) {
}
ctx, cancel := context.WithTimeout(r.Context(), 15*time.Second)
defer cancel()
+ if ref := s.restartCopies(ctx, acct.Sqid, app); ref != nil {
+ writeDoorRefusalJSON(w, r, ref)
+ return
+ }
if err := s.requestAppRestart(ctx, acct.Sqid, app); err != nil {
// Logged, not returned: a store error carries bucket names, endpoints
// and request ids. The caller gets the fixed sentence every other
diff --git a/internal/console/apiinstances.go b/internal/console/apiinstances.go
index 476508d38..5572ecbd1 100644
--- a/internal/console/apiinstances.go
+++ b/internal/console/apiinstances.go
@@ -49,6 +49,7 @@ import (
"github.com/carlosframework/platform/internal/regionlabel"
"github.com/carlosframework/platform/internal/registry"
"github.com/carlosframework/platform/internal/release"
+ "github.com/carlosframework/platform/internal/replicas"
"github.com/carlosframework/platform/internal/status"
)
@@ -275,6 +276,13 @@ type instanceListRecord struct {
// DeployStatus is replicaDeployStatus: the release and box-by-box swap
// state of a record with a copy assignment. Absent otherwise.
DeployStatus string `json:"deploy_status,omitempty"`
+ // DesiredCopies and Copies are the live view of a record with more than
+ // one copy (replicaViews): one entry per assigned box with the hub's own
+ // reading of its build, state, health and workers, then one "missing"
+ // entry per slot no box holds. Absent for a record with one copy. The
+ // record stays one host object; nothing here is a record of its own.
+ DesiredCopies int `json:"desired_copies,omitempty"`
+ Copies []replicas.Copy `json:"copies,omitempty"`
}
// hubRouting is the console box's registry as its edge routes it: the rows
@@ -1314,6 +1322,12 @@ func (s *Server) handleAPIInstanceList(w http.ResponseWriter, r *http.Request) {
}
health, held := s.instanceHealth(ctx, recs)
fleetHealth(health, recs, join, acct.Sqid, app)
+ // A record with more than one copy takes its word from the hub's live
+ // reading only (replicaview.go), before counts and the health filter.
+ views := s.replicaViewsLogged(ctx, recs)
+ for host, v := range views {
+ health[host] = replicaHealthWord(v)
+ }
counts := map[string]int{}
matched := make([]instanceListRecord, 0, len(recs))
home, names := s.regionHome(), s.regionNames()
@@ -1342,7 +1356,9 @@ func (s *Server) handleAPIInstanceList(w http.ResponseWriter, r *http.Request) {
MovePhrase: regionlabel.MovePhrase(rec, home, names),
Egress: join.egressFor(rec.Host, acct.Sqid, app),
RouteHeld: forwardHeldReason(held, rec),
- DeployStatus: replicaDeployStatus(rec)})
+ DeployStatus: replicaDeployStatus(rec),
+ DesiredCopies: views[rec.Host].Desired,
+ Copies: views[rec.Host].Copies})
}
total := len(matched)
// provision.ListRecords returns records host-sorted and nothing above
diff --git a/internal/console/apirestartscope.go b/internal/console/apirestartscope.go
index 0044e4596..4e4fafeb1 100644
--- a/internal/console/apirestartscope.go
+++ b/internal/console/apirestartscope.go
@@ -234,6 +234,15 @@ func (s *Server) handleAPIRestartScope(w http.ResponseWriter, r *http.Request) {
}
ctx, cancel := context.WithTimeout(r.Context(), 15*time.Second)
defer cancel()
+ // Every box matches an environment against its own routes, the copies'
+ // boxes included, all on one serial move. A host here is one of this
+ // box's own routes, never a replicated one (no copy runs on the hub).
+ if scope.Kind == release.RestartScopeEnvironment {
+ if ref := s.restartCopies(ctx, acct.Sqid, app); ref != nil {
+ writeDoorRefusalJSON(w, r, ref)
+ return
+ }
+ }
if err := s.writeRestartScope(ctx, acct.Sqid, app, scope); err != nil {
// Logged, not returned: a store error carries bucket names, endpoints
// and request ids. The caller gets the fixed sentence every other
diff --git a/internal/console/browserrestart.go b/internal/console/browserrestart.go
index 23a093c70..2b0b90af2 100644
--- a/internal/console/browserrestart.go
+++ b/internal/console/browserrestart.go
@@ -123,6 +123,15 @@ func (s *Server) handleBrowserRestart(w http.ResponseWriter, r *http.Request, ho
defer cancel()
var restartErr error
if host == "" {
+ if ref := s.restartCopies(ctx, acct.Sqid, app); ref != nil {
+ msg := words.Failed
+ if ref.Status == http.StatusConflict {
+ msg = restartCopiesRefusalPage
+ }
+ s.setFlash(w, "err", msg)
+ http.Redirect(w, r, "/a/"+url.PathEscape(acct.Sqid)+"/apps/"+url.PathEscape(app)+"/instances", http.StatusSeeOther)
+ return
+ }
restartErr = s.requestAppRestart(ctx, acct.Sqid, app)
} else {
restartErr = s.writeRestartScope(ctx, acct.Sqid, app, scope)
diff --git a/internal/console/overview.go b/internal/console/overview.go
index ca72ee3ee..51d442edb 100644
--- a/internal/console/overview.go
+++ b/internal/console/overview.go
@@ -8,6 +8,7 @@ import (
"strings"
"github.com/carlosframework/platform/internal/registry"
+ "github.com/carlosframework/platform/internal/replicas"
)
// OverviewStats is the Overview dashboard: the handful of numbers an owner
@@ -40,6 +41,16 @@ type OverviewStats struct {
// minus the unknowable. Templates render facts, never compute them.
InstanceCounted int
+ // CopiesDesired is the copies the app's instances with more than one
+ // copy should have, summed, and CopiesRunning how many of them the
+ // hub's live reading proves healthy: desired minus the missing or
+ // unhealthy entries (replicaViews), never the number of assigned boxes.
+ // CopiesUnknown counts assigned copies with no live reading. All zero
+ // for an app whose instances have one copy each, which shows nothing.
+ CopiesDesired int
+ CopiesRunning int
+ CopiesUnknown int
+
// SidecarTotal is how many of this account's routes are standalone
// workers (Kind "sidecar") — counted apart from InstanceTotal on
// purpose. A sidecar never serves a request and is never static either
@@ -245,7 +256,10 @@ func healthVerdict(st OverviewStats) (string, string) {
return "attention", "Needs attention"
case st.InstanceReporting+st.InstanceAsleep < st.InstanceCounted:
return "attention", "Needs attention"
- case st.InstanceUnknown > 0:
+ case st.CopiesRunning+st.CopiesUnknown < st.CopiesDesired:
+ // A copy the hub reads down or failed, or a slot no box holds.
+ return "attention", "Needs attention"
+ case st.InstanceUnknown > 0, st.CopiesUnknown > 0:
return "unknown", "Can't tell right now"
case st.Deployment.ReportableCount == 0:
return "ok", "All good"
@@ -260,6 +274,18 @@ func healthVerdict(st OverviewStats) (string, string) {
}
}
+// countCopies adds the live copy views to the dashboard and recomputes its
+// verdict: a copy the hub reads down, or a slot no box holds, needs
+// attention, and a copy with no reading cannot be called fine.
+func (st *OverviewStats) countCopies(views map[string]replicas.Snapshot) {
+ for _, v := range views {
+ st.CopiesDesired += v.Desired
+ st.CopiesRunning += copiesRunning(v)
+ st.CopiesUnknown += copiesUnknown(v)
+ }
+ st.Verdict, st.VerdictLabel = healthVerdict(*st)
+}
+
// domainNeedsAttention is the dashboard's one-bit read of a Domains row:
// guidance text means DNS isn't pointing here, and a TLS status other than
// ready/issuing means issuance failed. Issuing is patience, not attention.
diff --git a/internal/console/replicaview.go b/internal/console/replicaview.go
new file mode 100644
index 000000000..8ae5bf32c
--- /dev/null
+++ b/internal/console/replicaview.go
@@ -0,0 +1,246 @@
+package console
+
+// The console's live view of each copy of a replicated instance (stateless
+// replicas Plan 4, Task 3 as trimmed by R17). The hub is the console's own
+// box: its edge probes every assigned copy once a second and serves the
+// result on the agent's private snapshot socket (internal/host,
+// replicahealth_linux.go). This file joins that reading to the instance
+// records a caller already holds. It reads no bucket object and adds no
+// cadence: one local socket read per page view or list call, and none at all
+// when no record has more than one copy.
+//
+// Copy health shown to people comes from this reading only. The five-minute
+// status report's copy evidence (status.BoxMetrics.ReplicaCopies) is history
+// and is never read here, so a copy with no live reading is "unknown", never
+// "running".
+
+import (
+ "context"
+ "errors"
+ "log"
+ "net/http"
+ "slices"
+
+ "github.com/carlosframework/platform/internal/appconfig"
+ "github.com/carlosframework/platform/internal/provision"
+ "github.com/carlosframework/platform/internal/registry"
+ "github.com/carlosframework/platform/internal/replicas"
+)
+
+// The copy states a view carries. Anything else a hub says reads unknown.
+const (
+ copyStateRunning = "running" // copy SR-4-C07 (provisional)
+ copyStateDown = "down" // copy SR-4-C08 (provisional)
+ copyStateFailed = "failed" // copy SR-4-C09 (provisional)
+ copyStateUnknown = "unknown" // copy SR-4-C10 (provisional)
+ copyStateMissing = "missing" // copy SR-4-C11 (provisional)
+)
+
+// restartCopiesRefusal refuses `carlos restart` for an app with more than
+// one copy of an instance: the restart reaches every box on the same serial
+// move, so it would cycle every copy at once. copy SR-4-C47 (provisional,
+// pending Paul's copy review)
+const restartCopiesRefusal = "this app runs more than one copy of an instance, so a restart would cycle every copy at the same time. deploy a new build instead: its copies switch one box at a time"
+
+// restartCopiesRefusalPage is restartCopiesRefusal as the app page's flash
+// says it. copy SR-4-C48 (provisional, pending Paul's copy review)
+const restartCopiesRefusalPage = "This app runs more than one copy of an instance, so a restart would cycle every copy at the same time. Deploy a new build instead: its copies switch one box at a time."
+
+// restartCopies is the restart doors' check (F2). Every box serving the app
+// reads an app-wide restart on the same serial move, and a narrowed one by
+// environment is matched by every box against its own routes, so either
+// would cycle every copy of a replicated instance at once rather than one
+// box at a time. It refuses while the app's copies setting is above 1, or
+// while any record still holds more than one box, assigned or retiring, as
+// it does while a count of 1 takes effect. An app that never set a count is
+// one read (its config); only an app that did lists its records. Evidence
+// that cannot be read refuses, and nothing is cycled.
+func (s *Server) restartCopies(ctx context.Context, acct, app string) *doorRefusal {
+ unread := &doorRefusal{Status: http.StatusBadGateway, Msg: "could not request the restart — nothing was cycled; try again"}
+ cfg, err := s.copiesDefault(ctx, acct, app)
+ switch {
+ case err != nil:
+ log.Printf("console: restart %s/%s: copies setting: %v", acct, app, err)
+ return unread
+ case !cfg.explicit:
+ return nil
+ case appconfig.CopiesOf(&cfg.manifest) > 1:
+ return &doorRefusal{Status: http.StatusConflict, Msg: restartCopiesRefusal}
+ }
+ recs, truncated, skipped, err := s.listRecordsComplete(ctx, acct, app, instanceListMax)
+ if err != nil || truncated || len(skipped) > 0 {
+ log.Printf("console: restart %s/%s: records: %v (truncated %v, unreadable %v)", acct, app, err, truncated, skipped)
+ return unread
+ }
+ for _, rec := range recs {
+ if a := rec.ReplicaAssignment; a != nil && len(a.Boxes)+len(a.Retiring) > 1 {
+ return &doorRefusal{Status: http.StatusConflict, Msg: restartCopiesRefusal}
+ }
+ }
+ return nil
+}
+
+// replicaHealthSocket is Plan 3's snapshot socket on the hub, the agent's
+// (internal/host replicaHealthSocket). Only its path is shared: the console
+// dials it and never chooses a path from data.
+const replicaHealthSocket = "/run/carlos/.replicas/health.sock"
+
+// errNoHubReading says the console has no live copy table: no agent on this
+// box, a platform without the socket, or a socket this console may not use.
+var errNoHubReading = errors.New("replica health: no hub reading")
+
+// replicatedRecord reports whether rec has more than one copy. A copies=1
+// record keeps its legacy view and costs no socket read.
+func replicatedRecord(rec provision.Record) bool {
+ a := rec.ReplicaAssignment
+ return a != nil && a.Desired > 1
+}
+
+// replicaSnapshots is the hub's live copy table: the test hook when set,
+// else the private socket.
+func (s *Server) replicaSnapshots(ctx context.Context) (map[string]replicas.Snapshot, error) {
+ if s.replicaHealth != nil {
+ return s.replicaHealth(ctx)
+ }
+ return readReplicaHealthSocket(ctx, replicaHealthSocket)
+}
+
+// replicaViews is the live view of every record in recs with more than one
+// copy, keyed by host. Each view has one copy per assigned box, in label
+// order, then one "missing" copy per slot no box holds; it never invents a
+// box label. A copy's state and health come from the hub's reading only when
+// that reading names the record's own account, app, host, lifetime and
+// assignment revision, and the copy's own fleet and box; otherwise the copy
+// is unknown and not healthy. The views are always usable: err only says
+// the hub could not be read, and every copy then reads unknown.
+func (s *Server) replicaViews(ctx context.Context, recs []provision.Record) (map[string]replicas.Snapshot, error) {
+ var want []provision.Record
+ for _, rec := range recs {
+ if replicatedRecord(rec) {
+ want = append(want, rec)
+ }
+ }
+ if len(want) == 0 {
+ return nil, nil
+ }
+ live, err := s.replicaSnapshots(ctx)
+ if err != nil {
+ live = nil
+ }
+ out := make(map[string]replicas.Snapshot, len(want))
+ for _, rec := range want {
+ reading, ok := live[rec.Host]
+ out[rec.Host] = replicaView(rec, reading, ok)
+ }
+ return out, err
+}
+
+// replicaViewsLogged is replicaViews for a read-only page or list: a hub
+// that cannot be read is logged once per call, and every copy reads unknown.
+func (s *Server) replicaViewsLogged(ctx context.Context, recs []provision.Record) map[string]replicas.Snapshot {
+ views, err := s.replicaViews(ctx, recs)
+ if err != nil {
+ log.Printf("console: replica health: %v; copies read unknown", err)
+ }
+ return views
+}
+
+// replicaView joins one record to the hub's reading of its host.
+func replicaView(rec provision.Record, live replicas.Snapshot, ok bool) replicas.Snapshot {
+ a := rec.ReplicaAssignment
+ inc, incErr := provision.Incarnation(rec.Account, rec.App, rec.Host, rec.CreatedAt)
+ fleet, _ := registry.FleetPlacement(rec.Region)
+ v := replicas.Snapshot{Host: rec.Host, Account: rec.Account, App: rec.App, Incarnation: inc, Revision: a.Revision, Desired: a.Desired}
+ blank := replicas.Copy{Host: rec.Host, Account: rec.Account, App: rec.App, Fleet: fleet, Incarnation: inc, AssignmentRevision: a.Revision}
+ var boxes []string
+ if replicas.ValidateAssignment(*a) == nil {
+ boxes = a.Boxes
+ }
+ joined := ok && incErr == nil && fleet != "" && live.Host == rec.Host && live.Account == rec.Account &&
+ live.App == rec.App && live.Incarnation == inc && live.Revision == a.Revision
+ byBox := map[string]replicas.Copy{}
+ twice := map[string]bool{}
+ if joined {
+ for _, c := range live.Copies {
+ if c.Host != rec.Host || c.Account != rec.Account || c.App != rec.App || c.Fleet != fleet ||
+ c.Incarnation != inc || c.AssignmentRevision != a.Revision || !slices.Contains(boxes, c.Box) {
+ continue
+ }
+ if _, seen := byBox[c.Box]; seen {
+ twice[c.Box] = true
+ }
+ byBox[c.Box] = c
+ }
+ }
+ for _, box := range boxes {
+ c, ok := byBox[box]
+ if !ok || twice[box] {
+ // No reading for this copy, or two that disagree: unknown.
+ c = blank
+ c.Box, c.State = box, copyStateUnknown
+ }
+ c.Socket, c.BootID = "", ""
+ switch c.State {
+ case copyStateRunning, copyStateDown, copyStateFailed:
+ default:
+ c.State = copyStateUnknown
+ }
+ // Healthy only as the hub's verdict on a running copy.
+ c.Healthy = c.Healthy && c.State == copyStateRunning
+ if !c.Healthy && c.State == copyStateRunning {
+ c.State = copyStateUnknown
+ }
+ v.Copies = append(v.Copies, c)
+ }
+ for i := len(boxes); i < a.Desired; i++ {
+ c := blank
+ c.State = copyStateMissing
+ v.Copies = append(v.Copies, c)
+ }
+ return v
+}
+
+// copiesRunning is a view's running count: Desired minus the missing or
+// unhealthy entries, never the number of assigned boxes.
+func copiesRunning(v replicas.Snapshot) int {
+ n := 0
+ for _, c := range v.Copies {
+ if c.Healthy && c.Box != "" {
+ n++
+ }
+ }
+ return min(n, v.Desired)
+}
+
+// copiesUnknown is how many of a view's assigned copies have no live
+// reading.
+func copiesUnknown(v replicas.Snapshot) int {
+ n := 0
+ for _, c := range v.Copies {
+ if c.State == copyStateUnknown {
+ n++
+ }
+ }
+ return n
+}
+
+// replicaHealthWord is the instance-level health word of a replicated
+// record, from its live view only: Running while any copy is healthy, Not
+// responding when the hub reads every assigned copy down or failed, and
+// otherwise that it cannot tell. A box report saying the instance is awake
+// never makes it Running.
+func replicaHealthWord(v replicas.Snapshot) string {
+ if copiesRunning(v) > 0 {
+ return "Running"
+ }
+ known := 0
+ for _, c := range v.Copies {
+ if c.State == copyStateDown || c.State == copyStateFailed {
+ known++
+ }
+ }
+ if known > 0 && copiesUnknown(v) == 0 {
+ return "Not responding"
+ }
+ return healthUnknown
+}
diff --git a/internal/console/replicaview_linux.go b/internal/console/replicaview_linux.go
new file mode 100644
index 000000000..201408ed9
--- /dev/null
+++ b/internal/console/replicaview_linux.go
@@ -0,0 +1,134 @@
+//go:build linux
+
+package console
+
+// The console's side of Plan 3's private snapshot socket.
+//
+// ACCESS DECISION (D6, Plan 3 Q7): the socket stays private. The agent
+// creates /run/carlos/.replicas 0700 and health.sock 0600, both owned by the
+// agent's user (internal/host/replicahealth_linux.go), and this change does
+// not widen either mode or add a group. The console reads it because it runs
+// as that same user (console.service, User=carlos, like carlos-edge), and it
+// checks that before trusting a byte: the directory and the socket must be
+// owned by the console's own effective uid, the directory must admit no
+// group or other access, and the process at the other end of the connection
+// must be that uid too (SO_PEERCRED). A console that runs as any other user
+// gets no reading, and every copy then shows as unknown, never healthy.
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "io"
+ "net"
+ "net/http"
+ "os"
+ "path/filepath"
+ "syscall"
+ "time"
+
+ "github.com/carlosframework/platform/internal/replicas"
+)
+
+// replicaHealthTimeout bounds one read (Plan 3: one second).
+const replicaHealthTimeout = time.Second
+
+// replicaHealthMaxBytes bounds the reply. A hub's table is a few hundred
+// bytes per copy; a reply this large is not one.
+const replicaHealthMaxBytes = 8 << 20
+
+func readReplicaHealthSocket(ctx context.Context, path string) (map[string]replicas.Snapshot, error) {
+ euid := uint32(os.Geteuid())
+ if err := ownedPrivate(filepath.Dir(path), euid, true); err != nil {
+ return nil, err
+ }
+ if err := ownedPrivate(path, euid, false); err != nil {
+ return nil, err
+ }
+ ctx, cancel := context.WithTimeout(ctx, replicaHealthTimeout)
+ defer cancel()
+ client := &http.Client{Transport: &http.Transport{
+ DisableKeepAlives: true,
+ DialContext: func(ctx context.Context, _, _ string) (net.Conn, error) {
+ var d net.Dialer
+ conn, err := d.DialContext(ctx, "unix", path)
+ if err != nil {
+ return nil, errors.Join(errNoHubReading, err)
+ }
+ if err := peerIs(conn, euid); err != nil {
+ conn.Close()
+ return nil, err
+ }
+ return conn, nil
+ },
+ }}
+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, "http://replica-health/replica-health", nil)
+ if err != nil {
+ return nil, err
+ }
+ resp, err := client.Do(req)
+ if err != nil {
+ return nil, err
+ }
+ defer resp.Body.Close()
+ if resp.StatusCode != http.StatusOK {
+ return nil, errors.Join(errNoHubReading, errors.New(resp.Status))
+ }
+ raw, err := io.ReadAll(io.LimitReader(resp.Body, replicaHealthMaxBytes+1))
+ if err != nil {
+ return nil, err
+ }
+ if len(raw) > replicaHealthMaxBytes {
+ return nil, errors.Join(errNoHubReading, errors.New("reply too large"))
+ }
+ var out map[string]replicas.Snapshot
+ if err := json.Unmarshal(raw, &out); err != nil {
+ return nil, errors.Join(errNoHubReading, err)
+ }
+ return out, nil
+}
+
+// ownedPrivate checks that path is owned by uid, is a directory (dir) or a
+// socket, and, for the directory, admits no group or other access.
+func ownedPrivate(path string, uid uint32, dir bool) error {
+ info, err := os.Lstat(path)
+ if err != nil {
+ return errors.Join(errNoHubReading, err)
+ }
+ st, ok := info.Sys().(*syscall.Stat_t)
+ switch {
+ case !ok || st.Uid != uid:
+ return errors.Join(errNoHubReading, errors.New(path+": not owned by this console's user"))
+ case dir && (!info.IsDir() || info.Mode().Perm()&0o077 != 0):
+ return errors.Join(errNoHubReading, errors.New(path+": not a private directory"))
+ case !dir && info.Mode()&os.ModeSocket == 0:
+ return errors.Join(errNoHubReading, errors.New(path+": not a socket"))
+ }
+ return nil
+}
+
+// peerIs checks the connected process's uid with SO_PEERCRED.
+func peerIs(conn net.Conn, uid uint32) error {
+ uc, ok := conn.(*net.UnixConn)
+ if !ok {
+ return errNoHubReading
+ }
+ raw, err := uc.SyscallConn()
+ if err != nil {
+ return errors.Join(errNoHubReading, err)
+ }
+ var cred *syscall.Ucred
+ var credErr error
+ if err := raw.Control(func(fd uintptr) {
+ cred, credErr = syscall.GetsockoptUcred(int(fd), syscall.SOL_SOCKET, syscall.SO_PEERCRED)
+ }); err != nil {
+ return errors.Join(errNoHubReading, err)
+ }
+ if credErr != nil {
+ return errors.Join(errNoHubReading, credErr)
+ }
+ if cred.Uid != uid {
+ return errors.Join(errNoHubReading, errors.New("the snapshot socket is served by another user"))
+ }
+ return nil
+}
diff --git a/internal/console/replicaview_linux_test.go b/internal/console/replicaview_linux_test.go
new file mode 100644
index 000000000..6257f0491
--- /dev/null
+++ b/internal/console/replicaview_linux_test.go
@@ -0,0 +1,75 @@
+//go:build linux
+
+package console
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "net"
+ "net/http"
+ "os"
+ "path/filepath"
+ "testing"
+
+ "github.com/carlosframework/platform/internal/replicas"
+)
+
+// The access decision, witnessed: the console reads the agent's private
+// socket as the same user, through a 0700 directory, and refuses a
+// directory others may enter or a path that is not a socket. Every refusal
+// is errNoHubReading, which the views turn into unknown copies.
+func TestReplicaVisibilityReadsThePrivateSocket(t *testing.T) {
+ base, err := os.MkdirTemp(os.Getenv("TMPDIR"), "rv")
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { os.RemoveAll(base) })
+ dir := filepath.Join(base, ".replicas")
+ if err := os.Mkdir(dir, 0o700); err != nil {
+ t.Fatal(err)
+ }
+ path := filepath.Join(dir, "health.sock")
+ ln, err := net.Listen("unix", path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := os.Chmod(path, 0o600); err != nil {
+ t.Fatal(err)
+ }
+ want := map[string]replicas.Snapshot{"shop.example.com": {Host: "shop.example.com", Desired: 2,
+ Copies: []replicas.Copy{{Box: "b1", State: "running", Healthy: true}}}}
+ srv := &http.Server{Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path != "/replica-health" {
+ http.NotFound(w, r)
+ return
+ }
+ _ = json.NewEncoder(w).Encode(want)
+ })}
+ go srv.Serve(ln)
+ t.Cleanup(func() { srv.Close() })
+
+ got, err := readReplicaHealthSocket(context.Background(), path)
+ if err != nil || len(got["shop.example.com"].Copies) != 1 || !got["shop.example.com"].Copies[0].Healthy {
+ t.Fatalf("read %+v %v, want the hub's table", got, err)
+ }
+ if err := os.Chmod(dir, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := readReplicaHealthSocket(context.Background(), path); !errors.Is(err, errNoHubReading) {
+ t.Fatalf("a directory others may enter: %v, want no hub reading", err)
+ }
+ if err := os.Chmod(dir, 0o700); err != nil {
+ t.Fatal(err)
+ }
+ plain := filepath.Join(dir, "plain")
+ if err := os.WriteFile(plain, nil, 0o600); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := readReplicaHealthSocket(context.Background(), plain); !errors.Is(err, errNoHubReading) {
+ t.Fatalf("a file that is not a socket: %v, want no hub reading", err)
+ }
+ if _, err := readReplicaHealthSocket(context.Background(), filepath.Join(dir, "absent.sock")); !errors.Is(err, errNoHubReading) {
+ t.Fatalf("no socket: %v, want no hub reading", err)
+ }
+}
diff --git a/internal/console/replicaview_other.go b/internal/console/replicaview_other.go
new file mode 100644
index 000000000..12b2b0af9
--- /dev/null
+++ b/internal/console/replicaview_other.go
@@ -0,0 +1,15 @@
+//go:build !linux
+
+package console
+
+import (
+ "context"
+
+ "github.com/carlosframework/platform/internal/replicas"
+)
+
+// The snapshot socket is served by Linux agents only. Elsewhere there is no
+// hub reading, and every copy reads unknown.
+func readReplicaHealthSocket(context.Context, string) (map[string]replicas.Snapshot, error) {
+ return nil, errNoHubReading
+}
diff --git a/internal/console/replicaview_test.go b/internal/console/replicaview_test.go
new file mode 100644
index 000000000..409671de9
--- /dev/null
+++ b/internal/console/replicaview_test.go
@@ -0,0 +1,423 @@
+package console
+
+// The live copy view (stateless replicas Plan 4, Task 3 as trimmed by R17):
+// per-copy rows on the list door, the app overview's "N of M copies
+// running", a run and a session that start exactly once with two assigned
+// boxes, and a restart that refuses an app with more than one copy. Every
+// test goes through the real console (the interactive fixture's NewServer)
+// with bah's shop.example.com on bah's fleet home (ixFleetWorld), b1 and b2
+// both active. The hub's live table is the test hook replicaHealth.
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "net/http"
+ "os"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "golang.org/x/net/websocket"
+
+ "github.com/carlosframework/platform/internal/appconfig"
+ "github.com/carlosframework/platform/internal/interactive"
+ "github.com/carlosframework/platform/internal/provision"
+ "github.com/carlosframework/platform/internal/registry"
+ "github.com/carlosframework/platform/internal/release"
+ "github.com/carlosframework/platform/internal/replicas"
+ "github.com/carlosframework/platform/internal/runs"
+ "github.com/carlosframework/platform/internal/status"
+)
+
+// replicaViewFx is bah's shop with shop.example.com assigned to b1 and b2
+// of fleet home (desired copies desired), both boxes active and reporting
+// the host awake with both copies running, as the five-minute report would
+// say. It returns the fixture, the boxes' bearers, and the record.
+func replicaViewFx(t *testing.T, code string, desired int) (*interactiveFx, string, string, provision.Record) {
+ t.Helper()
+ fx := newIxFx(t, code)
+ b1, b2, _ := ixFleetWorld(t, fx, fx.acct)
+ reg, err := openRegistry(fx.regPath)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := reg.SetFleetBoxStatus("home", "b2", "active"); err != nil {
+ t.Fatal(err)
+ }
+ replaceRecord(t, fx, func(r *provision.Record) {
+ r.RecordSeq++
+ r.ReplicaAssignment = &replicas.Assignment{Revision: r.RecordSeq, Desired: desired, Boxes: []string{"b1", "b2"}}
+ })
+ rec, _ := ixRecord(t, fx, ixHost)
+ inc, err := provision.Incarnation(rec.Account, rec.App, rec.Host, rec.CreatedAt)
+ if err != nil {
+ t.Fatal(err)
+ }
+ // The status report claims both copies running and the host awake on
+ // both boxes. Nothing below may believe it over the hub.
+ for _, box := range []string{"b1", "b2"} {
+ b := status.Box{GeneratedAt: time.Now().Add(time.Second), Label: box,
+ Metrics: &status.BoxMetrics{Release: "v" + release.RootfsLifecycleFloor.String(),
+ Rollout: &status.RolloutReport{Hosts: map[string]status.HostRollout{
+ ixHost: {Account: fx.acct, App: "shop", Installed: "v1", Serving: "v1", Awake: true}}},
+ ReplicaCopies: map[string][]replicas.Copy{ixHost: {
+ {Host: ixHost, Account: fx.acct, App: "shop", Fleet: "home", Box: "b1", Incarnation: inc, AssignmentRevision: rec.ReplicaAssignment.Revision, State: "running", Healthy: true},
+ {Host: ixHost, Account: fx.acct, App: "shop", Fleet: "home", Box: "b2", Incarnation: inc, AssignmentRevision: rec.ReplicaAssignment.Revision, State: "running", Healthy: true},
+ }}}}
+ if err := status.WriteBox(context.Background(), release.NewPrefixStore(fx.rel, "fleets/home/"), b); err != nil {
+ t.Fatal(err)
+ }
+ }
+ return fx, b1, b2, rec
+}
+
+// hubCopy is the hub's reading of rec's copy on box.
+func hubCopy(rec provision.Record, box, state string, healthy bool, version string, running, declared int) replicas.Copy {
+ inc, _ := provision.Incarnation(rec.Account, rec.App, rec.Host, rec.CreatedAt)
+ return replicas.Copy{Host: rec.Host, Account: rec.Account, App: rec.App, Fleet: "home", Box: box, BootID: "boot-" + box,
+ Incarnation: inc, AssignmentRevision: rec.ReplicaAssignment.Revision, Generation: 3, Version: version,
+ Digest: strings.Repeat("ab", 32), State: state, Healthy: healthy, ObservedAt: time.Now(),
+ WorkersRunning: running, WorkersDeclared: declared, Socket: "/run/carlos/sockets/x.sock"}
+}
+
+// hubSays makes the hub's live table copies of rec, or err.
+func hubSays(fx *interactiveFx, rec provision.Record, err error, copies ...replicas.Copy) {
+ inc, _ := provision.Incarnation(rec.Account, rec.App, rec.Host, rec.CreatedAt)
+ fx.srv.replicaHealth = func(context.Context) (map[string]replicas.Snapshot, error) {
+ if err != nil {
+ return nil, err
+ }
+ return map[string]replicas.Snapshot{rec.Host: {Host: rec.Host, Account: rec.Account, App: rec.App, Incarnation: inc,
+ Revision: rec.ReplicaAssignment.Revision, Desired: rec.ReplicaAssignment.Desired, Copies: copies}}, nil
+ }
+}
+
+// listedCopy is the wire shape of one copy on the list door.
+type listedCopy struct {
+ Box string `json:"box"`
+ Version string `json:"version"`
+ State string `json:"state"`
+ Healthy bool `json:"healthy"`
+ WorkersRunning int `json:"workers_running"`
+ WorkersDeclared int `json:"workers_declared"`
+ BootID string `json:"boot_id"`
+}
+
+type listedInstance struct {
+ Host string `json:"host"`
+ Health string `json:"health"`
+ DesiredCopies int `json:"desired_copies"`
+ Copies []listedCopy `json:"copies"`
+ Raw json.RawMessage `json:"-"`
+}
+
+// listShop lists shop through the list door as alice, with query q.
+func listShop(t *testing.T, fx *interactiveFx, q string) (rows []listedInstance, raw string) {
+ t.Helper()
+ code, _, raw := rawReq(t, http.MethodGet, instancesURL(fx.consoleFixture, fx.acct, "shop")+q, fx.alice, "")
+ if code != http.StatusOK {
+ t.Fatalf("list = %d %s", code, raw)
+ }
+ var out struct {
+ Instances []listedInstance `json:"instances"`
+ }
+ if err := json.Unmarshal([]byte(raw), &out); err != nil {
+ t.Fatalf("list body %s: %v", raw, err)
+ }
+ return out.Instances, raw
+}
+
+// onlyShopHost is the one listed object for ixHost.
+func onlyShopHost(t *testing.T, rows []listedInstance) listedInstance {
+ t.Helper()
+ var found []listedInstance
+ for _, r := range rows {
+ if r.Host == ixHost {
+ found = append(found, r)
+ }
+ }
+ if len(found) != 1 {
+ t.Fatalf("%d objects for %s, want one host object: %+v", len(found), ixHost, rows)
+ }
+ return found[0]
+}
+
+// copiesLine is the overview's copies line for shop, as paul sees it.
+func copiesLine(t *testing.T, fx *interactiveFx, browser *http.Client) string {
+ t.Helper()
+ fx.srv.boxReports.invalidate()
+ status, loc, body := get(t, browser, fx.ts.URL+"/a/"+fx.acct+"/apps/shop")
+ if status != http.StatusOK {
+ t.Fatalf("overview = %d -> %q\n%s", status, loc, body)
+ }
+ return runningTile(t, body)
+}
+
+func TestReplicaVisibilityPrefersLiveHealth(t *testing.T) {
+ fx, _, _, rec := replicaViewFx(t, "code-rv-live", 2)
+ browser := signInPaul(t, fx.consoleFixture)
+
+ // The report says two running; the hub says b2 is down.
+ hubSays(fx, rec, nil,
+ hubCopy(rec, "b1", "running", true, "v2", 2, 2),
+ hubCopy(rec, "b2", "down", false, "v1", 0, 2))
+ got := onlyShopHost(t, mustList(t, fx))
+ if got.DesiredCopies != 2 || len(got.Copies) != 2 {
+ t.Fatalf("listed %+v, want two copies of two", got)
+ }
+ if c := got.Copies[0]; c.Box != "b1" || c.State != "running" || !c.Healthy || c.Version != "v2" || c.BootID != "" {
+ t.Fatalf("b1 %+v, want running and healthy on v2, with no boot id", c)
+ }
+ if c := got.Copies[1]; c.Box != "b2" || c.State != "down" || c.Healthy {
+ t.Fatalf("b2 %+v, want down and not healthy, whatever the report says", c)
+ }
+ if got.Health != "Running" {
+ t.Fatalf("health %q, want Running while one copy is", got.Health)
+ }
+ if tile := copiesLine(t, fx, browser); !strings.Contains(tile, "1 of 2 copies running") {
+ t.Fatalf("overview tile, want 1 of 2 copies running:\n%s", tile)
+ }
+
+ // No hub reading: every copy unknown, never two healthy.
+ hubSays(fx, rec, errNoHubReading)
+ got = onlyShopHost(t, mustList(t, fx))
+ for _, c := range got.Copies {
+ if c.State != "unknown" || c.Healthy {
+ t.Fatalf("copy %+v with no hub reading, want unknown and not healthy", c)
+ }
+ }
+ if got.Health != healthUnknown {
+ t.Fatalf("health %q with no hub reading, want %q", got.Health, healthUnknown)
+ }
+ tile := copiesLine(t, fx, browser)
+ if strings.Contains(tile, "2 of 2") || !strings.Contains(tile, "0 of 2 copies running") {
+ t.Fatalf("overview tile with no hub reading:\n%s", tile)
+ }
+
+ // A reading for another lifetime, revision, account or fleet is not
+ // this record's: unknown again.
+ for name, mutate := range map[string]func(*replicas.Copy){
+ "lifetime": func(c *replicas.Copy) { c.Incarnation = strings.Repeat("0", 64) },
+ "revision": func(c *replicas.Copy) { c.AssignmentRevision++ },
+ "account": func(c *replicas.Copy) { c.Account = "baj" },
+ "fleet": func(c *replicas.Copy) { c.Fleet = "away" },
+ "box": func(c *replicas.Copy) { c.Box = "b9" },
+ } {
+ a, b := hubCopy(rec, "b1", "running", true, "v2", 2, 2), hubCopy(rec, "b2", "running", true, "v2", 2, 2)
+ mutate(&a)
+ mutate(&b)
+ hubSays(fx, rec, nil, a, b)
+ got = onlyShopHost(t, mustList(t, fx))
+ for _, c := range got.Copies {
+ if c.Healthy || c.State != "unknown" {
+ t.Fatalf("%s: copy %+v from a reading that is not this record's", name, c)
+ }
+ }
+ }
+}
+
+// mustList lists shop with no query.
+func mustList(t *testing.T, fx *interactiveFx) []listedInstance {
+ t.Helper()
+ rows, _ := listShop(t, fx, "")
+ return rows
+}
+
+// A slot no box holds is a missing copy with no box label, and the running
+// count is desired minus missing and unhealthy.
+func TestReplicaVisibilityShowsMissingSlots(t *testing.T) {
+ fx, _, _, rec := replicaViewFx(t, "code-rv-missing", 3)
+ browser := signInPaul(t, fx.consoleFixture)
+ hubSays(fx, rec, nil,
+ hubCopy(rec, "b1", "running", true, "v2", 1, 1),
+ hubCopy(rec, "b2", "running", true, "v2", 1, 1))
+ got := onlyShopHost(t, mustList(t, fx))
+ if got.DesiredCopies != 3 || len(got.Copies) != 3 {
+ t.Fatalf("listed %+v, want three copies", got)
+ }
+ if c := got.Copies[2]; c.Box != "" || c.State != "missing" || c.Healthy {
+ t.Fatalf("third copy %+v, want missing with no box", c)
+ }
+ if tile := copiesLine(t, fx, browser); !strings.Contains(tile, "2 of 3 copies running") {
+ t.Fatalf("overview tile, want 2 of 3 copies running:\n%s", tile)
+ }
+}
+
+// One copy keeps its legacy view: no copies, no socket read.
+func TestReplicaVisibilityOneCopyUnchanged(t *testing.T) {
+ fx, _, _, _ := replicaViewFx(t, "code-rv-one", 2)
+ replaceRecord(t, fx, func(r *provision.Record) { r.ReplicaAssignment = nil })
+ read := false
+ fx.srv.replicaHealth = func(context.Context) (map[string]replicas.Snapshot, error) {
+ read = true
+ return nil, nil
+ }
+ _, raw := listShop(t, fx, "")
+ if strings.Contains(raw, `"copies"`) || strings.Contains(raw, `"desired_copies"`) {
+ t.Fatalf("a one-copy record lists copies: %s", raw)
+ }
+ if read {
+ t.Fatal("a list with no replicated record read the hub")
+ }
+}
+
+func TestReplicaCopyListHasOneRowPerBox(t *testing.T) {
+ fx, _, _, rec := replicaViewFx(t, "code-rv-rows", 2)
+ hubSays(fx, rec, nil,
+ hubCopy(rec, "b1", "running", true, "v2", 2, 2),
+ hubCopy(rec, "b2", "failed", false, "v1", 1, 2))
+ got := onlyShopHost(t, mustList(t, fx))
+ if len(got.Copies) != 2 {
+ t.Fatalf("listed %+v, want two copies", got)
+ }
+ a, b := got.Copies[0], got.Copies[1]
+ if a.Box != "b1" || a.Version != "v2" || a.State != "running" || !a.Healthy || a.WorkersRunning != 2 || a.WorkersDeclared != 2 {
+ t.Fatalf("b1 row %+v", a)
+ }
+ if b.Box != "b2" || b.Version != "v1" || b.State != "failed" || b.Healthy || b.WorkersRunning != 1 || b.WorkersDeclared != 2 {
+ t.Fatalf("b2 row %+v", b)
+ }
+ // A health filter answers the host once, never once per copy.
+ rows, raw := listShop(t, fx, "?health=running")
+ if len(rows) != 1 {
+ t.Fatalf("health filter: %d objects, want the one host: %s", len(rows), raw)
+ }
+ onlyShopHost(t, rows)
+ if !strings.Contains(raw, `"total":1`) || !strings.Contains(raw, `"counts":{"Running":1}`) {
+ t.Fatalf("health filter counts a copy as an instance: %s", raw)
+ }
+ if strings.Contains(raw, "/run/carlos/sockets") {
+ t.Fatalf("a socket path left the console: %s", raw)
+ }
+}
+
+// TestReplicaRunAndTTYStartOnce pins what already makes a command exclusive
+// with two assigned boxes: the run door's claim and the session door's
+// attach each let exactly one box through, and the one that runs is the
+// one recorded.
+func TestReplicaRunAndTTYStartOnce(t *testing.T) {
+ fx, b1, b2, rec := replicaViewFx(t, "code-rv-once", 2)
+ t.Cleanup(func() { fx.srv.runRelays.relays.Wait() })
+ hubSays(fx, rec, nil, hubCopy(rec, "b1", "running", true, "v1", 0, 0), hubCopy(rec, "b2", "running", true, "v1", 0, 0))
+ bearers := map[string]string{"b1": b1, "b2": b2}
+
+ // Both boxes dial the run door at once.
+ id := postFleetRun(t, fx, okMeta())
+ g := runGrant(t, fx, id)
+ type dialed struct {
+ box string
+ ws *websocket.Conn
+ }
+ race := func(dial func(box string) (*websocket.Conn, error)) []dialed {
+ var mu sync.Mutex
+ var won []dialed
+ var wg sync.WaitGroup
+ for _, box := range []string{"b1", "b2"} {
+ wg.Go(func() {
+ if ws, err := dial(box); err == nil {
+ mu.Lock()
+ won = append(won, dialed{box, ws})
+ mu.Unlock()
+ }
+ })
+ }
+ wg.Wait()
+ return won
+ }
+ won := race(func(box string) (*websocket.Conn, error) {
+ return runBoxDial(t, fx, id, fleetHeader(g.Token, "home/"+box, bearers[box]))
+ })
+ runStarts := len(won)
+ if runStarts != 1 {
+ t.Fatalf("%d boxes took the run, want exactly 1", runStarts)
+ }
+ runner := won[0]
+ runHello(t, runner.ws, interactive.RunHello{Schema: 1, Run: id, Box: runner.box, Boot: "b00t"})
+ if p := runPicked(t, runner.ws); p.State != interactive.RunStatePicked || p.Box != runner.box {
+ t.Fatalf("RunPicked %+v, want picked by %s", p, runner.box)
+ }
+ runEndAck(t, runner.ws, runs.Result{Exit: 0, Box: runner.box})
+ if r := runState(t, fx, provision.RunDone); r.Box != runner.box {
+ t.Fatalf("the record says %q ran it, want %s", r.Box, runner.box)
+ }
+
+ // Both boxes dial the session door at once.
+ cli := ixStart(t, fx, fx.alice, ixOpenArgv())
+ sid, sg := ixSessionGrant(t, fx, ixHost)
+ won = race(func(box string) (*websocket.Conn, error) {
+ return boxDial(t, fx, sid, fleetHeader(sg.Token, "home/"+box, bearers[box]))
+ })
+ ttyStarts := len(won)
+ if ttyStarts != 1 {
+ t.Fatalf("%d boxes attached the session, want exactly 1", ttyStarts)
+ }
+ tty := won[0]
+ boxWant(t, tty.ws, interactive.KindOpen)
+ boxEnd(t, tty.ws, interactive.End{Reason: interactive.EndExited})
+ executorBox := endOf(t, boxWant(t, cli, interactive.KindEnd)).Box
+ if runStarts != 1 || ttyStarts != 1 || executorBox != tty.box {
+ t.Fatal("command targeting was not exclusive")
+ }
+}
+
+// restartShop asks for shop's app-wide restart as alice.
+func restartShop(t *testing.T, fx *interactiveFx) (int, string) {
+ t.Helper()
+ code, _, body := rawReq(t, http.MethodPost, fx.ts.URL+"/api/cli/apps/"+fx.acct+"/shop/restart", fx.alice, "")
+ return code, body
+}
+
+// restartTouched reports whether shop's restart generation exists.
+func restartTouched(t *testing.T, fx *interactiveFx) bool {
+ t.Helper()
+ _, _, err := fx.rel.Get(context.Background(), release.RestartGenKey(fx.acct, "shop"))
+ if err != nil && !errors.Is(err, os.ErrNotExist) {
+ t.Fatal(err)
+ }
+ return err == nil
+}
+
+// F2: an app-wide restart reaches every box serving the app on the same
+// serial move, so it would cycle every copy at once. It refuses while the
+// app has more than one copy of an instance, and writes nothing.
+func TestReplicaRestartRefusesCopies(t *testing.T) {
+ fx, _, _, _ := replicaViewFx(t, "code-rv-restart", 2)
+ if _, err := appconfig.SetCopies(context.Background(), fx.rel, fx.acct, "shop", 2); err != nil {
+ t.Fatal(err)
+ }
+ if code, body := restartShop(t, fx); code != http.StatusConflict || errorOf(t, body) != restartCopiesRefusal {
+ t.Fatalf("copies 2: %d %s, want 409 %q", code, body, restartCopiesRefusal)
+ }
+ // Scaling down: the count is 1 but the record still has two copies.
+ if _, err := appconfig.SetCopies(context.Background(), fx.rel, fx.acct, "shop", 1); err != nil {
+ t.Fatal(err)
+ }
+ if code, body := restartShop(t, fx); code != http.StatusConflict || errorOf(t, body) != restartCopiesRefusal {
+ t.Fatalf("two copies at count 1: %d %s, want 409", code, body)
+ }
+ if restartTouched(t, fx) {
+ t.Fatal("a refused restart touched the restart generation")
+ }
+ // A restart by environment is matched by every box, the copies' too.
+ fx.addRoute(t, registry.Route{Host: "relay.example.com", Kind: "instance", App: "shop", Account: fx.acct,
+ Channel: "stable", Provisioned: true, Status: "ready", Environment: "relay"})
+ code, _, body := rawReq(t, http.MethodPost, fx.ts.URL+"/api/cli/apps/"+fx.acct+"/shop/restart/scope", fx.alice, `{"environment":"relay"}`)
+ if code != http.StatusConflict || errorOf(t, body) != restartCopiesRefusal {
+ t.Fatalf("restart --environment with two copies: %d %s, want 409", code, body)
+ }
+ if code, _, body := rawReq(t, http.MethodPost, fx.ts.URL+"/api/cli/apps/"+fx.acct+"/shop/restart/scope", fx.alice, `{"environment":"relay","dry_run":true}`); code != http.StatusOK {
+ t.Fatalf("a dry run writes nothing and is not refused: %d %s", code, body)
+ }
+ // One copy left: the restart is requested as before.
+ replaceRecord(t, fx, func(r *provision.Record) {
+ r.ReplicaAssignment = &replicas.Assignment{Revision: r.ReplicaAssignment.Revision + 1, Desired: 1, Boxes: []string{"b1"}}
+ })
+ if code, body := restartShop(t, fx); code != http.StatusOK {
+ t.Fatalf("one copy: %d %s, want 200", code, body)
+ }
+ if !restartTouched(t, fx) {
+ t.Fatal("the restart was not requested")
+ }
+}
diff --git a/internal/console/server.go b/internal/console/server.go
index 3b0fc526a..9836aa896 100644
--- a/internal/console/server.go
+++ b/internal/console/server.go
@@ -66,6 +66,7 @@ import (
"github.com/carlosframework/platform/internal/registrar"
"github.com/carlosframework/platform/internal/registry"
"github.com/carlosframework/platform/internal/release"
+ "github.com/carlosframework/platform/internal/replicas"
"github.com/carlosframework/platform/internal/status"
"github.com/carlosframework/platform/internal/svcrole"
"github.com/carlosframework/platform/internal/telemetry"
@@ -1182,7 +1183,10 @@ type Server struct {
// `carlos db` door (apidb.go). NewServer points it at a small cache of
// lease.ReadReplicaClient values; tests point it at a file replica.
dbReplica func(ctx context.Context, prefix string) (replicaReader, error)
- dbClients dbReplicaCache
+ // replicaHealth reads the hub's live copy table (replicaview.go). nil is
+ // the agent's private snapshot socket; tests set a fixed table.
+ replicaHealth func(ctx context.Context) (map[string]replicas.Snapshot, error)
+ dbClients dbReplicaCache
// dbStreams bounds the db door's active file streams, and dbStreamIdle
// is how long one may go without moving a byte (apidb.go).
dbStreams *dbStreamLimits
@@ -4437,6 +4441,13 @@ func (s *Server) handleApp(w http.ResponseWriter, r *http.Request) {
boxes, _ := s.pageBoxReports(r.Context())
dbJoin := joinBoxes(boxes, time.Now())
p.Overview = assembleOverview(p.Detail, acct.Sqid, metrics, versions, dbJoin)
+ // The copy counts read the records this page view already holds
+ // (pageRecords' held read) and the hub's live table: no bucket cadence.
+ if recs, err := s.pageRecords(r.Context(), acct.Sqid, app); err != nil {
+ log.Printf("console: overview copies %s/%s: %v", acct.Sqid, app, err)
+ } else {
+ p.Overview.countCopies(s.replicaViewsLogged(r.Context(), recs))
+ }
// The diagram is drawn from the SAME tenant-filtered rows the Running tab
// renders, so the two can never disagree about which addresses exist or
// how they are doing — see flow.go's package comment for why it is not
diff --git a/internal/console/templates/app_overview.html b/internal/console/templates/app_overview.html
index df7a9df6f..0efeba245 100644
--- a/internal/console/templates/app_overview.html
+++ b/internal/console/templates/app_overview.html
@@ -33,6 +33,10 @@
<h2>Running</h2>
<p class="tile-value">{{if eq .InstanceTotal 0}}—{{else if and (eq .InstanceExpected 0) (eq .InstanceUnknown 0)}}Served{{else if .MetricsUnavailable}}?{{else if eq .InstanceCounted 0}}?{{else}}{{.InstanceReporting}} of {{.InstanceCounted}}{{end}}</p>
<p class="tile-detail">{{if eq .InstanceTotal 0}}nothing running yet{{else if and (eq .InstanceExpected 0) (eq .InstanceUnknown 0)}}static — the platform serves it, nothing to run{{else if or .MetricsUnavailable (and (eq .InstanceCounted 0) .InstanceUnknown)}}no data right now{{else if eq .InstanceCounted 0}}no readings for {{.InstanceNoReadings}} copies — stamp their units to see health{{else}}copies reporting{{if .InstanceAsleep}} · {{.InstanceAsleep}} asleep{{end}}{{if .InstanceNoReadings}} · {{.InstanceNoReadings}} no readings{{end}}{{end}}</p>
+ {{/* SR-4-C01 (provisional): the hub's live count of an app whose
+ instances run more than one copy. A copy with no live reading is
+ not counted as running. */}}
+ {{if .CopiesDesired}}<p class="tile-detail">{{.CopiesRunning}} of {{.CopiesDesired}} copies running</p>{{end}}
</a>
<a class="tile" href="{{$.Nav}}/apps/{{$.AppName}}/instances">
<h2>Resources</h2>
diff --git a/internal/provision/plan9_b8_census_test.go b/internal/provision/plan9_b8_census_test.go
index df6204556..5abd155f6 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 := statelessReplicas4Task2WriteCensusInventory()
+ inventory := statelessReplicas4Task3WriteCensusInventory()
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/stateless_replicas_4_task3_census_test.go b/internal/provision/stateless_replicas_4_task3_census_test.go
new file mode 100644
index 000000000..f0df23045
--- /dev/null
+++ b/internal/provision/stateless_replicas_4_task3_census_test.go
@@ -0,0 +1,37 @@
+package provision
+
+// statelessReplicas4Task3WriteCensusInventory is stateless replicas Plan 4
+// Task 3's review of the record-write census, layered on Task 2's.
+// Self-review only; the independent #280 verdict is the controller's.
+//
+// - Server.handleAPIInstanceList: joins the hub's live copy table
+// (replicaViews, a local socket read) to the records it already listed,
+// and overrides a replicated record's health word from it. It reads no
+// new record and writes none; its only record reference is the
+// unchanged instances literal.
+// - Server.handleBrowserRestart: the app-wide restart first asks
+// restartCopies, which reads the copies setting and, for an app that
+// set one, lists the app's records (listRecordsComplete, a read) and
+// refuses while any holds more than one box. No record write; the
+// reference is the unchanged instances literal of its redirects.
+// - No new record writer. The deferred run and session target writes are
+// not part of the trimmed task.
+func statelessReplicas4Task3WriteCensusInventory() []censusEntry {
+ entries := append([]censusEntry(nil), statelessReplicas4Task2WriteCensusInventory()...)
+ for _, r := range []censusEntry{
+ {"internal/console/apiinstances.go", "Server.handleAPIInstanceList", "key-site", "lit:instances", "5fc085b0bf1ff6fed54ceb3efd04c2ed1b819b937324a487fdd54c06d8e14f96"},
+ {"internal/console/browserrestart.go", "Server.handleBrowserRestart", "key-site", "lit:instances", "f06faf4afd6c437a3211a2b32084fd34aa7d9ba942ea3424bc7cb9e950abef55"},
+ } {
+ replaced := false
+ for i, e := range entries {
+ if e.File == r.File && e.Unit == r.Unit {
+ entries[i], replaced = r, true
+ break
+ }
+ }
+ if !replaced {
+ entries = append(entries, r)
+ }
+ }
+ return entries
+}
diff --git a/internal/provision/testdata/plan14-root-reads-chain.tsv b/internal/provision/testdata/plan14-root-reads-chain.tsv
index ad9a7680c..e6d29f3c5 100644
--- a/internal/provision/testdata/plan14-root-reads-chain.tsv
+++ b/internal/provision/testdata/plan14-root-reads-chain.tsv
@@ -176,3 +176,4 @@ plan14-root-reads-stateless-replicas-4-task2.tsv 40c909a853a761733e9f837d4c8336b
plan14-root-reads-stateless-replicas-4-task2-fix1.tsv 1a0605f79ac62c776bccc1ae8d166357b05c6acb56aeead59290e43b9cc67788
plan14-root-reads-stateless-replicas-4-task2-fix2.tsv 5f83de2e018b47543789a8dbe2cccb86b2d644fbe9ee5771e5d621704ae46e0b
plan14-root-reads-stateless-replicas-4-task2-fix3.tsv bd25367161555e8a9c5b0df079ad2d8eb648ebaeae3f407e6c638f2f7f01605b
+plan14-root-reads-stateless-replicas-4-task3.tsv bd25367161555e8a9c5b0df079ad2d8eb648ebaeae3f407e6c638f2f7f01605b
diff --git a/internal/provision/testdata/plan14-root-reads-stateless-replicas-4-task3.tsv b/internal/provision/testdata/plan14-root-reads-stateless-replicas-4-task3.tsv
new file mode 100644
index 000000000..74f521e79
--- /dev/null
+++ b/internal/provision/testdata/plan14-root-reads-stateless-replicas-4-task3.tsv
@@ -0,0 +1,3 @@
+# Census overlay stateless-replicas-4-task3, written by census-propose (#369). census-ruling-stateless-replicas-4-task3, approved on #280 before the merge; the approval card is docs/superpowers/notes/census-proposal-stateless-replicas-4-task3.md.
+# 0 body, 0 sites, 1 envelope: each changed unit re-frozen at its existing disposition with its claim appended.
+@coverage . 98ab956b35f7af4c07903323805a0c1ee34acf7068274036f4a0bfa51bb73b92