carlos / platform Public

Merge origin/main into rollup-tenant-tags (census re-proposed on main's chain)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev 8ec6d4c857faada94d17cda4459b6b9ac97cb4cc parent e2e9238parent 80343a5
25 files changed, +1,058 −130
  • docs/superpowers/notes/census-ha-p1a-433-claims.md +22 −0
  • docs/superpowers/notes/census-proposal-ha-p1a-433.md +34 −0
  • docs/superpowers/notes/census-proposal-rollup-tenant-tags.md +1 −1
  • docs/superpowers/notes/reviews/ASTRA-FINDINGS-ha-p1a-433-r1.md +36 −0
  • docs/superpowers/notes/reviews/ASTRA-FINDINGS-ha-p1a-433-r2.md +21 −0
  • docs/superpowers/notes/reviews/CODEX-REVIEW-BRIEF-ha-p1a-433-R1.md +30 −0
  • docs/superpowers/notes/reviews/CODEX-REVIEW-BRIEF-ha-p1a-433-R2.md +30 −0
  • internal/host/agent.go +1 −6
  • internal/host/agent_layout_test.go +87 −4
  • internal/host/edgesfile_test.go +3 −0
  • internal/host/egress_source_test.go +30 −0
  • internal/host/host_test.go +12 −0
  • internal/host/layoutleg.go +43 −0
  • internal/host/rootfsplacement.go +10 −7
  • internal/instancectl/peer_edge.go +115 −0
  • internal/instancectl/peer_edge_test.go +120 −0
  • internal/instancectl/peer_linux.go +20 −50
  • internal/provision/boxpools_test.go +53 −0
  • internal/provision/reconcile.go +41 −0
  • internal/provision/reconcile_eligibility_test.go +2 −0
  • internal/provision/testdata/plan14-root-reads-chain.tsv +2 −1
  • internal/provision/testdata/plan14-root-reads-ha-p1a-433.tsv +28 −0
  • internal/registry/claimrows.go +5 −2
  • internal/registry/ha_test.go +157 −0
  • internal/registry/registry.go +155 −59

CI passed — run details

diff --git a/docs/superpowers/notes/census-ha-p1a-433-claims.md b/docs/superpowers/notes/census-ha-p1a-433-claims.md
new file mode 100644
index 000000000..d2a5dacf4
--- /dev/null
+++ b/docs/superpowers/notes/census-ha-p1a-433-claims.md
@@ -0,0 +1,22 @@
+# CLAIMS for the root-read census, branch ha-p1a-dev-pair-433 (amadan #433: P1a follow-up fixes and the shared-pool token).
+# Format (AGENTS.md "The census"): <file>:<unit><TAB><what changed>. Lines starting with # are ignored.
+# Base: fc30b421 (origin/main, carries region HA P1a fd93024a).
+
+# Fix 1: root peer check (instance-control, uid 0)
+internal/instancectl/peer_linux.go:productionPeerOK root (carlos-instance-control.service): reads nothing now. The systemctl MainPID read moved verbatim to systemdEdgeMainPID, and the decision and its one-second cache moved to edgePeer.check (internal/instancectl/peer_edge.go, envelope re-pinned). Acceptance is unchanged: SO_PEERCRED uid carlos AND pid equal to the MainPID systemd reports for carlos-edge.service. New in edgePeer.check: a peer the cached answer refuses (a stale pid or a cached failure, #433) is checked once against a fresh read before the refusal, at most one forced read per 100 ms; the peer is accepted only if the fresh MainPID equals it, so nothing wider is accepted.
+internal/instancectl/peer_linux.go:systemdEdgeMainPID root (carlos-instance-control.service): the same exec productionPeerOK's closure ran before, moved out unchanged: systemctl show -p MainPID --value carlos-edge.service, fixed argv, 3 s timeout; output that does not parse is 0 (no MainPID), which edgePeer refuses. No input from a peer, tenant or agent reaches the argv.
+
+# Fix 2: root reads routes before the agent migrates (registry, read-only child as carlos; read-write in the agent)
+internal/registry/registry.go:Registry.List the registry's SQLite side as carlos (agent, registry child, and root's read-only registry child via openServiceRegistryReadOnly): calls readCols on the same connection before the same SELECT ... FROM routes ORDER BY host. A read-write registry gets routeCols unchanged; a read-only one gets routeCols with any column routeAddedColumns adds that the table lacks read as its migration default ("0 AS ha"), so root's egress naming and source work before the new agent migrates (#433). Decides nothing; no read added.
+internal/registry/registry.go:Registry.Get same identities as List: +registry:sql is r.sql handed to readCols, the same connection the SELECT already used; same SELECT ... WHERE host = ? with the select list readCols returns (routeCols for a read-write registry). Root's instanceRegistryHostApp and instanceRegistryHostRuntime read Get through the read-only child and now work before the migration too.
+internal/registry/registry.go:Registry.migrate the registry's SQLite side as carlos (agent, registry child; a box CLI verb that opens the registry directly runs it as whoever runs it), on every registry open: the ALTER TABLE routes statements are now built from the one migration definition routeAddedColumns (addedColumn name, type, default; review r1 P2): for each entry without the Claim mark, "ALTER TABLE routes ADD COLUMN " + spec(), byte for byte the statements main runs, in main's order, under the same duplicate-column rule. +registry:Claim is that mark, +whole:addedColumn the struct. Every name, type and default is an in-binary literal; no statement added, removed or changed; no read added.
+internal/registry/registry.go:Registry.readCols new; the registry's SQLite side as carlos. For a read-write registry returns routeCols and reads nothing. For a read-only one (registry:readOnly), one SELECT name FROM pragma_table_info('routes') over the registry's own mode=ro, query_only connection. The names read are only compared with the in-binary routeCols and routeAddedColumns lists, never put into SQL: the select list is built from routeCols and the in-binary defaults (the empty string literal or 0, parsed from routeAddedColumns by a fixed regexp). An agent-written table can only make a known added column read as its default, which is what the migration gives it; a missing CREATE column is not stood in for and the read fails as before.
+
+# Fix 3: CARLOS_POOLS token (agent, carlos)
+internal/host/agent.go:provisionTickConfig the agent (carlos-edge.service, user carlos) and the edges file loop's eligibility: the same CARLOS_POOLS read, now parsed by provision.ParseBoxPools (internal/provision, envelope re-pinned), the one parser boxPools also uses. "@shared" (provision.SharedPoolToken, never a valid pool name) is the shared "" pool; other tokens are literal as before; empty elements and repeats dropped. No read added.
+
+# Review r1 P2 (Astra): every migration-added column from one definition
+internal/registry/claimrows.go:Registry.migrateClaimOwnership the registry's SQLite side as carlos, on every registry open (called from migrate): the four claim ownership ALTERs for routes and timers come from routeAddedColumns' Claim-marked entries (claim_incarnation TEXT, claim_stamp INTEGER, claim_owner TEXT, claim_row_id TEXT, each NOT NULL DEFAULT the empty string or 0), as "ALTER TABLE " + table + " ADD COLUMN " + spec(): the same statements as main's inline list, same order, same tables, same duplicate-column rule. +registry:Claim is the mark, +whole:addedColumn the struct; in-binary literals only; no read added.
+internal/registry/registry.go:addedColumn.spec new; pure: joins the entry's in-binary Name, Type and Default into "<name> <type> NOT NULL DEFAULT <default>". +registry:Name/Type/Default are the struct's own fields; it reads nothing from the database, a file or an input.
+internal/registry/registry.go:addedRouteColumnDefaults new as a census unit (it replaces the regexp parse of the ALTER texts): pure, maps each routeAddedColumns entry's in-binary Name to its in-binary Default, now including the four claim ownership columns, so readCols stands their defaults in for a read-only registry that predates migrateClaimOwnership. Reads nothing from the database, a file or an input.
+# changed registry schema: the registry struct field set gains addedColumn's Name, Type, Default and Claim (an in-binary migration definition, not a table column); no route, timer or archive field changed. Re-pinned by census-propose.
diff --git a/docs/superpowers/notes/census-proposal-ha-p1a-433.md b/docs/superpowers/notes/census-proposal-ha-p1a-433.md
new file mode 100644
index 000000000..d39629b4a
--- /dev/null
+++ b/docs/superpowers/notes/census-proposal-ha-p1a-433.md
@@ -0,0 +1,34 @@
+# Census approval: ha-p1a-433
+
+Ruling `census-ruling-ha-p1a-433`. The independent reviewer approves or rejects every change below, 8 with a new disposition; nothing goes to the census owner (Paul, #280, 2026-10-26).
+
+| unit | change | read sites | what changed |
+|---|---|---|---|
+| `internal/host/agent.go` `provisionTickConfig` | body | unchanged (2) | the agent (carlos-edge.service, user carlos) and the edges file loop's eligibility: the same CARLOS_POOLS read, now parsed by provision.ParseBoxPools (internal/provision, envelope re-pinned), the one parser boxPools also uses. "@shared" (provision.SharedPoolToken, never a valid pool name) is the shared "" pool; other tokens are literal as before; empty elements and repeats dropped. No read added. |
+| `internal/registry/registry.go` `Registry.List` | body | unchanged (16) | the registry's SQLite side as carlos (agent, registry child, and root's read-only registry child via openServiceRegistryReadOnly): calls readCols on the same connection before the same SELECT ... FROM routes ORDER BY host. A read-write registry gets routeCols unchanged; a read-only one gets routeCols with any column routeAddedColumns adds that the table lacks read as its migration default ("0 AS ha"), so root's egress naming and source work before the new agent migrates (#433). Decides nothing; no read added. |
+| `internal/registry/registry.go` `Registry.Get` | sites | +registry:sql | same identities as List: +registry:sql is r.sql handed to readCols, the same connection the SELECT already used; same SELECT ... WHERE host = ? with the select list readCols returns (routeCols for a read-write registry). Root's instanceRegistryHostApp and instanceRegistryHostRuntime read Get through the read-only child and now work before the migration too. |
+
+Envelopes re-pinned: `internal/host`, `internal/instancectl`, `internal/provision`, `internal/registry`.
+
+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. Escalate 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. An escalation goes to the census owner as a decision.
+
+Recorded dispositions, which each change must still satisfy:
+
+- `internal/host/agent.go` `provisionTickConfig`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=J4;basis=root-input
+- `internal/registry/registry.go` `Registry.List`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=J1,J4;basis=route-and-input;rev3=census-ruling-instance-egress-sizes-328-329;identity=the registry's SQLite side, as carlos: in the agent (/opt/carlos/carlos agent, carlos-edge.service) and in the registry child (carlos __registry-child, which a root pass forks as the service user), and now also in the read-only registry child (carlos __registry-child read-only, which root's instance control forks as the service user through openServiceRegistryReadOnly);basis=#328 plan 2 Task 13 fix (4e7bbc4b): a read-only registry (OpenReadOnly sets readOnly) lists over its own mode=ro, query_only connection (registry:sql, one site, r.sql) instead of a fresh sql.Open on its path, which opens read-write; registry:readOnly (one site) is the branch on that flag. A read-write registry keeps main's fresh connection. The same SELECT of routeCols from routes; it serves root's egress source (listRegistryReadOnly) every row; it decides nothing
+- `internal/registry/registry.go` `Registry.Get`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=J1,J4;basis=route-and-input
+
+New dispositions, which census-propose wrote and the reviewer checks against the unit's reads and the diff:
+
+- new `internal/instancectl/peer_linux.go:systemdEdgeMainPID`: reads +file:CommandContext; written legacy, accepted-legacy, frozen
+- new `internal/registry/registry.go:Registry.readCols`: reads +file:Query, +registry:readOnly; written legacy, accepted-legacy, frozen
+- new `internal/registry/registry.go:addedColumn.spec`: reads +registry:Default, +registry:Name, +registry:Type; written legacy, accepted-legacy, frozen
+- new `internal/registry/registry.go:addedRouteColumnDefaults`: reads +registry:Default, +registry:Name, +whole:addedColumn; written legacy, accepted-legacy, frozen
+- other `changed registry schema`: closed only if it is the registry schema (re-pinned)
+- quiet `internal/instancectl/peer_linux.go:productionPeerOK`: reads nothing now; retired while it reads nothing (or its row keeps no sites)
+- reads `internal/registry/claimrows.go:Registry.migrateClaimOwnership`: +registry:Claim, +whole:addedColumn; keeps legacy, task accepted-legacy
+- reads `internal/registry/registry.go:Registry.migrate`: +registry:Claim, +whole:addedColumn; keeps legacy, task accepted-legacy
+
+Seal: `5192052a23d2fdd6f5d48b5617fe28a9bb03458e1e931c060fbdc42c3d627927` → `f8acbc0dd8828636e3f73d9afd0e539d3dfd1346e0232d91903c33d6eb27d820`.
+
+Overlay: `internal/provision/testdata/plan14-root-reads-ha-p1a-433.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`.
diff --git a/docs/superpowers/notes/census-proposal-rollup-tenant-tags.md b/docs/superpowers/notes/census-proposal-rollup-tenant-tags.md
index 0cf7769e5..f50ea83f9 100644
--- a/docs/superpowers/notes/census-proposal-rollup-tenant-tags.md
+++ b/docs/superpowers/notes/census-proposal-rollup-tenant-tags.md
@@ -6,6 +6,6 @@ Envelopes re-pinned: `internal/metrics`.
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. Escalate 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. An escalation goes to the census owner as a decision.
-Seal: `5192052a23d2fdd6f5d48b5617fe28a9bb03458e1e931c060fbdc42c3d627927` → `5192052a23d2fdd6f5d48b5617fe28a9bb03458e1e931c060fbdc42c3d627927`.
+Seal: `f8acbc0dd8828636e3f73d9afd0e539d3dfd1346e0232d91903c33d6eb27d820` → `f8acbc0dd8828636e3f73d9afd0e539d3dfd1346e0232d91903c33d6eb27d820`.
Overlay: `internal/provision/testdata/plan14-root-reads-rollup-tenant-tags.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`.
diff --git a/docs/superpowers/notes/reviews/ASTRA-FINDINGS-ha-p1a-433-r1.md b/docs/superpowers/notes/reviews/ASTRA-FINDINGS-ha-p1a-433-r1.md
new file mode 100644
index 000000000..e9428b8ac
--- /dev/null
+++ b/docs/superpowers/notes/reviews/ASTRA-FINDINGS-ha-p1a-433-r1.md
@@ -0,0 +1,36 @@
+Reviewed `fc30b421..a3650c4c2eca917c2c2cce2c2ffc217114d37f32`, round 1.
+
+**P1: none found.**
+
+**P2 — Registry: fallback omits four migration-added columns.**
+`readCols` gets defaults only from `routeAddedColumns` ([registry.go:1135](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/ha-p1a-dev-pair-433/internal/registry/registry.go:1135)). That list excludes `claim_incarnation`, `claim_stamp`, `claim_owner`, and `claim_row_id`, added separately by [claimrows.go:39](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/ha-p1a-dev-pair-433/internal/registry/claimrows.go:39). All four remain in `routeCols`.
+
+A registry predating that migration still makes both `List` and `Get` fail with `no such column`, contrary to check 3’s requirement to tolerate every migration-added column. An in-memory SQLite probe using the source’s SQL reproduced this for each omitted column. The specific missing-`ha` case succeeds.
+
+Fix: include all four defaults through a shared migration definition and extend the compatibility test to remove each migration-added column independently. The current test checks the fallback list against itself, so it misses these omissions.
+
+**Fault family:** read-only registry compatibility before migration.
+
+**P3: none found.**
+
+Census decisions below approve the trust boundaries and dispositions at this commit; the P2 concerns compatibility completeness.
+
+| Unit or envelope | Class | Verdict | Lines read and basis |
+|---|---|---|---|
+| `provisionTickConfig` | body | APPROVE | `internal/host/agent.go:3490–3519`; same environment inputs, shared parser. |
+| `Registry.List` | body | APPROVE | `internal/registry/registry.go:1065–1102`; read-only connection retained; fixed select identifiers. |
+| `Registry.migrate` | body | APPROVE | `internal/registry/registry.go:646–830`; all 52 extracted statements retain their text and order. |
+| `Registry.Get` | sites | APPROVE | `internal/registry/registry.go:1153–1171`; same connection and parameterized host predicate. |
+| `systemdEdgeMainPID` | new, accepted-legacy | APPROVE | `internal/instancectl/peer_linux.go:74–85`; fixed command and arguments, three-second timeout; invalid answers refused by `readLocked`. |
+| `Registry.readCols` | new, accepted-legacy | APPROVE | `internal/registry/registry.go:703–715,1112–1150`; schema names only control membership checks; SQL comes from binary literals. |
+| `productionPeerOK` | quiet | APPROVE | `internal/instancectl/peer_linux.go:47–70`; scanned command read moved to the separately recorded unit; UID and PID checks remain. |
+| `internal/host` | envelope | APPROVE | `agent.go:635–725,3490–3519`; `layoutleg.go:355–469`; `rootfsplacement.go:149–169,309–321`. Retries precede recovery and startup; unswept fallback and ownership refusal remain. |
+| `internal/instancectl` | envelope | APPROVE | `peer_edge.go:27–115`; `peer_linux.go:22–85`; `server.go:315–365`. Fresh acceptance requires exact PID equality; forced reads are limited; production acceptance is serial. |
+| `internal/provision` | envelope | APPROVE | `reconcile.go:2894–2955`; `provision.go:875`. Only exact `@shared` maps to the shared pool; invalid nonempty tokens remain literal. |
+| `internal/registry` | envelope | APPROVE | `registry.go:607–624,646–830,1017–1171`; `readonly.go:11–25`; `claimrows.go:39–51`. Read-write migration behavior is unchanged; no database-supplied identifier enters generated SQL. |
+
+All four envelope hashes and six recorded function-body hashes match the proposal. `git diff --check` passed. Go tests could not start because the read-only sandbox denied build-directory creation; the SQLite probe is not a Go test result. Network restrictions prevented retrieving #433 or recording decisions on #280. No files changed.
+
+Apply the P2 without reopening the review, retaining the required census and changed-root-behavior checks within this round.
+
+**READY AFTER FIXES**
\ No newline at end of file
diff --git a/docs/superpowers/notes/reviews/ASTRA-FINDINGS-ha-p1a-433-r2.md b/docs/superpowers/notes/reviews/ASTRA-FINDINGS-ha-p1a-433-r2.md
new file mode 100644
index 000000000..5f664b43b
--- /dev/null
+++ b/docs/superpowers/notes/reviews/ASTRA-FINDINGS-ha-p1a-433-r2.md
@@ -0,0 +1,21 @@
+Reviewed `a3650c4c..3ffbf984a669778ea4fcb8e5d362e1f368787334`, scoped round 2. Earlier approvals remain unchanged.
+
+**P1: none found.**
+**P2: none found.** The four omitted claim columns now share the migration definition and receive their correct fallback defaults.
+
+**P3 — Census documentation:** [census-ha-p1a-433-claims.md:13](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/ha-p1a-dev-pair-433/docs/superpowers/notes/census-ha-p1a-433-claims.md:13) still describes defaults parsed by a regexp; the overlay repeats this description. Readers could mistake the removed parser for a validation boundary. Follow-up: describe the literal `addedColumn` definitions instead. **Fault family:** census explanation accuracy. No further review round needed.
+
+| Unit or envelope | Class | Verdict | Lines read and basis |
+|---|---|---|---|
+| `addedColumn.spec` | new, accepted-legacy | APPROVE | `internal/registry/registry.go:646–720`; joins binary literals only. |
+| `addedRouteColumnDefaults` | new, accepted-legacy | APPROVE | `internal/registry/registry.go:661–731,1130–1167`; all 56 added columns covered; database-provided names never enter SQL. |
+| `Registry.migrate` | reads | APPROVE | `internal/registry/registry.go:736–848`; same 52 statements, ordering and error handling. |
+| `Registry.migrateClaimOwnership` | reads | APPROVE | `internal/registry/claimrows.go:39–55`; same four definitions, both tables and duplicate-column handling. |
+| Registry schema | other | APPROVE | `internal/registry/registry.go:646–649`; field inventory adds only `Claim`, `Default`, `Type`; `Name` already existed. No stored schema change. |
+| `internal/registry` | envelope | APPROVE | Above ranges; `registry.go:1083–1189`, `readonly.go:11–25`, `ha_test.go:107–202`. Read-only restrictions remain; no new untrusted SQL or root authority. |
+
+Verified migration statement equivalence, all four changed function fingerprints, the registry envelope and cumulative census seals. An in-memory SQLite probe passed with each added column absent individually and all 56 absent together.
+
+Targeted Go tests could not start: the read-only sandbox blocked build-directory creation. Network restrictions prevented retrieving #433; review relied on the brief. No files changed.
+
+**READY**
\ No newline at end of file
diff --git a/docs/superpowers/notes/reviews/CODEX-REVIEW-BRIEF-ha-p1a-433-R1.md b/docs/superpowers/notes/reviews/CODEX-REVIEW-BRIEF-ha-p1a-433-R1.md
new file mode 100644
index 000000000..ca15574ae
--- /dev/null
+++ b/docs/superpowers/notes/reviews/CODEX-REVIEW-BRIEF-ha-p1a-433-R1.md
@@ -0,0 +1,30 @@
+# Review brief: HA P1a #433 fixes and the shared-pool token (code + census), round 1 of 3
+
+Repo carlos/platform, branch `ha-p1a-dev-pair-433`, the commit named in the reviewer's prompt.
+Under review: the diff `fc30b421..<that commit>` (code, tests) AND its census proposal (`docs/superpowers/notes/census-proposal-ha-p1a-433.md`, overlay `internal/provision/testdata/plan14-root-reads-ha-p1a-433.tsv`, claims `docs/superpowers/notes/census-ha-p1a-433-claims.md`).
+Authorities: main's code; the approved spec `docs/superpowers/specs/2026-10-26-region-ha-without-claims-design.md` (rev 6.1); AGENTS.md "The census: the reviewer decides". Problem statement: amadan discussion #433.
+
+You are the independent reviewer (Astra; the author is Claude) for both the code and the census. You decide every census class.
+
+## Fixed: do not re-argue
+- Paul's rulings: fix #433; add a reserved token so a box can serve the shared pool plus a named pool (dev HA pair "hapair" on two IE dev boxes, ordinary instances stay one-box).
+
+## What to check
+1. Root peer check (`internal/instancectl/peer_edge.go`, `peer_linux.go`): the re-read of systemd's MainPID on a mismatch accepts ONLY a peer whose pid equals the fresh MainPID; nothing wider; rate limit sound; no TOCTOU that lets another process in.
+2. Agent startup sweep retry (`internal/host/layoutleg.go` `startActivator`): bounded; strictly before recovery and any wake; never a sweep after wakes may start; unswept fallback unchanged.
+3. Registry read-only column tolerance (`Registry.readCols`, `List`, `Get`): root reads every migration-added column as its default when absent; the agent's read-write path unchanged; no SQL built from untrusted input.
+4. `provision.ParseBoxPools` and `@shared`: one parser for both call sites; `@shared` can never be a pool name; a typo can never widen a box to the shared pool; serves_shared_pool consistent.
+5. Census: for every unit and envelope on the card, a verdict citing the lines read; reject if root can now open, run, query or follow anything new from a path or input a tenant, an app or a box agent can create, write or name, or if a check root relies on is weakened.
+
+## Severity
+- **P1**: unsafe (for root, single writer, or tenancy), would not compile, a test fails, or it would not work. Blocks merge.
+- **P2**: wrong or missing. Fixed without reopening this review.
+- **P3**: clarity. Follow-up list only.
+
+## Output
+Findings ranked P1, P2, P3 (area, problem, evidence file:line, failure scenario, fix, fault family), then the census table (unit, class, APPROVE/REJECT, lines read). End with exactly one verdict:
+- **READY**: no P1 and no P2.
+- **READY AFTER FIXES**: no P1; listed P2s fixed without another round.
+- **NOT READY**: one or more P1s, listed.
+
+Do not edit files. Do not spawn Anthropic-model reviewers or subagents of your own. Do not run the full test suites. Leave GOCACHE unset.
diff --git a/docs/superpowers/notes/reviews/CODEX-REVIEW-BRIEF-ha-p1a-433-R2.md b/docs/superpowers/notes/reviews/CODEX-REVIEW-BRIEF-ha-p1a-433-R2.md
new file mode 100644
index 000000000..bcb0d7ec4
--- /dev/null
+++ b/docs/superpowers/notes/reviews/CODEX-REVIEW-BRIEF-ha-p1a-433-R2.md
@@ -0,0 +1,30 @@
+# Review brief: HA P1a #433 fixes and the shared-pool token (code + census), round 2 of 3 (scoped)
+
+Repo carlos/platform, branch `ha-p1a-dev-pair-433`, the commit named in the reviewer's prompt.
+Under review (SCOPED): the P2 fix and census update only, `85db2687` and `961f1e14` (diff `a3650c4c..<that commit>`). Round 1 (READY AFTER FIXES, P2: read-only fallback omitted four claim columns) approved every other unit; do not re-review those. Census units changed: new `addedColumn.spec`, `addedRouteColumnDefaults`; changed `Registry.migrate`, `Registry.migrateClaimOwnership`; other: registry schema re-pin; envelope `internal/registry`.
+Authorities: main's code; the approved spec `docs/superpowers/specs/2026-10-26-region-ha-without-claims-design.md` (rev 6.1); AGENTS.md "The census: the reviewer decides". Problem statement: amadan discussion #433.
+
+You are the independent reviewer (Astra; the author is Claude) for both the code and the census. You decide every census class.
+
+## Fixed: do not re-argue
+- Paul's rulings: fix #433; add a reserved token so a box can serve the shared pool plus a named pool (dev HA pair "hapair" on two IE dev boxes, ordinary instances stay one-box).
+
+## What to check
+1. Root peer check (`internal/instancectl/peer_edge.go`, `peer_linux.go`): the re-read of systemd's MainPID on a mismatch accepts ONLY a peer whose pid equals the fresh MainPID; nothing wider; rate limit sound; no TOCTOU that lets another process in.
+2. Agent startup sweep retry (`internal/host/layoutleg.go` `startActivator`): bounded; strictly before recovery and any wake; never a sweep after wakes may start; unswept fallback unchanged.
+3. Registry read-only column tolerance (`Registry.readCols`, `List`, `Get`): root reads every migration-added column as its default when absent; the agent's read-write path unchanged; no SQL built from untrusted input.
+4. `provision.ParseBoxPools` and `@shared`: one parser for both call sites; `@shared` can never be a pool name; a typo can never widen a box to the shared pool; serves_shared_pool consistent.
+5. Census: for every unit and envelope on the card, a verdict citing the lines read; reject if root can now open, run, query or follow anything new from a path or input a tenant, an app or a box agent can create, write or name, or if a check root relies on is weakened.
+
+## Severity
+- **P1**: unsafe (for root, single writer, or tenancy), would not compile, a test fails, or it would not work. Blocks merge.
+- **P2**: wrong or missing. Fixed without reopening this review.
+- **P3**: clarity. Follow-up list only.
+
+## Output
+Findings ranked P1, P2, P3 (area, problem, evidence file:line, failure scenario, fix, fault family), then the census table (unit, class, APPROVE/REJECT, lines read). End with exactly one verdict:
+- **READY**: no P1 and no P2.
+- **READY AFTER FIXES**: no P1; listed P2s fixed without another round.
+- **NOT READY**: one or more P1s, listed.
+
+Do not edit files. Do not spawn Anthropic-model reviewers or subagents of your own. Do not run the full test suites. Leave GOCACHE unset.
diff --git a/internal/host/agent.go b/internal/host/agent.go
index 811b0ee89..cb6cb3528 100644
--- a/internal/host/agent.go
+++ b/internal/host/agent.go
@@ -3489,12 +3489,7 @@ func domainsTickConfig(getenv func(string) string, publicIP string) (domains.Con
// record's own "no-inbound" placement request — see ReconcileConfig.Inbound.
func provisionTickConfig(getenv func(string) string) provision.ReconcileConfig {
region := strings.TrimSpace(getenv("CARLOS_REGION"))
- var pools []string
- for _, p := range strings.Split(getenv("CARLOS_POOLS"), ",") {
- if p = strings.TrimSpace(p); p != "" {
- pools = append(pools, p)
- }
- }
+ pools := provision.ParseBoxPools(getenv("CARLOS_POOLS"))
dd := getenv("CARLOS_DATA_DIR")
if dd == "" {
dd = "/data"
diff --git a/internal/host/agent_layout_test.go b/internal/host/agent_layout_test.go
index 849a38bc0..b354e7861 100644
--- a/internal/host/agent_layout_test.go
+++ b/internal/host/agent_layout_test.go
@@ -3,6 +3,7 @@ package host
import (
"context"
"errors"
+ "fmt"
"os"
"path/filepath"
"reflect"
@@ -244,16 +245,33 @@ func TestLayoutLegNeverLosesAKick(t *testing.T) {
}
}
+// fastSweepRetries makes startActivator's retry waits a millisecond each
+// for one test, and puts them back after it.
+func fastSweepRetries(t *testing.T) {
+ t.Helper()
+ backoff, window := startupSweepBackoff, startupSweepWindow
+ startupSweepBackoff = []time.Duration{time.Millisecond, time.Millisecond, time.Millisecond, time.Millisecond}
+ startupSweepWindow = time.Minute
+ t.Cleanup(func() { startupSweepBackoff, startupSweepWindow = backoff, window })
+}
+
// Recovery runs after the startup unit sweep and before the activator
-// starts, and it runs even when the sweep failed, told so.
+// starts, and it runs even when the sweep failed, told so. A sweep that
+// keeps failing is tried once and retried len(startupSweepBackoff) times
+// first (#433).
func TestStartActivatorRecoversAfterTheSweepAndBeforeStart(t *testing.T) {
+ fastSweepRetries(t)
for _, tc := range []struct {
name string
sweepErr error
swept bool
+ sweeps int
}{
- {"sweep ok", nil, true},
- {"sweep failed", errors.New("channel down"), false},
+ {"sweep ok", nil, true, 1},
+ {"sweep failed", errors.New("channel down"), false, 5},
+ // No control socket at all: a box without the channel, not a
+ // refusal that may clear, so it is not retried.
+ {"no socket", fmt.Errorf("instance control socket /run/x.sock: %w", os.ErrNotExist), false, 1},
} {
t.Run(tc.name, func(t *testing.T) {
var events []string
@@ -262,7 +280,11 @@ func TestStartActivatorRecoversAfterTheSweepAndBeforeStart(t *testing.T) {
func(context.Context) error { events = append(events, "sweep"); return tc.sweepErr },
func(_ context.Context, swept bool) { events = append(events, "recover"); gotSwept = swept },
func() { events = append(events, "start") })
- if want := []string{"sweep", "recover", "start"}; !reflect.DeepEqual(events, want) {
+ var want []string
+ for range tc.sweeps {
+ want = append(want, "sweep")
+ }
+ if want = append(want, "recover", "start"); !reflect.DeepEqual(events, want) {
t.Fatalf("order = %v, want %v", events, want)
}
if gotSwept != tc.swept {
@@ -272,6 +294,67 @@ func TestStartActivatorRecoversAfterTheSweepAndBeforeStart(t *testing.T) {
}
}
+// #433: root refused the new agent's first call, the startup sweep,
+// because its view of the edge's main pid lagged the restart. The sweep is
+// retried before anything can wake, so the box counts as swept
+// (seedSweptAtStart, which same-box recovery of an HA host needs) and the
+// activator starts only after the sweep that succeeded.
+func TestStartupSweepRetriesARefusalBeforeAnyWake(t *testing.T) {
+ fastSweepRetries(t)
+ prev := seedSweptAtStart.Load()
+ t.Cleanup(func() { seedSweptAtStart.Store(prev) })
+ seedSweptAtStart.Store(false)
+ var events []string
+ sweeps := 0
+ done := activatorStart{
+ Sweep: func(context.Context) error {
+ sweeps++
+ events = append(events, "sweep")
+ if sweeps == 1 {
+ return errors.New("instance control socket /run/carlos/control.sock: EOF")
+ }
+ return nil
+ },
+ Recover: func(_ context.Context, swept bool) *layout.Pass {
+ seedSweptAtStart.Store(swept)
+ events = append(events, "recover")
+ return nil
+ },
+ Publish: func(*layout.Pass) {},
+ Start: func() {
+ if !seedSweptAtStart.Load() {
+ t.Error("the activator started with the box unswept")
+ }
+ events = append(events, "start")
+ },
+ Ready: func() { events = append(events, "ready") },
+ Routes: func() ([]registry.Route, error) { return nil, nil },
+ }.Run(t.Context())
+ <-done
+ if want := []string{"sweep", "sweep", "recover", "start", "ready"}; !reflect.DeepEqual(events, want) {
+ t.Fatalf("events = %v, want %v", events, want)
+ }
+ if !seedSweptAtStart.Load() {
+ t.Fatal("seedSweptAtStart false after the retried sweep succeeded")
+ }
+}
+
+// The retries stop at the window: a sweep that hangs to its own deadline
+// is not tried again, so the box never waits minutes before it serves.
+func TestStartupSweepRetriesStopAtTheWindow(t *testing.T) {
+ fastSweepRetries(t)
+ startupSweepWindow = 0
+ sweeps := 0
+ var gotSwept = true
+ startActivator(context.Background(),
+ func(context.Context) error { sweeps++; return errors.New("refused") },
+ func(_ context.Context, swept bool) { gotSwept = swept },
+ func() {})
+ if sweeps != 1 || gotSwept {
+ t.Fatalf("sweeps = %d, swept = %v; want one sweep, unswept", sweeps, gotSwept)
+ }
+}
+
// The intent recovery runs under at start: "" when none applies, the
// recorded mode when one does, and IntentUnreadable whenever the box
// cannot be sure, which holds a completed revert fenced.
diff --git a/internal/host/edgesfile_test.go b/internal/host/edgesfile_test.go
index 9d4ec950f..c16dfca27 100644
--- a/internal/host/edgesfile_test.go
+++ b/internal/host/edgesfile_test.go
@@ -1264,6 +1264,9 @@ func TestEdgesFileEligibilityFollowsTheReconcileConfig(t *testing.T) {
{"", "", true, true},
{"tito", "", false, true},
{",tito", "", false, true},
+ {"@shared,hapair", "", true, true},
+ {"@shared", "", true, true},
+ {"cohort1,hapair", "", false, true},
{"", "none", true, false},
{"tito", "NONE", false, false},
}
diff --git a/internal/host/egress_source_test.go b/internal/host/egress_source_test.go
index 6c21baeba..3772ec691 100644
--- a/internal/host/egress_source_test.go
+++ b/internal/host/egress_source_test.go
@@ -3,6 +3,7 @@ package host
import (
"context"
"crypto/ed25519"
+ "database/sql"
"encoding/json"
"errors"
"io/fs"
@@ -888,3 +889,32 @@ func TestRegistryEgressSourceCarriesTheRowTenant(t *testing.T) {
tenant("not nested", p, "abc", "shop")
tenant("under claims", readPolicy(t, claimsEgressSource(), "shop-a.example.com"), "", "")
}
+
+// #433: at the upgrade to region HA P1a root named slices from the
+// registry before the new agent's migration added routes.ha, and logged
+// "egress: naming slices: ... no such column: ha". Root's reads (the
+// slice names and the allow source) work on a registry the old agent
+// left, without the column.
+func TestRootEgressReadsARegistryWithoutTheHAColumn(t *testing.T) {
+ reg, dd := egressRegistry(t)
+ clock := &testClock{now: time.Date(2026, 10, 26, 21, 30, 0, 0, time.UTC)}
+ upsertRows(t, reg, nestedRow(dd, "shop-a.example.com"), nestedRow(dd, "shop-b.example.com"))
+ setAllow(t, reg, "shop-a.example.com", "10.0.5.20", unixText(clock.Now().Add(time.Hour)))
+ db, err := sql.Open("sqlite", reg.Path())
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := db.Exec(`ALTER TABLE routes DROP COLUMN ha`); err != nil {
+ t.Fatal(err)
+ }
+ db.Close()
+
+ hosts, err := registryEgressHosts(dd)()
+ if err != nil {
+ t.Fatalf("naming slices without routes.ha: %v", err)
+ }
+ if want := []string{"shop-a.example.com", "shop-b.example.com"}; !reflect.DeepEqual(hosts, want) {
+ t.Fatalf("hosts = %v, want %v", hosts, want)
+ }
+ wantPolicy(t, readPolicy(t, testEgressSource(t, dd, clock.Now), "shop-a.example.com"), instancectl.EgressPolicy{Allow: []string{"10.0.5.20"}})
+}
diff --git a/internal/host/host_test.go b/internal/host/host_test.go
index 872e958ea..d96d2c955 100644
--- a/internal/host/host_test.go
+++ b/internal/host/host_test.go
@@ -896,6 +896,18 @@ func TestProvisionTickConfig(t *testing.T) {
t.Errorf("Pools = %v, want empties dropped and whitespace trimmed", got.Pools)
}
+ // The shared pool's token (provision.SharedPoolToken) is the "" pool,
+ // beside a named one: one parser for the tick and for boxPools.
+ got = provisionTickConfig(env(map[string]string{"CARLOS_POOLS": "@shared, hapair"}))
+ if !reflect.DeepEqual(got.Pools, []string{"", "hapair"}) {
+ t.Errorf("Pools = %#v, want the shared pool and hapair", got.Pools)
+ }
+ for raw, want := range map[string]string{"": "", "@shared": "", "@shared,hapair": "hapair", "cohort1, hapair": "cohort1,hapair"} {
+ if got := boxPools(env(map[string]string{"CARLOS_POOLS": raw})); got != want {
+ t.Errorf("boxPools(%q) = %q, want %q", raw, got, want)
+ }
+ }
+
got = provisionTickConfig(env(map[string]string{"CARLOS_DATA_DIR": "/custom"}))
if got.DataDir != "/custom" {
t.Errorf("DataDir = %q, want /custom", got.DataDir)
diff --git a/internal/host/layoutleg.go b/internal/host/layoutleg.go
index 71c8f9998..af6779d21 100644
--- a/internal/host/layoutleg.go
+++ b/internal/host/layoutleg.go
@@ -9,7 +9,9 @@ package host
import (
"context"
+ "errors"
"fmt"
+ "io/fs"
"log"
"os"
"os/user"
@@ -376,13 +378,54 @@ func newLayoutPass(reg *registry.Registry, svc *activator.Service, dd string, ne
return p
}
+// startupSweepBackoff is the wait before each retry of a failed startup
+// sweep: five tries over 15 s of waiting. startupSweepWindow bounds them
+// from the first try, so a sweep that hangs to its own deadline is not
+// tried again. Variables only so tests can shorten them.
+var (
+ startupSweepBackoff = []time.Duration{time.Second, 2 * time.Second, 4 * time.Second, 8 * time.Second}
+ startupSweepWindow = 20 * time.Second
+)
+
// startActivator is the order the activator comes up in. The startup unit
// sweep first, so nothing an earlier agent left is running. Then layout
// recovery, which runs even when the sweep failed (completing a journal
// is exact) and is told whether it succeeded. Then Start, so no host is
// woken while a journal says its files are between two directories.
+//
+// A failed sweep is retried (#433): root refused the new agent's first
+// call while its view of the edge's main pid lagged the restart, and a box
+// whose sweep failed can never retake an HA host on its own (same-box
+// recovery needs the sweep). The retries all run here, before Start, so
+// no wake can begin while one is pending: a sweep stops every instance
+// unit, and it must never run after wakes may have started. They wait
+// startupSweepBackoff between tries and stop once the next try would
+// begin past startupSweepWindow from the first, or when ctx ends; then
+// the box carries on unswept, as before, and same-box recovery stays
+// refused (and alarmed by the activator) until the agent restarts. A box
+// with no control socket at all is not retried: that is not a refusal
+// that can clear.
func startActivator(ctx context.Context, sweep func(context.Context) error, recoverLayout func(ctx context.Context, swept bool), start func()) {
+ deadline := time.Now().Add(startupSweepWindow)
err := sweep(ctx)
+ tries := 1
+retry:
+ for _, wait := range startupSweepBackoff {
+ if err == nil || ctx.Err() != nil || errors.Is(err, fs.ErrNotExist) || time.Now().Add(wait).After(deadline) {
+ break
+ }
+ log.Printf("agent: startup sweep try %d failed: %v; trying again in %s", tries, err, wait)
+ select {
+ case <-ctx.Done():
+ break retry
+ case <-time.After(wait):
+ }
+ err = sweep(ctx)
+ tries++
+ }
+ if err != nil && tries > 1 {
+ log.Printf("agent: startup sweep failed %d times, last: %v; serving unswept, so same-box recovery of HA hosts stays refused until the agent restarts", tries, err)
+ }
recoverLayout(ctx, err == nil)
start()
}
diff --git a/internal/host/rootfsplacement.go b/internal/host/rootfsplacement.go
index 66e47b851..b43c5b3cc 100644
--- a/internal/host/rootfsplacement.go
+++ b/internal/host/rootfsplacement.go
@@ -23,6 +23,7 @@ import (
"github.com/carlosframework/platform/internal/activator"
"github.com/carlosframework/platform/internal/instancectl"
+ "github.com/carlosframework/platform/internal/provision"
"github.com/carlosframework/platform/internal/registry"
"github.com/carlosframework/platform/internal/release"
"github.com/carlosframework/platform/internal/status"
@@ -305,16 +306,18 @@ func singleTenant(getenv func(string) string) bool {
}
}
-// boxPools is CARLOS_POOLS as the provision tick reads it: the non-empty
-// trimmed names, joined by commas.
+// boxPools is the dedicated pools this box serves, as the provision tick
+// reads CARLOS_POOLS (provision.ParseBoxPools), joined by commas: "" when
+// it serves the shared pool alone. The shared pool is no dedicated pool,
+// so it is left out.
func boxPools(getenv func(string) string) string {
- var pools []string
- for _, p := range strings.Split(getenv("CARLOS_POOLS"), ",") {
- if p = strings.TrimSpace(p); p != "" {
- pools = append(pools, p)
+ var named []string
+ for _, p := range provision.ParseBoxPools(getenv("CARLOS_POOLS")) {
+ if p != "" {
+ named = append(named, p)
}
}
- return strings.Join(pools, ",")
+ return strings.Join(named, ",")
}
// rootfsReadiness is the control client's /ready/rootfs.
diff --git a/internal/instancectl/peer_edge.go b/internal/instancectl/peer_edge.go
new file mode 100644
index 000000000..7a48ac846
--- /dev/null
+++ b/internal/instancectl/peer_edge.go
@@ -0,0 +1,115 @@
+package instancectl
+
+import (
+ "fmt"
+ "sync"
+ "time"
+)
+
+// edgePeer decides whether a connecting peer is the edge's main process
+// (design §5.4): uid carlos AND the MainPID systemd reports for
+// carlos-edge.service. It is productionPeerOK's decision, apart from the
+// socket and from systemctl, so it can be tested on any platform.
+//
+// mainPID asks systemd. Its answer, a pid or a failure, is cached for
+// edgePIDCache: while the edge has no MainPID (a restart window) every
+// refused connect would otherwise re-exec systemctl, and the accept loop
+// waits on each check.
+//
+// A cached answer can predate an agent restart (#433): the old agent's
+// last calls cache its pid, and the new agent's first call, the startup
+// sweep, arrives within the second and was refused against it. So a peer
+// the cache refuses is checked once more against a fresh read before it is
+// refused, and accepted only if systemd names it now. That widens nothing:
+// the peer must still be the main pid systemd reports. Forced reads are
+// at most one per edgePIDForceEvery, so a refused peer connecting in a
+// loop cannot make every connect exec systemctl.
+type edgePeer struct {
+ carlosUID int
+ mainPID func() (int, error)
+ now func() time.Time
+
+ mu sync.Mutex
+ pid int
+ lastErr error
+ at time.Time
+ forced time.Time // the last forced read
+}
+
+// edgePIDCache is how long one systemd answer is reused.
+const edgePIDCache = time.Second
+
+// edgePIDForceEvery is the least time between two forced reads.
+const edgePIDForceEvery = 100 * time.Millisecond
+
+// cached is the edge's main pid, from the cache while it is fresh; read is
+// whether systemd was asked for it.
+func (p *edgePeer) cached() (pid int, read bool, err error) {
+ p.mu.Lock()
+ defer p.mu.Unlock()
+ if p.now().Sub(p.at) < edgePIDCache {
+ if p.pid > 0 {
+ return p.pid, false, nil
+ }
+ if p.lastErr != nil {
+ return 0, false, p.lastErr
+ }
+ }
+ pid, err = p.readLocked()
+ return pid, true, err
+}
+
+// fresh asks systemd again, past the cache, unless a forced read ran less
+// than edgePIDForceEvery ago; then it is the cached answer. read is
+// whether systemd was asked.
+func (p *edgePeer) fresh() (pid int, read bool, err error) {
+ p.mu.Lock()
+ defer p.mu.Unlock()
+ now := p.now()
+ if !p.forced.IsZero() && now.Sub(p.forced) < edgePIDForceEvery {
+ return p.pid, false, p.lastErr
+ }
+ p.forced = now
+ pid, err = p.readLocked()
+ return pid, true, err
+}
+
+// readLocked asks systemd and caches the answer. p.mu is held.
+func (p *edgePeer) readLocked() (int, error) {
+ pid, err := p.mainPID()
+ if err == nil && pid <= 0 {
+ err = fmt.Errorf("carlos-edge.service has no MainPID")
+ }
+ if err != nil {
+ p.pid, p.lastErr, p.at = 0, err, p.now()
+ return 0, err
+ }
+ p.pid, p.lastErr, p.at = pid, nil, p.now()
+ return pid, nil
+}
+
+// check accepts the peer only when uid is carlos and pid is the edge's
+// main pid.
+func (p *edgePeer) check(uid uint32, pid int32) error {
+ if int(uid) != p.carlosUID {
+ return fmt.Errorf("peer uid %d is not carlos", uid)
+ }
+ main, read, err := p.cached()
+ if err == nil && int(pid) == main {
+ return nil
+ }
+ // A cached answer refuses: ask systemd now (#433), once. An answer
+ // cached() has just read is already fresh.
+ if !read {
+ if fmain, asked, ferr := p.fresh(); asked {
+ main, err = fmain, ferr
+ }
+ }
+ if err != nil {
+ return err
+ }
+ if int(pid) != main {
+ return fmt.Errorf("peer pid %d is not the edge's main pid %d", pid, main)
+ }
+ return nil
+}
diff --git a/internal/instancectl/peer_edge_test.go b/internal/instancectl/peer_edge_test.go
new file mode 100644
index 000000000..ae505d347
--- /dev/null
+++ b/internal/instancectl/peer_edge_test.go
@@ -0,0 +1,120 @@
+package instancectl
+
+import (
+ "errors"
+ "strings"
+ "testing"
+ "time"
+)
+
+// fakeSystemd answers MainPID from a value the test moves, and counts the
+// reads.
+type fakeSystemd struct {
+ pid int
+ err error
+ reads int
+}
+
+func (f *fakeSystemd) mainPID() (int, error) {
+ f.reads++
+ return f.pid, f.err
+}
+
+func newTestEdgePeer(sd *fakeSystemd, clock *time.Time) *edgePeer {
+ return &edgePeer{carlosUID: 990, mainPID: sd.mainPID, now: func() time.Time { return *clock }}
+}
+
+// #433: root's cached main pid lags an agent restart. The new agent's
+// first call is checked against a fresh read before it is refused, and
+// accepted only when systemd names it; a fresh read that still names
+// another pid refuses.
+func TestEdgePeerRereadsAStaleMainPID(t *testing.T) {
+ clock := time.Unix(1_700_000_000, 0)
+ sd := &fakeSystemd{pid: 100}
+ p := newTestEdgePeer(sd, &clock)
+ if err := p.check(990, 100); err != nil {
+ t.Fatalf("the edge's main pid refused: %v", err)
+ }
+ // The agent restarts inside the cache window: systemd now says 200.
+ sd.pid = 200
+ clock = clock.Add(300 * time.Millisecond)
+ if err := p.check(990, 200); err != nil {
+ t.Fatalf("the new main pid refused against a stale cache: %v", err)
+ }
+ // The refreshed answer is cached: the old pid is refused now.
+ if err := p.check(990, 100); err == nil || !strings.Contains(err.Error(), "is not the edge's main pid 200") {
+ t.Fatalf("the old main pid after the restart: %v", err)
+ }
+
+ // A peer systemd does not name is refused after the fresh read too.
+ clock = clock.Add(2 * time.Second)
+ sd.pid = 300
+ if err := p.check(990, 300); err != nil {
+ t.Fatalf("main pid 300: %v", err)
+ }
+ clock = clock.Add(300 * time.Millisecond)
+ before := sd.reads
+ if err := p.check(990, 301); err == nil || !strings.Contains(err.Error(), "peer pid 301 is not the edge's main pid 300") {
+ t.Fatalf("a child of the edge: %v", err)
+ }
+ if sd.reads != before+1 {
+ t.Fatalf("the mismatch made %d systemd reads, want one fresh read", sd.reads-before)
+ }
+}
+
+// A cached failure (the edge had no MainPID during its restart) does not
+// refuse the new main process either: systemd is asked again.
+func TestEdgePeerRereadsACachedFailure(t *testing.T) {
+ clock := time.Unix(1_700_000_000, 0)
+ sd := &fakeSystemd{pid: 0}
+ p := newTestEdgePeer(sd, &clock)
+ if err := p.check(990, 200); err == nil {
+ t.Fatal("a peer accepted while the edge has no MainPID")
+ }
+ sd.pid = 200
+ clock = clock.Add(200 * time.Millisecond)
+ if err := p.check(990, 200); err != nil {
+ t.Fatalf("the new main pid refused against a cached failure: %v", err)
+ }
+ sd.err = errors.New("systemctl: timeout")
+ clock = clock.Add(2 * time.Second)
+ if err := p.check(990, 200); err == nil {
+ t.Fatal("a peer accepted when systemd could not be read")
+ }
+}
+
+// Forced reads are rate-limited: a peer that keeps connecting with a pid
+// that is not the edge's does not exec systemctl on every connect.
+func TestEdgePeerForcedReadsAreRateLimited(t *testing.T) {
+ clock := time.Unix(1_700_000_000, 0)
+ sd := &fakeSystemd{pid: 100}
+ p := newTestEdgePeer(sd, &clock)
+ if err := p.check(990, 100); err != nil {
+ t.Fatal(err)
+ }
+ for i := 0; i < 50; i++ {
+ clock = clock.Add(time.Millisecond)
+ if err := p.check(990, 666); err == nil {
+ t.Fatal("a stranger accepted")
+ }
+ }
+ // 50 ms of a refused peer: the first mismatch forces a read, the rest
+ // fall inside edgePIDForceEvery.
+ if sd.reads != 2 {
+ t.Fatalf("systemd reads = %d, want 2 (the first check and one forced read)", sd.reads)
+ }
+}
+
+// The uid is checked first and never widened: a non-carlos peer is refused
+// without asking systemd, even when its pid is the main pid.
+func TestEdgePeerRefusesAnotherUID(t *testing.T) {
+ clock := time.Unix(1_700_000_000, 0)
+ sd := &fakeSystemd{pid: 100}
+ p := newTestEdgePeer(sd, &clock)
+ if err := p.check(0, 100); err == nil || !strings.Contains(err.Error(), "peer uid 0 is not carlos") {
+ t.Fatalf("uid 0: %v", err)
+ }
+ if sd.reads != 0 {
+ t.Fatalf("systemd asked %d times for a wrong uid", sd.reads)
+ }
+}
diff --git a/internal/instancectl/peer_linux.go b/internal/instancectl/peer_linux.go
index 11ee0e45f..6678a0218 100644
--- a/internal/instancectl/peer_linux.go
+++ b/internal/instancectl/peer_linux.go
@@ -13,7 +13,6 @@ import (
"os/user"
"strconv"
"strings"
- "sync"
"syscall"
"time"
@@ -43,8 +42,8 @@ func peerCred(conn net.Conn) (*unix.Ucred, error) {
// productionPeerOK requires the peer to be uid carlos AND the main process
// of carlos-edge.service as systemd reports it (design §5.4): a flat tenant
// is a child of that pid, never the pid itself, and a nested tenant cannot
-// reach the socket at all. MainPID is asked of systemctl and cached for one
-// second, because the agent restarts and the pid changes.
+// reach the socket at all. The decision is edgePeer's; MainPID is asked of
+// systemctl.
func productionPeerOK() func(net.Conn) error {
// A missing carlos user or an unparsable uid is fatal at startup, not a
// permanent refusal cached into the returned closure: socket activation
@@ -60,59 +59,30 @@ func productionPeerOK() func(net.Conn) error {
if err != nil {
log.Fatalf("instance-control: carlos uid %q: %v", u.Uid, err)
}
- var mu sync.Mutex
- var mainPID int
- var lastErr error
- var at time.Time
- edgePID := func() (int, error) {
- mu.Lock()
- defer mu.Unlock()
- // Cache both a success and a failure for one second: while the
- // edge has no MainPID yet (a restart window), every refused
- // connect would otherwise re-exec systemctl under this mutex —
- // the negative case needs the same cache the positive one always
- // had (codex review fix round 2 item 5).
- if time.Since(at) < time.Second {
- if mainPID > 0 {
- return mainPID, nil
- }
- if lastErr != nil {
- return 0, lastErr
- }
- }
- ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
- defer cancel()
- out, err := exec.CommandContext(ctx, "systemctl", "show", "-p", "MainPID", "--value", edgeUnit).Output()
- if err != nil {
- mainPID, lastErr, at = 0, err, time.Now()
- return 0, err
- }
- pid, err := strconv.Atoi(strings.TrimSpace(string(out)))
- if err != nil || pid <= 0 {
- err = fmt.Errorf("carlos-edge.service has no MainPID")
- mainPID, lastErr, at = 0, err, time.Now()
- return 0, err
- }
- mainPID, lastErr, at = pid, nil, time.Now()
- return pid, nil
- }
+ peer := &edgePeer{carlosUID: carlosUID, mainPID: systemdEdgeMainPID, now: time.Now}
return func(conn net.Conn) error {
cred, err := peerCred(conn)
if err != nil {
return err
}
- if int(cred.Uid) != carlosUID {
- return fmt.Errorf("peer uid %d is not carlos", cred.Uid)
- }
- pid, err := edgePID()
- if err != nil {
- return err
- }
- if int(cred.Pid) != pid {
- return fmt.Errorf("peer pid %d is not the edge's main pid %d", cred.Pid, pid)
- }
- return nil
+ return peer.check(cred.Uid, cred.Pid)
+ }
+}
+
+// systemdEdgeMainPID is carlos-edge.service's MainPID as systemd reports
+// it now; 0 when the unit has none.
+func systemdEdgeMainPID() (int, error) {
+ ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
+ defer cancel()
+ out, err := exec.CommandContext(ctx, "systemctl", "show", "-p", "MainPID", "--value", edgeUnit).Output()
+ if err != nil {
+ return 0, err
+ }
+ pid, err := strconv.Atoi(strings.TrimSpace(string(out)))
+ if err != nil {
+ return 0, nil
}
+ return pid, nil
}
// activatedListener returns the socket-activated listener when systemd
diff --git a/internal/provision/boxpools_test.go b/internal/provision/boxpools_test.go
new file mode 100644
index 000000000..b18ea986c
--- /dev/null
+++ b/internal/provision/boxpools_test.go
@@ -0,0 +1,53 @@
+package provision
+
+import (
+ "reflect"
+ "testing"
+)
+
+// CARLOS_POOLS (#433 follow-up): SharedPoolToken names the shared "" pool,
+// so a box can serve it beside a named pool. Every other token is taken
+// literally, as before, and an empty element is dropped, never read as the
+// shared pool (",tito" serves tito alone, codex R3-3).
+func TestParseBoxPools(t *testing.T) {
+ for _, c := range []struct {
+ raw string
+ pools []string
+ serve []string // pools served
+ not []string // pools not served
+ }{
+ {"", nil, []string{""}, []string{"hapair"}},
+ {"@shared", []string{""}, []string{""}, []string{"hapair", "@shared"}},
+ {"@shared,hapair", []string{"", "hapair"}, []string{"", "hapair"}, []string{"cohort1", "@shared"}},
+ {" hapair , @shared ,, ", []string{"hapair", ""}, []string{"", "hapair"}, []string{"cohort1"}},
+ {"cohort1,hapair", []string{"cohort1", "hapair"}, []string{"cohort1", "hapair"}, []string{""}},
+ {",tito", []string{"tito"}, []string{"tito"}, []string{""}},
+ {"hapair,@shared,hapair,@shared", []string{"hapair", ""}, []string{"", "hapair"}, nil},
+ // Not the token and not a pool name: literal, so it serves no
+ // record a door mints, and never the shared pool.
+ {"@Shared", []string{"@Shared"}, nil, []string{"", "shared"}},
+ {"@other,hapair", []string{"@other", "hapair"}, []string{"hapair"}, []string{"", "other"}},
+ } {
+ got := ParseBoxPools(c.raw)
+ if !reflect.DeepEqual(got, c.pools) {
+ t.Errorf("ParseBoxPools(%q) = %#v, want %#v", c.raw, got, c.pools)
+ }
+ for _, p := range c.serve {
+ if !poolServed(got, p) {
+ t.Errorf("CARLOS_POOLS=%q does not serve pool %q", c.raw, p)
+ }
+ }
+ for _, p := range c.not {
+ if poolServed(got, p) {
+ t.Errorf("CARLOS_POOLS=%q serves pool %q", c.raw, p)
+ }
+ }
+ }
+}
+
+// The token can never be a pool's name: the record grammar refuses it.
+func TestSharedPoolTokenIsNoPoolName(t *testing.T) {
+ if ValidPool(SharedPoolToken) {
+ t.Fatalf("%q is a valid pool name", SharedPoolToken)
+ }
+}
diff --git a/internal/provision/reconcile.go b/internal/provision/reconcile.go
index c47f75c7a..397d7e343 100644
--- a/internal/provision/reconcile.go
+++ b/internal/provision/reconcile.go
@@ -2891,6 +2891,47 @@ func forEach(items []string, f func(string)) {
wg.Wait()
}
+// SharedPoolToken is the CARLOS_POOLS token for the shared "" pool, so a
+// box can serve it beside a named pool ("@shared,hapair"). A pool name is
+// [a-z0-9-]{0,16} (ValidPool), so no pool can be called this.
+const SharedPoolToken = "@shared"
+
+// ParseBoxPools parses CARLOS_POOLS, the pools this box serves, into
+// ReconcileConfig.Pools. It is the one parser: the provision tick, the
+// edges file's serves_shared_pool (through the same config) and the rootfs
+// placement refusal all read the variable through it.
+//
+// Elements are comma-separated and trimmed; an empty one is dropped, never
+// read as the shared pool (",tito" serves tito alone). SharedPoolToken is
+// the shared pool, "" in the result. Every other token is taken literally,
+// as before this token existed: one that is not a pool name (another "@"
+// word, "@Shared", upper case) matches no record a door mints and never
+// the shared pool, and is logged once. A repeat is dropped. No element at
+// all is nil, which poolServed reads as the shared pool alone.
+func ParseBoxPools(raw string) []string {
+ var pools []string
+ for _, p := range strings.Split(raw, ",") {
+ p = strings.TrimSpace(p)
+ switch {
+ case p == "":
+ continue
+ case p == SharedPoolToken:
+ p = ""
+ case !ValidPool(p):
+ if _, seen := oddBoxPools.LoadOrStore(p, true); !seen {
+ log.Printf("provision: CARLOS_POOLS names %q, which is not a pool name (want [a-z0-9-]{0,16}, or %s for the shared pool); it serves no pool a door creates", p, SharedPoolToken)
+ }
+ }
+ if !slices.Contains(pools, p) {
+ pools = append(pools, p)
+ }
+ }
+ return pools
+}
+
+// oddBoxPools is the CARLOS_POOLS tokens ParseBoxPools has logged.
+var oddBoxPools sync.Map
+
// poolServed reports whether pool is one this box serves. An empty
// cfg.Pools means the shared "" pool ONLY, never "every pool" — the same
// convention domains.Config's AppsDomain=="" carries: unconfigured means the
diff --git a/internal/provision/reconcile_eligibility_test.go b/internal/provision/reconcile_eligibility_test.go
index 6f9ac5556..6c38cd5e2 100644
--- a/internal/provision/reconcile_eligibility_test.go
+++ b/internal/provision/reconcile_eligibility_test.go
@@ -13,6 +13,8 @@ func TestSharedInstanceEligibilityIsTheMintPredicate(t *testing.T) {
{nil, "", true, true},
{[]string{"tito"}, "", false, true},
{[]string{"", "tito"}, "", true, true},
+ {ParseBoxPools("@shared,hapair"), "", true, true},
+ {ParseBoxPools("cohort1,hapair"), "", false, true},
{nil, InboundNone, true, false},
{[]string{"tito"}, InboundNone, false, false},
}
diff --git a/internal/provision/testdata/plan14-root-reads-chain.tsv b/internal/provision/testdata/plan14-root-reads-chain.tsv
index 31be98710..a7b879c4b 100644
--- a/internal/provision/testdata/plan14-root-reads-chain.tsv
+++ b/internal/provision/testdata/plan14-root-reads-chain.tsv
@@ -9,4 +9,5 @@ plan14-root-reads-region-ha-p1a.tsv 125c5c411cd0a04000d9652800b51bc7c066081c0075
plan14-root-reads-nearest-region-b.tsv f4e36134015ec6d09bada7be500c8faad22450afda12d033a8e3e24b1e8bb361
plan14-root-reads-alias-socket-follow-338.tsv 5192052a23d2fdd6f5d48b5617fe28a9bb03458e1e931c060fbdc42c3d627927
plan14-root-reads-usage-attribution-390.tsv 5192052a23d2fdd6f5d48b5617fe28a9bb03458e1e931c060fbdc42c3d627927
-plan14-root-reads-rollup-tenant-tags.tsv 5192052a23d2fdd6f5d48b5617fe28a9bb03458e1e931c060fbdc42c3d627927
+plan14-root-reads-ha-p1a-433.tsv f8acbc0dd8828636e3f73d9afd0e539d3dfd1346e0232d91903c33d6eb27d820
+plan14-root-reads-rollup-tenant-tags.tsv f8acbc0dd8828636e3f73d9afd0e539d3dfd1346e0232d91903c33d6eb27d820
diff --git a/internal/provision/testdata/plan14-root-reads-ha-p1a-433.tsv b/internal/provision/testdata/plan14-root-reads-ha-p1a-433.tsv
new file mode 100644
index 000000000..9278afba2
--- /dev/null
+++ b/internal/provision/testdata/plan14-root-reads-ha-p1a-433.tsv
@@ -0,0 +1,28 @@
+# Census overlay ha-p1a-433, written by census-propose (#369). census-ruling-ha-p1a-433, approved on #280 before the merge; the approval card is docs/superpowers/notes/census-proposal-ha-p1a-433.md.
+# 2 body, 1 sites, 4 envelope: each changed unit re-frozen at its existing disposition with its claim appended.
+# 8 new dispositions: 2 reads re-frozen at their disposition with the claim, 4 new units frozen accepted-legacy, 1 quiet units retired while they read nothing, 1 other.
+@legacy d5186710900d37c74a217ea1c872a06c8afd634093845b390830c888dc2e6988 internal/host/agent.go provisionTickConfig legacy accepted-legacy accepted-legacy;rev3=J4;basis=root-input;rev3=census-ruling-ha-p1a-433;basis=the agent (carlos-edge.service, user carlos) and the edges file loop's eligibility: the same CARLOS_POOLS read, now parsed by provision.ParseBoxPools (internal/provision, envelope re-pinned), the one parser boxPools also uses. "@shared" (provision.SharedPoolToken, never a valid pool name) is the shared "" pool; other tokens are literal as before; empty elements and repeats dropped. No read added. data-literal@207,data-literal@248 0321619c2abad2a9431515f92e28465a6b40aa49332fdcddf939e7b3e2a6ebe7
+@legacy 4de6e4827c9e69619633552c8c373e9704097d986b8ab4ce2b07bb4952ceb460 internal/registry/registry.go Registry.List legacy accepted-legacy accepted-legacy;rev3=J1,J4;basis=route-and-input;rev3=census-ruling-instance-egress-sizes-328-329;identity=the registry's SQLite side, as carlos: in the agent (/opt/carlos/carlos agent, carlos-edge.service) and in the registry child (carlos __registry-child, which a root pass forks as the service user), and now also in the read-only registry child (carlos __registry-child read-only, which root's instance control forks as the service user through openServiceRegistryReadOnly);basis=#328 plan 2 Task 13 fix (4e7bbc4b): a read-only registry (OpenReadOnly sets readOnly) lists over its own mode=ro, query_only connection (registry:sql, one site, r.sql) instead of a fresh sql.Open on its path, which opens read-write; registry:readOnly (one site) is the branch on that flag. A read-write registry keeps main's fresh connection. The same SELECT of routeCols from routes; it serves root's egress source (listRegistryReadOnly) every row; it decides nothing;rev3=census-ruling-ha-p1a-433;basis=the registry's SQLite side as carlos (agent, registry child, and root's read-only registry child via openServiceRegistryReadOnly): calls readCols on the same connection before the same SELECT ... FROM routes ORDER BY host. A read-write registry gets routeCols unchanged; a read-only one gets routeCols with any column routeAddedColumns adds that the table lacks read as its migration default ("0 AS ha"), so root's egress naming and source work before the new agent migrates (#433). Decides nothing; no read added. file:Exec@396,file:Open@212,file:Query@569,registry:Routes@145,registry:path@231,registry:readOnly@183,registry:remote@49,registry:remote@81,registry:sql@172,whole:Route@149,whole:Route@797,whole:Route@810,whole:Route@815,whole:Route@829,whole:remoteClient@51,whole:remoteClient@83 4505dd81395a06055029d52b27debb90209fd3a8aac1af4d589bee8bc33a0ba5
+@legacy 182fbc52eb5bd221ef5f55b07e56d5dda2b09e1b3da28e47919c521b270062e9 internal/instancectl/peer_linux.go systemdEdgeMainPID legacy accepted-legacy accepted-legacy;rev3=census-ruling-ha-p1a-433;basis=root (carlos-instance-control.service): the same exec productionPeerOK's closure ran before, moved out unchanged: systemctl show -p MainPID --value carlos-edge.service, fixed argv, 3 s timeout; output that does not parse is 0 (no MainPID), which edgePeer refuses. No input from a peer, tenant or agent reaches the argv. file:CommandContext@143 f71136a6afa17f28657515e080c67d3391a21e7475b4eca3e5249f607b175a4e
+@legacy 5fc36e10630d095bb775ab528335634412a33d3aea9809af9403ad998fcb7d64 internal/registry/registry.go Registry.readCols legacy accepted-legacy accepted-legacy;rev3=census-ruling-ha-p1a-433;basis=new; the registry's SQLite side as carlos. For a read-write registry returns routeCols and reads nothing. For a read-only one (registry:readOnly), one SELECT name FROM pragma_table_info('routes') over the registry's own mode=ro, query_only connection. The names read are only compared with the in-binary routeCols and routeAddedColumns lists, never put into SQL: the select list is built from routeCols and the in-binary defaults (the empty string literal or 0, parsed from routeAddedColumns by a fixed regexp). An agent-written table can only make a known added column read as its default, which is what the migration gives it; a missing CREATE column is not stood in for and the read fails as before. file:Query@117,registry:readOnly@63 f4b586a0331bbf958a2b957f08ef779bf7ca16a99101891ee0007cf142fa7f1b
+@legacy 90b76b74a3a96404f981c217def2e8cf6d7aaf172b67aaa3714245d6438c3cde internal/registry/registry.go addedColumn.spec legacy accepted-legacy accepted-legacy;rev3=census-ruling-ha-p1a-433;basis=new; pure: joins the entry's in-binary Name, Type and Default into "<name> <type> NOT NULL DEFAULT <default>". +registry:Name/Type/Default are the struct's own fields; it reads nothing from the database, a file or an input. registry:Default@92,registry:Name@45,registry:Type@60 4a0c847a4c4afc8ef279b0cf45e1d77b9f48839337222b5b2d7f9bd0d9e18078
+@legacy 7f57f26c268c831d65e4dc8ff1610d684d067dc291115463dd0f7a18efc4d480 internal/registry/registry.go addedRouteColumnDefaults legacy accepted-legacy accepted-legacy;rev3=census-ruling-ha-p1a-433;basis=new as a census unit (it replaces the regexp parse of the ALTER texts): pure, maps each routeAddedColumns entry's in-binary Name to its in-binary Default, now including the four claim ownership columns, so readCols stands their defaults in for a read-only registry that predates migrateClaimOwnership. Reads nothing from the database, a file or an input. registry:Default@135,registry:Name@125,whole:addedColumn@99 c1764a9b1a6df43619e98a9efd2867b81f32441b63fe23e5520d8ca177e41e47
+@legacy 84032054f14612fedfe899360fec0296d3b3a2136db23fea9ab562a23da8cace internal/registry/claimrows.go Registry.migrateClaimOwnership legacy accepted-legacy accepted-legacy;rev3=J1,J4;basis=route-and-input;rev3=census-ruling-ha-p1a-433;basis=the registry's SQLite side as carlos, on every registry open (called from migrate): the four claim ownership ALTERs for routes and timers come from routeAddedColumns' Claim-marked entries (claim_incarnation TEXT, claim_stamp INTEGER, claim_owner TEXT, claim_row_id TEXT, each NOT NULL DEFAULT the empty string or 0), as "ALTER TABLE " + table + " ADD COLUMN " + spec(): the same statements as main's inline list, same order, same tables, same duplicate-column rule. +registry:Claim is the mark, +whole:addedColumn the struct; in-binary literals only; no read added. file:Exec@196,file:Exec@365,registry:Claim@152,registry:sql@196,registry:sql@365,whole:addedColumn@125 9c23e3ca20731e3eb1b11e8758ee562f121922fb024dae3b839c4e121ce924b3
+@legacy 3bbee2be2030884bb5d02ece03fd5767aa744deafebc0edffe6452901337338c internal/registry/registry.go Registry.migrate legacy accepted-legacy accepted-legacy;rev3=census-ruling-self-serve-moves-1;basis=the registry's SQLite side, as carlos: in the agent (/opt/carlos/carlos agent, carlos-edge.service) and in the registry child (carlos __registry-child, which a root pass forks as the service user), on every registry open; a box CLI verb that opens the registry directly runs it as whoever runs the verb: census-ruling-seeded-instances's body with two more columns added to routes (incarnation and serving_seq, INTEGER NOT NULL DEFAULT 0, idempotent through the duplicate-column rule); self-serve moves 1 Task 7;rev3=census-ruling-rootfs-apps-2;basis=one more ALTER TABLE, routes ADD COLUMN runtime TEXT NOT NULL DEFAULT '', beside main's rate_limit, assets_off, asset_gen, incarnation and serving_seq (the last four from the merges of origin/main 3c33f2eb and 953b9fda); the same sixteen sites, no read added;rev3=census-ruling-instance-egress-sizes-328-329;basis=#328/#329 plan 1 Task 4: three more ALTER TABLE statements in the existing loop, routes ADD COLUMN egress_allow, size and policy_expires_at, each TEXT NOT NULL DEFAULT '' and idempotent through the duplicate-column rule; the same sixteen sites, no read added.;rev3=census-ruling-region-ha-p1a;basis=one more ALTER TABLE in the existing loop: routes ADD COLUMN ha INTEGER NOT NULL DEFAULT 0, idempotent through the duplicate-column rule; the same sixteen sites, no read added;rev3=census-ruling-ha-p1a-433;basis=the registry's SQLite side as carlos (agent, registry child; a box CLI verb that opens the registry directly runs it as whoever runs it), on every registry open: the ALTER TABLE routes statements are now built from the one migration definition routeAddedColumns (addedColumn name, type, default; review r1 P2): for each entry without the Claim mark, "ALTER TABLE routes ADD COLUMN " + spec(), byte for byte the statements main runs, in main's order, under the same duplicate-column rule. +registry:Claim is that mark, +whole:addedColumn the struct. Every name, type and default is an in-binary literal; no statement added, removed or changed; no read added. file:Exec@1694,file:Exec@2554,file:Exec@2833,file:Exec@3696,file:Exec@3872,file:Exec@51,file:Exec@600,file:Exec@963,registry:Claim@525,registry:sql@1694,registry:sql@2554,registry:sql@2833,registry:sql@3696,registry:sql@3872,registry:sql@51,registry:sql@600,registry:sql@963,whole:addedColumn@500 c1aa99249122d7976764fc6571eada4c1fbda98d52e96d493c64f3e39c31d5bd
+@legacy c4f52621ee9b897da8526befa1450902d86770d3f07954b1b297de96cb1181f5 internal/registry/registry.go Registry.Get legacy accepted-legacy accepted-legacy;rev3=J1,J4;basis=route-and-input;rev3=census-ruling-ha-p1a-433;basis=same identities as List: +registry:sql is r.sql handed to readCols, the same connection the SELECT already used; same SELECT ... WHERE host = ? with the select list readCols returns (routeCols for a read-write registry). Root's instanceRegistryHostApp and instanceRegistryHostRuntime read Get through the read-only child and now work before the migration too. file:QueryRow@262,registry:Route@165,registry:remote@58,registry:remote@90,registry:sql@209,registry:sql@262,whole:Route@169,whole:Route@455,whole:remoteClient@60,whole:remoteClient@92 736f4a42df871f765a124ea532a38ba1c8ab8bf16375eb0c480f855ddf5c3e82
+internal/host/agent.go provisionTickConfig legacy accepted-legacy accepted-legacy;rev3=J4;basis=root-input;rev3=census-ruling-ha-p1a-433;basis=the agent (carlos-edge.service, user carlos) and the edges file loop's eligibility: the same CARLOS_POOLS read, now parsed by provision.ParseBoxPools (internal/provision, envelope re-pinned), the one parser boxPools also uses. "@shared" (provision.SharedPoolToken, never a valid pool name) is the shared "" pool; other tokens are literal as before; empty elements and repeats dropped. No read added. data-literal@207,data-literal@248 0321619c2abad2a9431515f92e28465a6b40aa49332fdcddf939e7b3e2a6ebe7
+internal/registry/registry.go Registry.List legacy accepted-legacy accepted-legacy;rev3=J1,J4;basis=route-and-input;rev3=census-ruling-instance-egress-sizes-328-329;identity=the registry's SQLite side, as carlos: in the agent (/opt/carlos/carlos agent, carlos-edge.service) and in the registry child (carlos __registry-child, which a root pass forks as the service user), and now also in the read-only registry child (carlos __registry-child read-only, which root's instance control forks as the service user through openServiceRegistryReadOnly);basis=#328 plan 2 Task 13 fix (4e7bbc4b): a read-only registry (OpenReadOnly sets readOnly) lists over its own mode=ro, query_only connection (registry:sql, one site, r.sql) instead of a fresh sql.Open on its path, which opens read-write; registry:readOnly (one site) is the branch on that flag. A read-write registry keeps main's fresh connection. The same SELECT of routeCols from routes; it serves root's egress source (listRegistryReadOnly) every row; it decides nothing;rev3=census-ruling-ha-p1a-433;basis=the registry's SQLite side as carlos (agent, registry child, and root's read-only registry child via openServiceRegistryReadOnly): calls readCols on the same connection before the same SELECT ... FROM routes ORDER BY host. A read-write registry gets routeCols unchanged; a read-only one gets routeCols with any column routeAddedColumns adds that the table lacks read as its migration default ("0 AS ha"), so root's egress naming and source work before the new agent migrates (#433). Decides nothing; no read added. file:Exec@396,file:Open@212,file:Query@569,registry:Routes@145,registry:path@231,registry:readOnly@183,registry:remote@49,registry:remote@81,registry:sql@172,whole:Route@149,whole:Route@797,whole:Route@810,whole:Route@815,whole:Route@829,whole:remoteClient@51,whole:remoteClient@83 4505dd81395a06055029d52b27debb90209fd3a8aac1af4d589bee8bc33a0ba5
+internal/instancectl/peer_linux.go systemdEdgeMainPID legacy accepted-legacy accepted-legacy;rev3=census-ruling-ha-p1a-433;basis=root (carlos-instance-control.service): the same exec productionPeerOK's closure ran before, moved out unchanged: systemctl show -p MainPID --value carlos-edge.service, fixed argv, 3 s timeout; output that does not parse is 0 (no MainPID), which edgePeer refuses. No input from a peer, tenant or agent reaches the argv. file:CommandContext@143 f71136a6afa17f28657515e080c67d3391a21e7475b4eca3e5249f607b175a4e
+internal/registry/registry.go Registry.readCols legacy accepted-legacy accepted-legacy;rev3=census-ruling-ha-p1a-433;basis=new; the registry's SQLite side as carlos. For a read-write registry returns routeCols and reads nothing. For a read-only one (registry:readOnly), one SELECT name FROM pragma_table_info('routes') over the registry's own mode=ro, query_only connection. The names read are only compared with the in-binary routeCols and routeAddedColumns lists, never put into SQL: the select list is built from routeCols and the in-binary defaults (the empty string literal or 0, parsed from routeAddedColumns by a fixed regexp). An agent-written table can only make a known added column read as its default, which is what the migration gives it; a missing CREATE column is not stood in for and the read fails as before. file:Query@117,registry:readOnly@63 f4b586a0331bbf958a2b957f08ef779bf7ca16a99101891ee0007cf142fa7f1b
+internal/registry/registry.go addedColumn.spec legacy accepted-legacy accepted-legacy;rev3=census-ruling-ha-p1a-433;basis=new; pure: joins the entry's in-binary Name, Type and Default into "<name> <type> NOT NULL DEFAULT <default>". +registry:Name/Type/Default are the struct's own fields; it reads nothing from the database, a file or an input. registry:Default@92,registry:Name@45,registry:Type@60 4a0c847a4c4afc8ef279b0cf45e1d77b9f48839337222b5b2d7f9bd0d9e18078
+internal/registry/registry.go addedRouteColumnDefaults legacy accepted-legacy accepted-legacy;rev3=census-ruling-ha-p1a-433;basis=new as a census unit (it replaces the regexp parse of the ALTER texts): pure, maps each routeAddedColumns entry's in-binary Name to its in-binary Default, now including the four claim ownership columns, so readCols stands their defaults in for a read-only registry that predates migrateClaimOwnership. Reads nothing from the database, a file or an input. registry:Default@135,registry:Name@125,whole:addedColumn@99 c1764a9b1a6df43619e98a9efd2867b81f32441b63fe23e5520d8ca177e41e47
+internal/registry/claimrows.go Registry.migrateClaimOwnership legacy accepted-legacy accepted-legacy;rev3=J1,J4;basis=route-and-input;rev3=census-ruling-ha-p1a-433;basis=the registry's SQLite side as carlos, on every registry open (called from migrate): the four claim ownership ALTERs for routes and timers come from routeAddedColumns' Claim-marked entries (claim_incarnation TEXT, claim_stamp INTEGER, claim_owner TEXT, claim_row_id TEXT, each NOT NULL DEFAULT the empty string or 0), as "ALTER TABLE " + table + " ADD COLUMN " + spec(): the same statements as main's inline list, same order, same tables, same duplicate-column rule. +registry:Claim is the mark, +whole:addedColumn the struct; in-binary literals only; no read added. file:Exec@196,file:Exec@365,registry:Claim@152,registry:sql@196,registry:sql@365,whole:addedColumn@125 9c23e3ca20731e3eb1b11e8758ee562f121922fb024dae3b839c4e121ce924b3
+internal/registry/registry.go Registry.migrate legacy accepted-legacy accepted-legacy;rev3=census-ruling-self-serve-moves-1;basis=the registry's SQLite side, as carlos: in the agent (/opt/carlos/carlos agent, carlos-edge.service) and in the registry child (carlos __registry-child, which a root pass forks as the service user), on every registry open; a box CLI verb that opens the registry directly runs it as whoever runs the verb: census-ruling-seeded-instances's body with two more columns added to routes (incarnation and serving_seq, INTEGER NOT NULL DEFAULT 0, idempotent through the duplicate-column rule); self-serve moves 1 Task 7;rev3=census-ruling-rootfs-apps-2;basis=one more ALTER TABLE, routes ADD COLUMN runtime TEXT NOT NULL DEFAULT '', beside main's rate_limit, assets_off, asset_gen, incarnation and serving_seq (the last four from the merges of origin/main 3c33f2eb and 953b9fda); the same sixteen sites, no read added;rev3=census-ruling-instance-egress-sizes-328-329;basis=#328/#329 plan 1 Task 4: three more ALTER TABLE statements in the existing loop, routes ADD COLUMN egress_allow, size and policy_expires_at, each TEXT NOT NULL DEFAULT '' and idempotent through the duplicate-column rule; the same sixteen sites, no read added.;rev3=census-ruling-region-ha-p1a;basis=one more ALTER TABLE in the existing loop: routes ADD COLUMN ha INTEGER NOT NULL DEFAULT 0, idempotent through the duplicate-column rule; the same sixteen sites, no read added;rev3=census-ruling-ha-p1a-433;basis=the registry's SQLite side as carlos (agent, registry child; a box CLI verb that opens the registry directly runs it as whoever runs it), on every registry open: the ALTER TABLE routes statements are now built from the one migration definition routeAddedColumns (addedColumn name, type, default; review r1 P2): for each entry without the Claim mark, "ALTER TABLE routes ADD COLUMN " + spec(), byte for byte the statements main runs, in main's order, under the same duplicate-column rule. +registry:Claim is that mark, +whole:addedColumn the struct. Every name, type and default is an in-binary literal; no statement added, removed or changed; no read added. file:Exec@1694,file:Exec@2554,file:Exec@2833,file:Exec@3696,file:Exec@3872,file:Exec@51,file:Exec@600,file:Exec@963,registry:Claim@525,registry:sql@1694,registry:sql@2554,registry:sql@2833,registry:sql@3696,registry:sql@3872,registry:sql@51,registry:sql@600,registry:sql@963,whole:addedColumn@500 c1aa99249122d7976764fc6571eada4c1fbda98d52e96d493c64f3e39c31d5bd
+internal/registry/registry.go Registry.Get legacy accepted-legacy accepted-legacy;rev3=J1,J4;basis=route-and-input;rev3=census-ruling-ha-p1a-433;basis=same identities as List: +registry:sql is r.sql handed to readCols, the same connection the SELECT already used; same SELECT ... WHERE host = ? with the select list readCols returns (routeCols for a read-write registry). Root's instanceRegistryHostApp and instanceRegistryHostRuntime read Get through the read-only child and now work before the migration too. file:QueryRow@262,registry:Route@165,registry:remote@58,registry:remote@90,registry:sql@209,registry:sql@262,whole:Route@169,whole:Route@455,whole:remoteClient@60,whole:remoteClient@92 736f4a42df871f765a124ea532a38ba1c8ab8bf16375eb0c480f855ddf5c3e82
+@remove internal/instancectl/peer_linux.go productionPeerOK
+@removed internal/instancectl/peer_linux.go productionPeerOK H3 census-ruling-ha-p1a-433;basis=root (carlos-instance-control.service): reads nothing now. The systemctl MainPID read moved verbatim to systemdEdgeMainPID, and the decision and its one-second cache moved to edgePeer.check (internal/instancectl/peer_edge.go, envelope re-pinned). Acceptance is unchanged: SO_PEERCRED uid carlos AND pid equal to the MainPID systemd reports for carlos-edge.service. New in edgePeer.check: a peer the cached answer refuses (a stale pid or a cached failure, #433) is checked once against a fresh read before the refusal, at most one forced read per 100 ms; the peer is accepted only if the fresh MainPID equals it, so nothing wider is accepted.
+@coverage internal/host 797fbd93c1ef001e1a3cc2a21ab096695e919926e8eb3b2bf7d92c35722b2568
+@coverage internal/instancectl bd5c2dc71194fb61dd4dc3c34c0bc001b1f7ff3a605718161a3d68ff5e42be41
+@coverage internal/provision 97e8b635847f2d6808f21d7ae068f362993c69f547e02c5b311756da8f662c50
+@coverage internal/registry 40555af3a72b13fa691f023156257d3e8020fe26119edcbab940c6323978dffc
+@fields A,Account,Accounts,AddedAt,Addr,Addrs,Alias,Aliases,Alive,AllowAbsent,App,Archives,Args,AssetGen,AssetsOff,At,Attempts,B,Backing,Bucket,BuildState,Callback,CallbackError,CallbackFailed,Canary,Caps,CertExpiresAt,Changed,Channel,CheckedAt,Claim,ClaimIncarnation,ClaimOwner,ClaimOwnership,ClaimRowID,ClaimStamp,Class,Contents,CreatedAt,DBPath,DNSCheckedAt,DNSStatus,Deadline,Default,Demand,Digest,DoneBefore,Due,DueAt,EgressAllow,Env,EnvBefore,Environment,Error,ErrorKind,ExcludeHosts,ExpectGood,ExpectOp,ExpectPair,Expected,F,Failed,FenceGen,Fleet,FleetBox,FleetBoxes,Fleets,From,FromDB,FromOp,FromSock,Gate,GoodDemand,GoodDigest,GoodVersion,HA,Hash,Health,Held,Hibernate,HoldOp,Host,Hosts,ID,Id,IdValue,Idle,IdleSeconds,ImportGate,Incarnation,Journal,Keep,Kind,Label,LastAt,LastError,LastMs,LastStatus,Limit,MaxRun,MaxRunSeconds,Method,Ms,Name,Next,NextAt,NextDue,NextGood,NextValue,Now,Number,Number64,Observed,ObservedValue,Old,On,Op,Original,Owner,Ownership,P,Pair,Path,Paths,Platform,PolicyExpiresAt,Pool,Prefix,Prev,PrevVersion,Provisioned,RateLimit,RecordKey,Region,Registration,Replica,Replicas,Replication,Retirement,Route,Routes,Row,Rows,Runtime,Seed,SeedID,SeedSource,ServingSeq,ServingVersion,Size,Slug,Socket,Spec,Sqid,State,Status,StatusNamed,Steering,StringMap,T,TValue,Tags,Target,Targets,Text,Timer,Timers,Times,To,ToDB,ToOp,ToSock,TokenHash,Tunnel,Type,Unit,UpdateSettings,Ver,Version,W,WakeIncarnation,Wildcards,closed,conn,connect,ctx,d,dec,done,enc,full,input,mu,output,path,readOnly,remote,sql,wait
diff --git a/internal/registry/claimrows.go b/internal/registry/claimrows.go
index 4b164549c..237b2e91d 100644
--- a/internal/registry/claimrows.go
+++ b/internal/registry/claimrows.go
@@ -38,8 +38,11 @@ type ClaimRowArchive struct {
func (r *Registry) migrateClaimOwnership() error {
for _, table := range []string{"routes", "timers"} {
- for _, column := range []string{"claim_incarnation TEXT NOT NULL DEFAULT ''", "claim_stamp INTEGER NOT NULL DEFAULT 0", "claim_owner TEXT NOT NULL DEFAULT ''", "claim_row_id TEXT NOT NULL DEFAULT ''"} {
- if _, err := r.sql.Exec("ALTER TABLE " + table + " ADD COLUMN " + column); err != nil && !strings.Contains(err.Error(), "duplicate column") {
+ for _, c := range routeAddedColumns {
+ if !c.Claim {
+ continue
+ }
+ if _, err := r.sql.Exec("ALTER TABLE " + table + " ADD COLUMN " + c.spec()); err != nil && !strings.Contains(err.Error(), "duplicate column") {
return err
}
}
diff --git a/internal/registry/ha_test.go b/internal/registry/ha_test.go
index 9a8f53bd4..6ccdd97db 100644
--- a/internal/registry/ha_test.go
+++ b/internal/registry/ha_test.go
@@ -1,7 +1,10 @@
package registry
import (
+ "database/sql"
"path/filepath"
+ "reflect"
+ "strings"
"testing"
)
@@ -43,3 +46,157 @@ func TestHAMarkIsSticky(t *testing.T) {
t.Fatal("SetHA on an unknown host: want an error")
}
}
+
+// dropRouteColumns opens path read-write and drops cols from routes: the
+// registry an older agent left, before its successor's migration ran.
+func dropRouteColumns(t *testing.T, path string, cols ...string) {
+ t.Helper()
+ db, err := sql.Open("sqlite", path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer db.Close()
+ for _, c := range cols {
+ if _, err := db.Exec(`ALTER TABLE routes DROP COLUMN ` + c); err != nil {
+ t.Fatalf("drop %s: %v", c, err)
+ }
+ }
+}
+
+// #433: at the upgrade to P1a root read routes.ha before the new agent's
+// migration added it ("no such column: ha"), and egress slice naming
+// failed. A read-only registry, root's, reads a column the table lacks as
+// its migration default.
+func TestReadOnlyRegistryReadsBeforeTheAgentMigrates(t *testing.T) {
+ path := filepath.Join(t.TempDir(), "registry.db")
+ w, err := Open(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ rt := Route{Host: "shop.example.com", Kind: "instance", Status: "ready", App: "shop", Channel: "stable", EgressAllow: "203.0.113.7/32"}
+ if err := w.Upsert(rt); err != nil {
+ t.Fatal(err)
+ }
+ w.Close()
+ dropRouteColumns(t, path, "ha", "policy_expires_at")
+
+ ro, err := OpenReadOnly(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer ro.Close()
+ rows, err := ro.List()
+ if err != nil {
+ t.Fatalf("List without the ha column: %v", err)
+ }
+ if len(rows) != 1 || rows[0].Host != rt.Host || rows[0].HA || rows[0].PolicyExpiresAt != "" || rows[0].EgressAllow != rt.EgressAllow {
+ t.Fatalf("List = %+v", rows)
+ }
+ got, err := ro.Get(rt.Host)
+ if err != nil {
+ t.Fatalf("Get without the ha column: %v", err)
+ }
+ if got == nil || got.HA || got.App != "shop" || got.EgressAllow != rt.EgressAllow {
+ t.Fatalf("Get = %+v", got)
+ }
+ if got, err := ro.Get("absent.example.com"); err != nil || got != nil {
+ t.Fatalf("Get of an absent host = %+v, %v", got, err)
+ }
+}
+
+// routeAddedColumns, the one migration definition, is exactly routeCols
+// less the first CREATE's columns (review r1 P2, #433): a column read by
+// routeCols that no definition adds, or a definition routeCols does not
+// read, fails here. Each default is one a TEXT or INTEGER column can take.
+func TestRouteAddedColumnsIsEveryMigrationAddedColumn(t *testing.T) {
+ defined := map[string]bool{}
+ for _, c := range routeAddedColumns {
+ if defined[c.Name] {
+ t.Errorf("%s is defined twice", c.Name)
+ }
+ defined[c.Name] = true
+ if !(c.Type == "TEXT" && c.Default == "''") && !(c.Type == "INTEGER" && c.Default == "0") {
+ t.Errorf("%s: %s DEFAULT %s", c.Name, c.Type, c.Default)
+ }
+ }
+ read := map[string]bool{}
+ for _, c := range migrationAddedRouteCols() {
+ read[c] = true
+ if !defined[c] {
+ t.Errorf("routeCols reads %s, which no migration definition adds", c)
+ }
+ }
+ for c := range defined {
+ if !read[c] {
+ t.Errorf("%s is defined but not in routeCols", c)
+ }
+ }
+ for _, c := range []string{"ha", "claim_incarnation", "claim_stamp", "claim_owner", "claim_row_id"} {
+ if !defined[c] {
+ t.Errorf("%s missing", c)
+ }
+ }
+}
+
+// routesCreateColumns is the first CREATE TABLE routes's columns; every
+// other routeCols column is added by a migration.
+var routesCreateColumns = map[string]bool{
+ "host": true, "kind": true, "socket": true, "status": true, "last_error": true,
+ "db_path": true, "version": true, "prev_version": true, "created_at": true,
+}
+
+// migrationAddedRouteCols is routeCols less the first CREATE's columns,
+// read from routeCols itself rather than from any migration list.
+func migrationAddedRouteCols() []string {
+ var out []string
+ for _, c := range strings.Split(routeCols, ",") {
+ if c = strings.TrimSpace(c); !routesCreateColumns[c] {
+ out = append(out, c)
+ }
+ }
+ return out
+}
+
+// Review r1 P2 (#433): root's read-only List and Get work on a registry
+// that lacks ANY one migration-added routes column, each read as its
+// migration default, the claim ownership columns included.
+func TestReadOnlyRegistryReadsWithoutEachAddedColumn(t *testing.T) {
+ for _, c := range routeAddedColumns {
+ col := c.Name
+ t.Run(col, func(t *testing.T) {
+ path := filepath.Join(t.TempDir(), "registry.db")
+ w, err := Open(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ // Only first-CREATE columns set: every added column holds its
+ // default, which is what the stand-in must read back.
+ rt := Route{Host: "shop.example.com", Kind: "instance", Status: "ready", Socket: "/run/shop.sock"}
+ if err := w.Upsert(rt); err != nil {
+ t.Fatal(err)
+ }
+ want, err := w.Get(rt.Host)
+ if err != nil || want == nil {
+ t.Fatalf("writer Get: %+v, %v", want, err)
+ }
+ w.Close()
+ dropRouteColumns(t, path, col)
+ ro, err := OpenReadOnly(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer ro.Close()
+ rows, err := ro.List()
+ if err != nil {
+ t.Fatalf("List without %s: %v", col, err)
+ }
+ got, err := ro.Get(rt.Host)
+ if err != nil {
+ t.Fatalf("Get without %s: %v", col, err)
+ }
+ if len(rows) != 1 || !reflect.DeepEqual(rows[0], *want) || got == nil || !reflect.DeepEqual(*got, *want) {
+ t.Fatalf("without %s: List %+v, Get %+v, want %+v", col, rows, got, want)
+ }
+ })
+ }
+}
diff --git a/internal/registry/registry.go b/internal/registry/registry.go
index cf6ee2c8e..2fb646e27 100644
--- a/internal/registry/registry.go
+++ b/internal/registry/registry.go
@@ -638,6 +638,98 @@ func (r *Registry) Close() error {
return r.sql.Close()
}
+// addedColumn is one column a migration adds to an existing table: a
+// name, a type (TEXT or INTEGER) and its NOT NULL DEFAULT as SQL (the
+// empty string literal or 0). Claim marks the claim ownership columns,
+// which migrateClaimOwnership adds to routes and timers; migrate adds the
+// rest to routes.
+type addedColumn struct {
+ Name, Type, Default string
+ Claim bool
+}
+
+// spec is the column's ADD COLUMN text: "<name> <type> NOT NULL DEFAULT <default>".
+func (c addedColumn) spec() string {
+ return c.Name + " " + c.Type + " NOT NULL DEFAULT " + c.Default
+}
+
+// routeAddedColumns is the one definition of every column a migration adds
+// to routes after the first CREATE, in the order each migration adds them:
+// migrate and migrateClaimOwnership both range over it, and a read-only
+// reader stands each one's default in for a column the agent has not
+// added yet (readCols, #433).
+var routeAddedColumns = []addedColumn{
+ {Name: "slug", Type: "TEXT", Default: "''"},
+ {Name: "addr", Type: "TEXT", Default: "''"},
+ {Name: "app", Type: "TEXT", Default: "''"},
+ {Name: "pool", Type: "TEXT", Default: "''"},
+ {Name: "region", Type: "TEXT", Default: "''"},
+ {Name: "channel", Type: "TEXT", Default: "''"},
+ {Name: "hibernate", Type: "INTEGER", Default: "0"},
+ {Name: "canary", Type: "INTEGER", Default: "0"},
+ {Name: "replication", Type: "TEXT", Default: "''"},
+ {Name: "next_due", Type: "INTEGER", Default: "0"},
+ {Name: "backing", Type: "TEXT", Default: "''"},
+ {Name: "status_named", Type: "INTEGER", Default: "0"},
+ {Name: "platform", Type: "INTEGER", Default: "0"},
+ {Name: "dns_status", Type: "TEXT", Default: "''"},
+ {Name: "dns_checked_at", Type: "INTEGER", Default: "0"},
+ {Name: "cert_expires_at", Type: "INTEGER", Default: "0"},
+ {Name: "account", Type: "TEXT", Default: "''"},
+ {Name: "environment", Type: "TEXT", Default: "''"},
+ {Name: "caps", Type: "TEXT", Default: "''"},
+ {Name: "tunnel", Type: "TEXT", Default: "''"},
+ {Name: "provisioned", Type: "INTEGER", Default: "0"},
+ {Name: "seed", Type: "TEXT", Default: "''"},
+ {Name: "unit", Type: "TEXT", Default: "''"},
+ {Name: "fleet_box", Type: "TEXT", Default: "''"},
+ {Name: "addrs", Type: "TEXT", Default: "''"},
+ {Name: "health", Type: "TEXT", Default: "''"},
+ {Name: "steering", Type: "TEXT", Default: "''"},
+ {Name: "gate", Type: "TEXT", Default: "''"},
+ {Name: "args", Type: "TEXT", Default: "''"},
+ {Name: "idle_seconds", Type: "INTEGER", Default: "0"},
+ {Name: "max_run_seconds", Type: "INTEGER", Default: "0"},
+ {Name: "replicas", Type: "TEXT", Default: "''"},
+ {Name: "replica", Type: "INTEGER", Default: "0"},
+ {Name: "hold_op", Type: "TEXT", Default: "''"},
+ {Name: "good_version", Type: "TEXT", Default: "''"},
+ {Name: "good_digest", Type: "TEXT", Default: "''"},
+ {Name: "good_demand", Type: "TEXT", Default: "''"},
+ {Name: "serving_version", Type: "TEXT", Default: "''"},
+ {Name: "update_settings", Type: "TEXT", Default: "''"},
+ {Name: "build_state", Type: "TEXT", Default: "''"},
+ {Name: "seed_source", Type: "TEXT", Default: "''"},
+ {Name: "import_gate", Type: "TEXT", Default: "''"},
+ {Name: "runtime", Type: "TEXT", Default: "''"},
+ {Name: "rate_limit", Type: "TEXT", Default: "''"},
+ {Name: "assets_off", Type: "INTEGER", Default: "0"},
+ {Name: "asset_gen", Type: "TEXT", Default: "''"},
+ {Name: "incarnation", Type: "INTEGER", Default: "0"},
+ {Name: "serving_seq", Type: "INTEGER", Default: "0"},
+ // The app policy's converge (#328, #329; Route.EgressAllow): '' = none.
+ {Name: "egress_allow", Type: "TEXT", Default: "''"},
+ {Name: "size", Type: "TEXT", Default: "''"},
+ {Name: "policy_expires_at", Type: "TEXT", Default: "''"},
+ // Region HA P1a: the born-HA mark (Route.HA), sticky.
+ {Name: "ha", Type: "INTEGER", Default: "0"},
+ // Host claims' ownership (migrateClaimOwnership, routes and timers).
+ {Name: "claim_incarnation", Type: "TEXT", Default: "''", Claim: true},
+ {Name: "claim_stamp", Type: "INTEGER", Default: "0", Claim: true},
+ {Name: "claim_owner", Type: "TEXT", Default: "''", Claim: true},
+ {Name: "claim_row_id", Type: "TEXT", Default: "''", Claim: true},
+}
+
+// addedRouteColumnDefaults maps each column routeAddedColumns adds to its
+// DEFAULT as SQL: the empty string literal or 0.
+func addedRouteColumnDefaults() map[string]string {
+ out := map[string]string{}
+ for _, c := range routeAddedColumns {
+ out[c.Name] = c.Default
+ }
+ return out
+}
+
// migrate is additive (CREATE TABLE IF NOT EXISTS), so deploying new code
// over an existing registry is always safe. New columns go in the ALTER list —
// the "duplicate column" error is swallowed so the list stays idempotent.
@@ -656,63 +748,11 @@ CREATE TABLE IF NOT EXISTS routes (
);`); err != nil {
return err
}
- for _, stmt := range []string{
- `ALTER TABLE routes ADD COLUMN slug TEXT NOT NULL DEFAULT ''`,
- `ALTER TABLE routes ADD COLUMN addr TEXT NOT NULL DEFAULT ''`,
- `ALTER TABLE routes ADD COLUMN app TEXT NOT NULL DEFAULT ''`,
- `ALTER TABLE routes ADD COLUMN pool TEXT NOT NULL DEFAULT ''`,
- `ALTER TABLE routes ADD COLUMN region TEXT NOT NULL DEFAULT ''`,
- `ALTER TABLE routes ADD COLUMN channel TEXT NOT NULL DEFAULT ''`,
- `ALTER TABLE routes ADD COLUMN hibernate INTEGER NOT NULL DEFAULT 0`,
- `ALTER TABLE routes ADD COLUMN canary INTEGER NOT NULL DEFAULT 0`,
- `ALTER TABLE routes ADD COLUMN replication TEXT NOT NULL DEFAULT ''`,
- `ALTER TABLE routes ADD COLUMN next_due INTEGER NOT NULL DEFAULT 0`,
- `ALTER TABLE routes ADD COLUMN backing TEXT NOT NULL DEFAULT ''`,
- `ALTER TABLE routes ADD COLUMN status_named INTEGER NOT NULL DEFAULT 0`,
- `ALTER TABLE routes ADD COLUMN platform INTEGER NOT NULL DEFAULT 0`,
- `ALTER TABLE routes ADD COLUMN dns_status TEXT NOT NULL DEFAULT ''`,
- `ALTER TABLE routes ADD COLUMN dns_checked_at INTEGER NOT NULL DEFAULT 0`,
- `ALTER TABLE routes ADD COLUMN cert_expires_at INTEGER NOT NULL DEFAULT 0`,
- `ALTER TABLE routes ADD COLUMN account TEXT NOT NULL DEFAULT ''`,
- `ALTER TABLE routes ADD COLUMN environment TEXT NOT NULL DEFAULT ''`,
- `ALTER TABLE routes ADD COLUMN caps TEXT NOT NULL DEFAULT ''`,
- `ALTER TABLE routes ADD COLUMN tunnel TEXT NOT NULL DEFAULT ''`,
- `ALTER TABLE routes ADD COLUMN provisioned INTEGER NOT NULL DEFAULT 0`,
- `ALTER TABLE routes ADD COLUMN seed TEXT NOT NULL DEFAULT ''`,
- `ALTER TABLE routes ADD COLUMN unit TEXT NOT NULL DEFAULT ''`,
- `ALTER TABLE routes ADD COLUMN fleet_box TEXT NOT NULL DEFAULT ''`,
- `ALTER TABLE routes ADD COLUMN addrs TEXT NOT NULL DEFAULT ''`,
- `ALTER TABLE routes ADD COLUMN health TEXT NOT NULL DEFAULT ''`,
- `ALTER TABLE routes ADD COLUMN steering TEXT NOT NULL DEFAULT ''`,
- `ALTER TABLE routes ADD COLUMN gate TEXT NOT NULL DEFAULT ''`,
- `ALTER TABLE routes ADD COLUMN args TEXT NOT NULL DEFAULT ''`,
- `ALTER TABLE routes ADD COLUMN idle_seconds INTEGER NOT NULL DEFAULT 0`,
- `ALTER TABLE routes ADD COLUMN max_run_seconds INTEGER NOT NULL DEFAULT 0`,
- `ALTER TABLE routes ADD COLUMN replicas TEXT NOT NULL DEFAULT ''`,
- `ALTER TABLE routes ADD COLUMN replica INTEGER NOT NULL DEFAULT 0`,
- `ALTER TABLE routes ADD COLUMN hold_op TEXT NOT NULL DEFAULT ''`,
- `ALTER TABLE routes ADD COLUMN good_version TEXT NOT NULL DEFAULT ''`,
- `ALTER TABLE routes ADD COLUMN good_digest TEXT NOT NULL DEFAULT ''`,
- `ALTER TABLE routes ADD COLUMN good_demand TEXT NOT NULL DEFAULT ''`,
- `ALTER TABLE routes ADD COLUMN serving_version TEXT NOT NULL DEFAULT ''`,
- `ALTER TABLE routes ADD COLUMN update_settings TEXT NOT NULL DEFAULT ''`,
- `ALTER TABLE routes ADD COLUMN build_state TEXT NOT NULL DEFAULT ''`,
- `ALTER TABLE routes ADD COLUMN seed_source TEXT NOT NULL DEFAULT ''`,
- `ALTER TABLE routes ADD COLUMN import_gate TEXT NOT NULL DEFAULT ''`,
- `ALTER TABLE routes ADD COLUMN runtime TEXT NOT NULL DEFAULT ''`,
- `ALTER TABLE routes ADD COLUMN rate_limit TEXT NOT NULL DEFAULT ''`,
- `ALTER TABLE routes ADD COLUMN assets_off INTEGER NOT NULL DEFAULT 0`,
- `ALTER TABLE routes ADD COLUMN asset_gen TEXT NOT NULL DEFAULT ''`,
- `ALTER TABLE routes ADD COLUMN incarnation INTEGER NOT NULL DEFAULT 0`,
- `ALTER TABLE routes ADD COLUMN serving_seq INTEGER NOT NULL DEFAULT 0`,
- // The app policy's converge (#328, #329; Route.EgressAllow): '' = none.
- `ALTER TABLE routes ADD COLUMN egress_allow TEXT NOT NULL DEFAULT ''`,
- `ALTER TABLE routes ADD COLUMN size TEXT NOT NULL DEFAULT ''`,
- `ALTER TABLE routes ADD COLUMN policy_expires_at TEXT NOT NULL DEFAULT ''`,
- // Region HA P1a: the born-HA mark (Route.HA), sticky.
- `ALTER TABLE routes ADD COLUMN ha INTEGER NOT NULL DEFAULT 0`,
- } {
- if _, err := r.sql.Exec(stmt); err != nil && !strings.Contains(err.Error(), "duplicate column") {
+ for _, c := range routeAddedColumns {
+ if c.Claim {
+ continue // migrateClaimOwnership's, below
+ }
+ if _, err := r.sql.Exec("ALTER TABLE routes ADD COLUMN " + c.spec()); err != nil && !strings.Contains(err.Error(), "duplicate column") {
return err
}
}
@@ -1059,7 +1099,11 @@ func (r *Registry) List() ([]Route, error) {
}
db = fresh
}
- rows, err := db.Query(`SELECT ` + routeCols + ` FROM routes ORDER BY host`)
+ cols, err := r.readCols(db)
+ if err != nil {
+ return nil, err
+ }
+ rows, err := db.Query(`SELECT ` + cols + ` FROM routes ORDER BY host`)
if err != nil {
return nil, err
}
@@ -1075,6 +1119,54 @@ func (r *Registry) List() ([]Route, error) {
return out, rows.Err()
}
+// readCols is the select list List and Get read routes with over db. A
+// read-write registry has migrated, so it is routeCols. A read-only one is
+// root's, which can open a table an older agent left before its
+// successor's migrate adds the newest columns (#433: "no such column: ha"
+// at the upgrade to region HA P1a). So each routeCols column the table
+// lacks that routeAddedColumns adds is read as the default the migration
+// will give it ("0 AS ha"). A column of the first CREATE is never stood
+// in for: without it the read fails, as it always has.
+func (r *Registry) readCols(db *sql.DB) (string, error) {
+ if !r.readOnly {
+ return routeCols, nil
+ }
+ rows, err := db.Query(`SELECT name FROM pragma_table_info('routes')`)
+ if err != nil {
+ return "", err
+ }
+ defer rows.Close()
+ have := map[string]bool{}
+ for rows.Next() {
+ var name string
+ if err := rows.Scan(&name); err != nil {
+ return "", err
+ }
+ have[name] = true
+ }
+ if err := rows.Err(); err != nil {
+ return "", err
+ }
+ if len(have) == 0 {
+ return routeCols, nil // no routes table: the read fails as before
+ }
+ defaults := addedRouteColumnDefaults()
+ cols := strings.Split(routeCols, ",")
+ stood := false
+ for i, c := range cols {
+ c = strings.TrimSpace(c)
+ cols[i] = c
+ if def, ok := defaults[c]; ok && !have[c] {
+ cols[i] = def + " AS " + c
+ stood = true
+ }
+ }
+ if !stood {
+ return routeCols, nil
+ }
+ return strings.Join(cols, ", "), nil
+}
+
// Get returns the route for host, or (nil, nil) if there is none.
func (r *Registry) Get(host string) (*Route, error) {
if r.remote != nil {
@@ -1082,7 +1174,11 @@ func (r *Registry) Get(host string) (*Route, error) {
return out.Route, err
}
- row := r.sql.QueryRow(`SELECT `+routeCols+` FROM routes WHERE host = ?`, host)
+ cols, err := r.readCols(r.sql)
+ if err != nil {
+ return nil, err
+ }
+ row := r.sql.QueryRow(`SELECT `+cols+` FROM routes WHERE host = ?`, host)
t, err := scanRoute(row.Scan)
if err == sql.ErrNoRows {
return nil, nil