carlos / platform Public

alias-socket-follow-338: platform aliases follow their instance's socket, and a repair for stale ones (#338, #392)

A platform alias (the domains pass's apex mint) copied its source's socket
once; the layout pass nested the source and left the alias on the old flat
path, so seven flagship aliases answer 502.

- registry: SetInstancePaths (nest, un-nest, recovery) and Upsert (moves,
  re-mints, adoption, carlos add) carry the same tenant's platform aliases
  in the same transaction. Another account's or app's alias never moves.
- agent: every domains tick, on every platform box, an alias whose socket
  does not exist is repointed at the live socket of the one same-tenant
  route whose other-layout socket it names (RepointPlatformSocket re-checks
  tenant and sibling). Idempotent and logged.
- carlos status --layout: platform rows read alias (not external), with a
  reason when the socket is missing. Copy approved by delegation (Luna).
- Census: overlay alias-socket-follow-338 and the 9B8 LayoutSibling row,
  approved by Astra (#280). Astra round 1: READY AFTER FIXES, P2 fixed.

Needs a box release; not released or rolled.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Squashed from alias-socket-follow-338 into main.
claude agent, operated by paul@keymail.dev d3c5601be33f99fb64f293dc6d308b9301567c08 parent 1eb4e76
17 files changed, +1,100 −21
  • docs/site/cli.md +4 −2
  • docs/superpowers/notes/census-proposal-alias-socket-follow-338.md +27 −0
  • docs/superpowers/reviews/CODEX-FINDINGS-alias-socket-follow-338.md +44 −0
  • docs/superpowers/reviews/CODEX-REVIEW-BRIEF-alias-socket-follow-338.md +121 −0
  • internal/console/apistatuslayout_test.go +4 −0
  • internal/host/agent.go +4 −0
  • internal/host/aliassocket.go +95 −0
  • internal/host/aliassocket_test.go +216 −0
  • internal/host/layoutleg.go +26 −0
  • internal/layout/aliassocket_linux_test.go +87 −0
  • internal/provision/layoutsibling_test.go +24 −0
  • internal/provision/plan9_b8_census_test.go +2 −0
  • internal/provision/testdata/plan14-root-reads-alias-socket-follow-338.tsv +28 −0
  • internal/provision/testdata/plan14-root-reads-chain.tsv +1 −0
  • internal/registry/aliassocket.go +161 −0
  • internal/registry/aliassocket_test.go +198 −0
  • internal/registry/registry.go +58 −19

CI passed — run details

diff --git a/docs/site/cli.md b/docs/site/cli.md
index 3df4506f6..42cf3ac0a 100644
--- a/docs/site/cli.md
+++ b/docs/site/cli.md
@@ -2317,8 +2317,10 @@ directory, where it cannot see its neighbours. `fenced` means a move between
the two is in progress or stopped part way, and `conflict` means two routes
claim the same directory; neither wakes until that is resolved. `foreign`
rows have paths the layout pass does not recognise and leaves alone, and
-`external` rows are run by another supervisor. Like `--instances`, it goes
-through the console and is operator only.
+`external` rows are run by another supervisor. `alias` rows are platform
+addresses that use another instance's process. `REASON` says when the alias
+socket does not exist. Requests to that address then fail. Like
+`--instances`, it goes through the console and is operator only.
The REGION column names where each route or box runs, such as London (UK).
diff --git a/docs/superpowers/notes/census-proposal-alias-socket-follow-338.md b/docs/superpowers/notes/census-proposal-alias-socket-follow-338.md
new file mode 100644
index 000000000..d51253666
--- /dev/null
+++ b/docs/superpowers/notes/census-proposal-alias-socket-follow-338.md
@@ -0,0 +1,27 @@
+# Census approval: alias-socket-follow-338
+
+Ruling `census-ruling-alias-socket-follow-338`. The independent reviewer approves or rejects every change below, 13 with a new disposition; nothing goes to the census owner (Paul, #280, 2026-10-26).
+
+Envelopes re-pinned: `internal/host`, `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.
+
+New dispositions, which census-propose wrote and the reviewer checks against the unit's reads and the diff:
+
+- new `internal/host/aliassocket.go:liveSocket`: reads +file:Lstat; written legacy, accepted-legacy, frozen
+- new `internal/host/aliassocket.go:repairPlatformAliases`: reads +registry:Account ×2, +registry:App ×3, +registry:Host ×12, +registry:Platform ×2, +registry:Socket ×11, +whole:Route ×13; written legacy, accepted-legacy, frozen
+- new `internal/host/layoutleg.go:aliasLayout`: reads +registry:Socket ×2; written legacy, accepted-legacy, frozen
+- new `internal/registry/aliassocket.go:Registry.RepointPlatformSocket`: reads +file:Exec, +registry:Host ×2, +registry:Platform, +registry:Socket ×6, +whole:Route ×5; written legacy, accepted-legacy, frozen
+- new `internal/registry/aliassocket.go:Registry.inImmediateTx`: reads +registry:remote, +whole:claimTransaction, +whole:remoteClient; written legacy, accepted-legacy, frozen
+- new `internal/registry/aliassocket.go:carriesAliases`: reads +registry:App, +registry:Platform, +registry:Socket; written legacy, accepted-legacy, frozen
+- new `internal/registry/aliassocket.go:carryAliasesTx`: reads +file:Exec, +registry:Account, +registry:App, +registry:Host ×2, +registry:Socket ×3, +whole:Route; written legacy, accepted-legacy, frozen
+- new `internal/registry/aliassocket.go:sameTenant`: reads +registry:Account ×2, +registry:App ×2; written legacy, accepted-legacy, frozen
+- new `internal/registry/registry.go:upsertRoute`: reads +file:Exec, +whole:Route; written legacy, accepted-legacy, frozen
+- reads `internal/host/layoutleg.go:layoutStatusReport`: +registry:Hibernate, +registry:Host, +registry:Platform, +registry:Socket, +whole:Route; keeps diagnostic, task H3
+- reads `internal/host/layoutleg.go:unmanagedLayoutReport`: +registry:Hibernate, +registry:Host, +registry:Platform, +registry:Socket, +whole:Route; keeps diagnostic, task H3
+- reads `internal/registry/registry.go:Registry.SetInstancePaths`: -registry:sql ×2, +whole:Route ×2; keeps legacy, task accepted-legacy
+- reads `internal/registry/registry.go:Registry.Upsert`: -file:Exec, +registry:Host ×3, +registry:Platform, +registry:Socket ×2, +whole:Route ×7; keeps authority, task E3
+
+Seal: `f4e36134015ec6d09bada7be500c8faad22450afda12d033a8e3e24b1e8bb361` → `5192052a23d2fdd6f5d48b5617fe28a9bb03458e1e931c060fbdc42c3d627927`.
+
+Overlay: `internal/provision/testdata/plan14-root-reads-alias-socket-follow-338.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`.
diff --git a/docs/superpowers/reviews/CODEX-FINDINGS-alias-socket-follow-338.md b/docs/superpowers/reviews/CODEX-FINDINGS-alias-socket-follow-338.md
new file mode 100644
index 000000000..ff8e5ba42
--- /dev/null
+++ b/docs/superpowers/reviews/CODEX-FINDINGS-alias-socket-follow-338.md
@@ -0,0 +1,44 @@
+Census verdicts for `ae549c5f2d0af2fb9aecb7fda9698897f0e7267c`, reviewing `git diff origin/main...HEAD`:
+
+| Unit or envelope | Verdict | Evidence and basis |
+|---|---|---|
+| `liveSocket` | APPROVE | [aliassocket.go:39](/home/paulca/amadan.net/carlos/platform-alias-socket/internal/host/aliassocket.go:39): agent-side `Lstat`; no file opening or new root caller. |
+| `repairPlatformAliases` | APPROVE | [aliassocket.go:46](/home/paulca/amadan.net/carlos/platform-alias-socket/internal/host/aliassocket.go:46): filters by effective account and app, excludes platform/sidecar sources, requires one matching source. Transaction revalidates tenancy. |
+| `aliasLayout` | APPROVE | [layoutleg.go:237](/home/paulca/amadan.net/carlos/platform-alias-socket/internal/host/layoutleg.go:237): status-only socket check. |
+| `Registry.RepointPlatformSocket` | APPROVE | [aliassocket.go:127](/home/paulca/amadan.net/carlos/platform-alias-socket/internal/registry/aliassocket.go:127): rereads both rows under the write lock; checks platform/source shape, tenant and sibling relationship before updating. |
+| `Registry.inImmediateTx` | APPROVE | [aliassocket.go:100](/home/paulca/amadan.net/carlos/platform-alias-socket/internal/registry/aliassocket.go:100): rejects remote handles; uses the existing transaction implementation and rolls back errors. |
+| `carriesAliases` | APPROVE | [aliassocket.go:64](/home/paulca/amadan.net/carlos/platform-alias-socket/internal/registry/aliassocket.go:64): column predicate only; excludes sidecars and platform sources. |
+| `carryAliasesTx` | APPROVE | [aliassocket.go:76](/home/paulca/amadan.net/carlos/platform-alias-socket/internal/registry/aliassocket.go:76): updates only matching platform rows of the source’s effective account and app. |
+| `sameTenant` | APPROVE | [aliassocket.go:70](/home/paulca/amadan.net/carlos/platform-alias-socket/internal/registry/aliassocket.go:70): uses the established effective-account rule and exact app equality. |
+| `upsertRoute` | APPROVE | [registry.go:1334](/home/paulca/amadan.net/carlos/platform-alias-socket/internal/registry/registry.go:1334): extracted SQL and error handling are byte-identical to the previous implementation, apart from the executor name. Ownership refusal and normalization remain intact. |
+| `layoutStatusReport` | APPROVE | [layoutleg.go:214](/home/paulca/amadan.net/carlos/platform-alias-socket/internal/host/layoutleg.go:214): changes the reported classification of unmanaged platform sockets. |
+| `unmanagedLayoutReport` | APPROVE | [layoutleg.go:265](/home/paulca/amadan.net/carlos/platform-alias-socket/internal/host/layoutleg.go:265): journal/hold checks retain precedence; root’s separate downgrade guard still checks nested paths directly. |
+| `Registry.SetInstancePaths` | APPROVE | [registry.go:1993](/home/paulca/amadan.net/carlos/platform-alias-socket/internal/registry/registry.go:1993): preserves CAS conditions and error texts; carries aliases only after success, within the same transaction. |
+| `Registry.Upsert` | APPROVE | [registry.go:1300](/home/paulca/amadan.net/carlos/platform-alias-socket/internal/registry/registry.go:1300): preserves remote dispatch; ownership refusal precedes carry; previous sockets are followed only across the same tenant. |
+| `internal/host` envelope | APPROVE | Reviewed the above host changes and [agent.go:3797](/home/paulca/amadan.net/carlos/platform-alias-socket/internal/host/agent.go:3797). Repair runs after health stamping on each non-fleet domains tick, outside the housekeeper lease gate. |
+| `internal/registry` envelope | APPROVE | Reviewed both changed production files and transaction/remote callers. No new root filesystem access or weakened tenant boundary found. Functional issue below remains. |
+| New 9B8 `LayoutSibling` row | APPROVE | [plan9_b8_census_test.go:656](/home/paulca/amadan.net/carlos/platform-alias-socket/internal/provision/plan9_b8_census_test.go:656): pure path construction, no record write. Its recorded digest matches the function’s source. |
+
+P1: None found.
+
+**P2 — Brief §4: `LayoutSibling` misclassifies the nested socket for host `app`.**
+
+At [internal/registry/aliassocket.go:54](/home/paulca/amadan.net/carlos/platform-alias-socket/internal/registry/aliassocket.go:54), the generic flat-socket case precedes the nested case. Consequently:
+
+```text
+LayoutSibling("app", "/run/carlos/instances/app/app.sock")
+returns /run/carlos/instances/app/instances/app/app.sock
+wanted /run/carlos/app.sock
+```
+
+`app` is a valid hostname under [ValidHostShape](/home/paulca/amadan.net/carlos/platform-alias-socket/launchctx/controlname/names.go:18), and [addRail](/home/paulca/amadan.net/carlos/platform-alias-socket/cli.go:1389) permits it. For an already-nested source named `app` with an alias still pointing at `/run/carlos/app.sock`, repair finds no source and leaves the alias broken. Inserting that nested source over the stale alias also misses the carry.
+
+Fix: recognize the complete nested shape before the generic flat basename. Add `app` to the provision parity test and cover this stale-alias repair case. **Fault family:** flat/nested socket identity must round-trip for every supported host. Tenant isolation remains intact.
+
+P3: None found.
+
+The layout tests call the real `Pass` and registry, including recovery. Socket changes participate in the edge fingerprint. Formatting and `git diff --check` passed. Targeted Go tests could not start: the read-only sandbox refused creation of Go’s build directory. No full suites ran, and no files changed.
+
+This round has no P1; apply the P2 without reopening general review, retaining the required census check for the changed function and envelope.
+
+READY AFTER FIXES
\ No newline at end of file
diff --git a/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-alias-socket-follow-338.md b/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-alias-socket-follow-338.md
new file mode 100644
index 000000000..97759139d
--- /dev/null
+++ b/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-alias-socket-follow-338.md
@@ -0,0 +1,121 @@
+# Review brief: branch alias-socket-follow-338, round 1 of 3
+
+Repo carlos/platform, branch `alias-socket-follow-338`, commit dcd8cde331f708657620a72ee7f29b35964df2bd.
+Under review: the diff `78c23655e35b1914386f4dd9a59c3e2c48c0f9ed..dcd8cde331f708657620a72ee7f29b35964df2bd` (`git diff origin/main...HEAD`).
+Authorities: AGENTS.md on main (stopping rules, the census); amadan
+discussions #338 and #392 (the fault). Do not review against unmerged
+branches; if this work needs one, say so as a P1 and stop.
+
+You are an independent reviewer. Read the diff, then the code it touches
+and calls, and check every claim against that code.
+
+## The change
+
+A platform alias (`Route.Platform`, minted by internal/domains/reconcile.go
+`mintedRoute`, the `<app>.<sqid>.<apps-domain>` apex) copies its source
+route's socket once. The layout pass (internal/layout) moved instance rows
+from `/run/carlos/<host>.sock` to `/run/carlos/instances/<id>/app.sock`
+through `registry.SetInstancePaths` and never touched the aliases, so
+seven flagship aliases name a socket that does not exist and answer 502.
+
+1. internal/registry/aliassocket.go, registry.go: `SetInstancePaths` and
+ `Upsert` (for a non-platform, non-sidecar row with an app and a socket)
+ now run in one BEGIN IMMEDIATE transaction that also moves the same
+ tenant's platform rows (same effective account, same app) naming the
+ row's previous socket (Upsert: only if the previous row was the same
+ tenant) or its other-layout socket (`LayoutSibling`) to the row's
+ socket. Every other Upsert keeps the old single statement.
+2. internal/host/aliassocket.go: `repairPlatformAliases`, run by the
+ agent's domainsLoop after StampHealth on every platform box, every
+ tick: a platform row whose socket does not exist (Lstat, ModeSocket)
+ is repointed at the live socket of the one same-tenant route whose
+ other-layout socket it names, through `Registry.RepointPlatformSocket`,
+ which re-checks the tenant and the sibling relation in its own
+ transaction (agent handle only; refuses on a remote handle).
+3. internal/host/layoutleg.go: `carlos status --layout` names a platform
+ row `alias` (it was `external`, which also tripped the console's mixed
+ warning), with a reason when its socket does not exist. The console's
+ `layoutMixed` ignores unknown words already; a test pins it.
+4. Census: overlay `plan14-root-reads-alias-socket-follow-338`, card
+ docs/superpowers/notes/census-proposal-alias-socket-follow-338.md;
+ 9B8 inventory row for `LayoutSibling` (plan9_b8_census_test.go).
+
+## Fixed: do not re-argue
+
+- Paul approved building this box fix on 2026-10-26 ("Build the box
+ fix"). An apex on two boxes is by design (#392).
+- Out of scope, already reported as follow-ups: an alias whose source row
+ is gone from the box (moved away) stays stale and is logged; an alias
+ row has Hibernate false, so the edge never wakes a sleeping source
+ through it (pre-existing, internal/edge/edge.go:943).
+- Copy (the `alias` word, its reason, the cli.md sentence) is approved by
+ delegation; do not review wording.
+
+## What to check
+
+1. Tenant boundary (the invariant): no path in the diff ever points a
+ platform row at a socket of a row of another effective account or
+ another app: the SQL in `carryAliasesTx`, `RepointPlatformSocket`,
+ the repair's selection, the re-tenanted-host case in Upsert, legacy
+ rows with an empty or invalid account (EffectiveAccount).
+2. Upsert's semantics for every caller: the ON CONFLICT statement and its
+ claim-ownership refusal (ErrClaimOwnership must still leave nothing
+ written), normalizeRoute, the remote path (root's registry child runs
+ the same code), single-connection pool and BEGIN IMMEDIATE (deadlock
+ or SQLITE_BUSY risk for callers that already hold the connection or a
+ transaction, e.g. WithHoldsFrozen, claim transactions, import swap).
+3. `SetInstancePaths`: the CAS and its error texts unchanged; the carry
+ atomic with it; a missed CAS carries nothing; journal recovery
+ (internal/layout/pass.go recoverHost) gets the carry too.
+4. `LayoutSibling` against provision.DefaultSocket/NestedSocket/InstanceID
+ (the duplicate is pinned by internal/provision/layoutsibling_test.go);
+ odd inputs (hosts with dots only, long hosts, relative or unclean
+ paths).
+5. The repair: correctness, idempotence, races with a concurrent layout
+ move or Upsert, log volume on a box with many stale rows, cost per tick.
+6. Does anything else read a platform row's socket and depend on it not
+ changing (hostbox, claims, edge, appconfig syncexec, status, console)?
+7. Tests: are they production-wired where they claim (the layout test
+ drives the real Pass and registry), and do they fail when the
+ mechanism is removed?
+
+## Census
+
+Give a verdict for every unit and both re-pinned envelopes on the card
+(docs/superpowers/notes/census-proposal-alias-socket-follow-338.md), and
+for the new 9B8 inventory row, per AGENTS.md "The census": reject if the
+change lets root open, run, query or follow anything it did not before
+from a path or input a tenant, an app or a box agent can create, write or
+name; if it weakens a check, refusal, validation, argument or environment
+root relies on; if a new disposition is wrong for the unit's reads; or if
+the diff cannot settle any of these. Otherwise approve. Cite the lines
+you read.
+
+## Severity
+
+- **P1**: unsafe, would not compile, a test fails, or it would not work.
+ Blocks merge.
+- **P2**: wrong or missing. Fixed without reopening this review. (The
+ census, and review of any newly changed security, root, termination
+ or production-storage behaviour, still check the fix; see AGENTS.md,
+ "Stopping rules".)
+- **P3**: clarity or polish. Goes on a follow-up list; never a reason for
+ another round.
+
+A P1 states its failure scenario and the evidence (file:line). Do not
+raise a P2 to P1 to keep the review open.
+
+## Output
+
+Census verdicts first. Then findings ranked P1, P2, P3. Each gives the
+section, the problem, the evidence (file:line, verified), the failure
+scenario, a concrete fix and the invariant or trust boundary it breaks
+(that is its fault family). End with exactly one verdict:
+
+- **READY**: no P1 and no P2.
+- **READY AFTER FIXES**: no P1. The listed P2s are 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.
diff --git a/internal/console/apistatuslayout_test.go b/internal/console/apistatuslayout_test.go
index 842997c4e..182952547 100644
--- a/internal/console/apistatuslayout_test.go
+++ b/internal/console/apistatuslayout_test.go
@@ -184,6 +184,9 @@ func TestLayoutMixedNeedsANestedAndAFlatRow(t *testing.T) {
{[]string{"nested", "foreign"}, true},
{[]string{"nested", "external"}, true},
{[]string{"nested", "fenced", "conflict"}, false},
+ // A platform alias (#338) is another route's socket under a second
+ // name, no process of its own: it counts for neither side.
+ {[]string{"nested", "alias"}, false},
{[]string{"foreign", "external", "flat"}, false},
{nil, false},
} {
@@ -201,6 +204,7 @@ func TestLayoutMixedNeedsANestedAndAFlatRow(t *testing.T) {
{[]string{"flat"}, true},
{[]string{"nested", "nested"}, false},
{[]string{"fenced"}, false},
+ {[]string{"alias", "nested"}, false},
{nil, false},
} {
if got := layoutMixed("nested", rows(tc.layouts...)); got != tc.want {
diff --git a/internal/host/agent.go b/internal/host/agent.go
index 5bd85df81..811b0ee89 100644
--- a/internal/host/agent.go
+++ b/internal/host/agent.go
@@ -3798,6 +3798,10 @@ func domainsLoop(reg *registry.Registry, acmeCacheFlag string, hostClaim bool) {
if err := domains.StampHealth(ctx, reg, cfg, nil); err != nil {
log.Printf("agent: domains health: %v", err)
}
+ // Per-box as well: a platform alias minted on this box and left
+ // naming a socket that no longer exists (#338, #392) is pointed
+ // back at its source's live socket. See aliassocket.go.
+ repairPlatformAliases(reg, liveSocket)
}
}
}
diff --git a/internal/host/aliassocket.go b/internal/host/aliassocket.go
new file mode 100644
index 000000000..c7c594a26
--- /dev/null
+++ b/internal/host/aliassocket.go
@@ -0,0 +1,95 @@
+package host
+
+import (
+ "log"
+ "os"
+ "sync"
+
+ "github.com/carlosframework/platform/internal/registry"
+)
+
+// The platform alias repair (#338, #392).
+//
+// A platform alias (the domains pass's apex mint) copied its source
+// instance's socket once, and before #338 nothing moved it when the layout
+// pass nested the source. Those aliases still name the flat
+// /run/carlos/<host>.sock, which no longer exists, and answer 502. The
+// registry now carries aliases with every socket move; this pass repairs
+// the ones left behind, on every box, every domains tick.
+//
+// An alias is repaired only when all of these hold:
+// - its socket does not exist;
+// - exactly one route of its own tenant (effective account and app) has
+// the alias's socket as its socket in the other layout
+// (registry.LayoutSibling), so the alias was that route's copy;
+// - that route's socket exists now (an instance asleep is left for a
+// later tick).
+//
+// registry.RepointPlatformSocket re-checks the tenant and the sibling in
+// the same transaction as the write, so a route of another account or app
+// is never the target, whatever this pass reads. Idempotent: a repaired
+// alias names a live socket and is skipped from then on.
+
+// aliasSocketNoted remembers, per alias host, the stale socket this
+// process has already logged it could not repair, so a standing condition
+// logs once rather than every tick.
+var aliasSocketNoted sync.Map
+
+// liveSocket reports whether path exists and is a unix socket.
+func liveSocket(path string) bool {
+ fi, err := os.Lstat(path)
+ return err == nil && fi.Mode()&os.ModeSocket != 0
+}
+
+// repairPlatformAliases is one pass of the repair over reg, with live as
+// the socket check. It returns how many aliases it repointed.
+func repairPlatformAliases(reg *registry.Registry, live func(string) bool) int {
+ routes, err := reg.List()
+ if err != nil {
+ log.Printf("agent: platform alias repair: %v", err)
+ return 0
+ }
+ fixed := 0
+ for _, a := range routes {
+ if !a.Platform || a.Socket == "" || live(a.Socket) {
+ continue
+ }
+ var sources []registry.Route
+ for _, s := range routes {
+ if s.Platform || s.IsSidecar() || s.App == "" || s.Socket == "" || s.App != a.App ||
+ registry.EffectiveAccount(s.Account) != registry.EffectiveAccount(a.Account) {
+ continue
+ }
+ if registry.LayoutSibling(s.Host, s.Socket) == a.Socket {
+ sources = append(sources, s)
+ }
+ }
+ why := ""
+ switch {
+ case len(sources) == 0:
+ why = "no route of the same account and app on this box has it as its other-layout socket"
+ case len(sources) > 1:
+ why = "more than one route of the same account and app could own it"
+ case !live(sources[0].Socket):
+ why = "its source " + sources[0].Host + " has no live socket yet (asleep?); retried every tick"
+ }
+ if why != "" {
+ if prev, ok := aliasSocketNoted.Load(a.Host); !ok || prev != a.Socket {
+ aliasSocketNoted.Store(a.Host, a.Socket)
+ log.Printf("agent: platform alias %s names %s, which does not exist; left as is: %s", a.Host, a.Socket, why)
+ }
+ continue
+ }
+ changed, err := reg.RepointPlatformSocket(a.Host, sources[0].Host)
+ if err != nil {
+ log.Printf("agent: platform alias %s: repair onto %s refused: %v", a.Host, sources[0].Host, err)
+ continue
+ }
+ if changed {
+ fixed++
+ aliasSocketNoted.Delete(a.Host)
+ log.Printf("agent: platform alias %s repaired: %s did not exist, now %s (the socket of %s)", a.Host, a.Socket, sources[0].Socket, sources[0].Host)
+ }
+ }
+ return fixed
+}
diff --git a/internal/host/aliassocket_test.go b/internal/host/aliassocket_test.go
new file mode 100644
index 000000000..254e9963c
--- /dev/null
+++ b/internal/host/aliassocket_test.go
@@ -0,0 +1,216 @@
+package host
+
+import (
+ "net"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+
+ "github.com/carlosframework/platform/internal/layout"
+ "github.com/carlosframework/platform/internal/registry"
+ "github.com/carlosframework/platform/internal/status"
+)
+
+// listenAt binds a real unix socket at path for the test's life.
+func listenAt(t *testing.T, path string) {
+ t.Helper()
+ if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil {
+ t.Fatal(err)
+ }
+ l, err := net.Listen("unix", path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { l.Close() })
+}
+
+// aliasRepairBox is a registry with the stale shape #392 found on a box:
+// the source instance nested, and its apex alias still naming the flat
+// socket, which does not exist. Only a write of the source carries its
+// aliases, so writing the alias after the source leaves exactly the row a
+// pre-#338 nesting left behind. The source's socket is not bound yet.
+func aliasRepairBox(t *testing.T) (*registry.Registry, string, string) {
+ t.Helper()
+ dir, err := os.MkdirTemp("", "as")
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { os.RemoveAll(dir) })
+ src := "shop-a.abc.example.com"
+ flat := filepath.Join(dir, src+".sock")
+ nested := registry.LayoutSibling(src, flat)
+ reg, err := registry.Open(filepath.Join(t.TempDir(), "registry.db"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { reg.Close() })
+ for _, rt := range []registry.Route{
+ {Host: src, Kind: "instance", App: "shop", Account: "abc", Hibernate: true, Socket: nested, Status: "ready"},
+ {Host: "shop.abc.example.com", Kind: "instance", App: "shop", Account: "abc", Platform: true, Socket: flat, Status: "ready"},
+ } {
+ if err := reg.Upsert(rt); err != nil {
+ t.Fatal(err)
+ }
+ }
+ return reg, flat, nested
+}
+
+func socketAt(t *testing.T, reg *registry.Registry, host string) string {
+ t.Helper()
+ rt, err := reg.Get(host)
+ if err != nil || rt == nil {
+ t.Fatal(rt, err)
+ }
+ return rt.Socket
+}
+
+func TestRepairPlatformAliasesFixesAStaleRowOnce(t *testing.T) {
+ reg, flat, nested := aliasRepairBox(t)
+ // Asleep: the source has no live socket, so the alias waits.
+ if n := repairPlatformAliases(reg, liveSocket); n != 0 {
+ t.Fatalf("repaired %d with the source asleep", n)
+ }
+ if got := socketAt(t, reg, "shop.abc.example.com"); got != flat {
+ t.Fatalf("alias moved to %q with the source asleep", got)
+ }
+ listenAt(t, nested)
+ if n := repairPlatformAliases(reg, liveSocket); n != 1 {
+ t.Fatalf("repaired %d, want 1", n)
+ }
+ if got := socketAt(t, reg, "shop.abc.example.com"); got != nested {
+ t.Errorf("alias = %q, want %q", got, nested)
+ }
+ // Idempotent.
+ if n := repairPlatformAliases(reg, liveSocket); n != 0 {
+ t.Errorf("second pass repaired %d", n)
+ }
+}
+
+// The repair never points an alias across tenants: another account's
+// alias naming the flat socket of this account's instance stays put, and
+// so does an alias naming the flat socket of another account's live
+// instance.
+func TestRepairPlatformAliasesNeverCrossesTenants(t *testing.T) {
+ reg, flat, nested := aliasRepairBox(t)
+ listenAt(t, nested)
+ // xyz's alias names abc's flat socket.
+ if err := reg.Upsert(registry.Route{Host: "shop-2.xyz.example.com", Kind: "instance", App: "shop", Account: "xyz", Platform: true, Socket: flat, Status: "ready"}); err != nil {
+ t.Fatal(err)
+ }
+ // abc's alias names the flat socket of xyz's live nested instance.
+ other := "shop-b.xyz.example.com"
+ otherFlat := filepath.Join(filepath.Dir(flat), other+".sock")
+ otherNested := registry.LayoutSibling(other, otherFlat)
+ for _, rt := range []registry.Route{
+ {Host: other, Kind: "instance", App: "shop", Account: "xyz", Hibernate: true, Socket: otherNested, Status: "ready"},
+ {Host: "shop-old.abc.example.com", Kind: "instance", App: "shop", Account: "abc", Platform: true, Socket: otherFlat, Status: "ready"},
+ {Host: "shop.xyz.example.com", Kind: "instance", App: "shop", Account: "xyz", Platform: true, Socket: otherFlat, Status: "ready"},
+ } {
+ if err := reg.Upsert(rt); err != nil {
+ t.Fatal(err)
+ }
+ }
+ listenAt(t, otherNested)
+
+ repairPlatformAliases(reg, liveSocket)
+ if got := socketAt(t, reg, "shop-2.xyz.example.com"); got != flat {
+ t.Errorf("xyz's alias was pointed at %q", got)
+ }
+ if got := socketAt(t, reg, "shop-old.abc.example.com"); got != otherFlat {
+ t.Errorf("abc's alias was pointed at %q, xyz's socket", got)
+ }
+ // The repair still did its own tenant's work.
+ if got := socketAt(t, reg, "shop.abc.example.com"); got != nested {
+ t.Errorf("abc's alias = %q, want %q", got, nested)
+ }
+ // xyz's own alias at xyz's flat path is xyz's, and is repaired.
+ if got := socketAt(t, reg, "shop.xyz.example.com"); got != otherNested {
+ t.Errorf("xyz's alias = %q", got)
+ }
+}
+
+// `carlos status --layout` names a platform alias "alias", not "external"
+// (which also made a nested box read as mixed), and says when the socket
+// it names does not exist (#338). Both with a layout pass armed and without.
+func TestLayoutReportFlagsAnAliasWithNoSocket(t *testing.T) {
+ dir, err := os.MkdirTemp("", "as")
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { os.RemoveAll(dir) })
+ live := filepath.Join(dir, "live.sock")
+ listenAt(t, live)
+ dead := filepath.Join(dir, "dead.sock")
+ routes := []registry.Route{
+ {Host: "ok.abc.example.com", Kind: "instance", App: "shop", Account: "abc", Platform: true, Socket: live},
+ {Host: "stale.abc.example.com", Kind: "instance", App: "shop", Account: "abc", Platform: true, Socket: dead},
+ {Host: "external.example.com", Kind: "instance", Socket: dead},
+ }
+ check := func(t *testing.T, got map[string]string, reasons map[string]string) {
+ t.Helper()
+ want := map[string]string{"ok.abc.example.com": "alias", "stale.abc.example.com": "alias", "external.example.com": "external"}
+ for h, w := range want {
+ if got[h] != w {
+ t.Errorf("%s = %q, want %q", h, got[h], w)
+ }
+ }
+ if reasons["ok.abc.example.com"] != "" {
+ t.Errorf("a live alias has a reason: %q", reasons["ok.abc.example.com"])
+ }
+ if r := reasons["stale.abc.example.com"]; !strings.Contains(r, dead) || !strings.Contains(r, "does not exist") {
+ t.Errorf("stale alias reason = %q", r)
+ }
+ }
+ split := func(rep *status.LayoutReport) (map[string]string, map[string]string) {
+ words, reasons := map[string]string{}, map[string]string{}
+ for h, r := range rep.Rows {
+ words[h], reasons[h] = r.Layout, r.Reason
+ }
+ return words, reasons
+ }
+ t.Run("unmanaged", func(t *testing.T) {
+ resetLayoutGlobals(t)
+ t.Setenv("CARLOS_DATA_DIR", t.TempDir())
+ w, r := split(layoutStatusReport(routes))
+ check(t, w, r)
+ })
+ t.Run("armed", func(t *testing.T) {
+ resetLayoutGlobals(t)
+ armedLayoutPass.Store(&layout.Pass{DataDir: t.TempDir(), SocketDir: t.TempDir()})
+ w, r := split(layoutStatusReport(routes))
+ check(t, w, r)
+ })
+}
+
+// Astra r1 P2: the host "app", whose nested socket's base name is also
+// its flat one, is repaired like any other.
+func TestRepairPlatformAliasesHostNamedApp(t *testing.T) {
+ dir, err := os.MkdirTemp("", "as")
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { os.RemoveAll(dir) })
+ flat := filepath.Join(dir, "app.sock")
+ nested := filepath.Join(dir, "instances", "app", "app.sock")
+ reg, err := registry.Open(filepath.Join(t.TempDir(), "registry.db"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { reg.Close() })
+ for _, rt := range []registry.Route{
+ {Host: "app", Kind: "instance", App: "shop", Account: "abc", Hibernate: true, Socket: nested, Status: "ready"},
+ {Host: "shop.abc.example.com", Kind: "instance", App: "shop", Account: "abc", Platform: true, Socket: flat, Status: "ready"},
+ } {
+ if err := reg.Upsert(rt); err != nil {
+ t.Fatal(err)
+ }
+ }
+ listenAt(t, nested)
+ if n := repairPlatformAliases(reg, liveSocket); n != 1 {
+ t.Fatalf("repaired %d, want 1", n)
+ }
+ if got := socketAt(t, reg, "shop.abc.example.com"); got != nested {
+ t.Errorf("alias = %q, want %q", got, nested)
+ }
+}
diff --git a/internal/host/layoutleg.go b/internal/host/layoutleg.go
index 5974e697f..71c8f9998 100644
--- a/internal/host/layoutleg.go
+++ b/internal/host/layoutleg.go
@@ -211,6 +211,8 @@ func layoutStatusReport(routes []registry.Route) *status.LayoutReport {
// read against the activator's state, no root call.
rows[rt.Host] = status.RowLayout{Layout: string(word), Reason: reason, Note: pass.Note(rt.Host),
Size: rowSizeCell(sizes, rt.Host, word)}
+ case rt.Platform && rt.Socket != "" && !rt.Hibernate:
+ rows[rt.Host] = aliasLayout(rt, liveSocket)
case rt.Socket != "" && !rt.Hibernate:
// ActivatorManaged's own doc: an unflagged socket route is run
// by another supervisor, nobody's to migrate or isolate.
@@ -220,6 +222,26 @@ func layoutStatusReport(routes []registry.Route) *status.LayoutReport {
return &status.LayoutReport{Mode: mode, Rows: rows, Default: def.Applied, DefaultBlocked: def.Blocked}
}
+// Copy for a platform alias's row in `carlos status --layout` (#338,
+// approved by delegation, Luna pass 2026-10-26).
+const (
+ layoutAlias = "alias"
+ layoutAliasNoSocketFmt = "its socket %s does not exist. requests to this address fail"
+)
+
+// aliasLayout is a platform alias's row (the domains pass's apex mint): not
+// an instance of its own but another route's socket under a second name, so
+// it is neither external nor a process to isolate, and the console's mixed
+// warning does not count it. An alias whose socket does not exist answers
+// 502, and says so (#338).
+func aliasLayout(rt registry.Route, live func(string) bool) status.RowLayout {
+ row := status.RowLayout{Layout: layoutAlias}
+ if !live(rt.Socket) {
+ row.Reason = fmt.Sprintf(layoutAliasNoSocketFmt, rt.Socket)
+ }
+ return row
+}
+
// LayoutModeUnmanaged is the report Mode of a box with no activator armed:
// no pass runs there and no hibernate-flagged row ever wakes, so its rows
// are judged by path shape alone (see layoutStatusReport).
@@ -245,6 +267,10 @@ func unmanagedLayoutReport(routes []registry.Route) *status.LayoutReport {
rows[rt.Host] = status.RowLayout{Layout: string(activator.LayoutFenced), Reason: "layout migration in flight; see " + provision.LayoutJournalPath(dd, rt.Host) + " (no activator on this box to recover it)"}
case layout.HoldMarkerPresent(dd, rt.Host):
rows[rt.Host] = status.RowLayout{Layout: string(activator.LayoutFenced), Reason: "held down after a refused move to nested (no activator on this box to retry it)"}
+ case rt.Platform && rt.Socket != "" && !rt.Hibernate:
+ // Before the path shape: a repaired alias names a nested
+ // socket, and is still no instance of its own.
+ rows[rt.Host] = aliasLayout(rt, liveSocket)
case provision.NestedPaths(dd, rt):
rows[rt.Host] = status.RowLayout{Layout: string(activator.LayoutNested), Reason: "no activator on this box; judged by path shape"}
case rt.Socket != "" && !rt.Hibernate:
diff --git a/internal/layout/aliassocket_linux_test.go b/internal/layout/aliassocket_linux_test.go
new file mode 100644
index 000000000..a06263305
--- /dev/null
+++ b/internal/layout/aliassocket_linux_test.go
@@ -0,0 +1,87 @@
+//go:build linux
+
+package layout
+
+import (
+ "context"
+ "testing"
+
+ "github.com/carlosframework/platform/internal/registry"
+)
+
+// #338, production-wired: the layout pass nests a host whose platform alias
+// (the domains pass's apex mint, which copies the host's socket) names the
+// host's flat socket. After the move the alias names the nested socket,
+// after the revert the flat one again, and after a crash and recovery the
+// nested one. Another account's alias on the same path never moves.
+func TestConvergeCarriesThePlatformAliasWithTheHost(t *testing.T) {
+ const apex, foreign = "shop.abc.example.com", "shop.xyz.example.com"
+ setup := func(t *testing.T) (*Pass, string) {
+ t.Helper()
+ p, _ := box(t)
+ rt, err := p.Registry.Get(host)
+ if err != nil || rt == nil {
+ t.Fatal(rt, err)
+ }
+ owned := *rt
+ owned.App, owned.Account = "shop", "abc"
+ flat := owned.Socket
+ for _, row := range []registry.Route{
+ owned,
+ {Host: apex, Kind: "instance", App: "shop", Account: "abc", Platform: true, Socket: flat, Status: "ready"},
+ {Host: foreign, Kind: "instance", App: "shop", Account: "xyz", Platform: true, Socket: flat, Status: "ready"},
+ } {
+ if err := p.Registry.Upsert(row); err != nil {
+ t.Fatal(err)
+ }
+ }
+ return p, flat
+ }
+ aliasAt := func(t *testing.T, p *Pass, h string) string {
+ t.Helper()
+ rt, err := p.Registry.Get(h)
+ if err != nil || rt == nil {
+ t.Fatal(rt, err)
+ }
+ return rt.Socket
+ }
+
+ t.Run("converge and revert", func(t *testing.T) {
+ p, flat := setup(t)
+ if r := byHost(t, p.Converge(context.Background(), ModeNested))[host]; r.Outcome != "migrated" {
+ t.Fatalf("converge: %+v", r)
+ }
+ nested := endpoints(t, p, host, ModeNested).Socket
+ if got := aliasAt(t, p, apex); got != nested {
+ t.Errorf("alias after nesting = %q, want %q", got, nested)
+ }
+ if got := aliasAt(t, p, foreign); got != flat {
+ t.Errorf("another account's alias moved to %q", got)
+ }
+ if r := byHost(t, p.Converge(context.Background(), ModeFlat))[host]; r.Outcome != "reverted" {
+ t.Fatalf("revert: %+v", r)
+ }
+ if got := aliasAt(t, p, apex); got != flat {
+ t.Errorf("alias after the revert = %q, want %q", got, flat)
+ }
+ })
+
+ t.Run("recovery", func(t *testing.T) {
+ p, flat := setup(t)
+ p.abortAt = "after-files"
+ p.Converge(context.Background(), ModeNested)
+ p.abortAt = ""
+ if got := aliasAt(t, p, apex); got != flat {
+ t.Fatalf("alias moved before the row: %q", got)
+ }
+ if r := byHost(t, p.Recover(context.Background(), ""))[host]; r.Outcome != "recovered" {
+ t.Fatalf("recover: %+v", r)
+ }
+ if got, want := aliasAt(t, p, apex), endpoints(t, p, host, ModeNested).Socket; got != want {
+ t.Errorf("alias after recovery = %q, want %q", got, want)
+ }
+ if got := aliasAt(t, p, foreign); got != flat {
+ t.Errorf("another account's alias moved to %q", got)
+ }
+ })
+}
diff --git a/internal/provision/layoutsibling_test.go b/internal/provision/layoutsibling_test.go
new file mode 100644
index 000000000..9bbdc4121
--- /dev/null
+++ b/internal/provision/layoutsibling_test.go
@@ -0,0 +1,24 @@
+package provision
+
+import (
+ "strings"
+ "testing"
+
+ "github.com/carlosframework/platform/internal/registry"
+)
+
+// registry.LayoutSibling carries a copy of InstanceID, because registry
+// cannot import this package. This pins the copy to the original: for a
+// short host and a host long enough to be hashed, the flat and nested
+// sockets are each other's sibling (#338).
+func TestLayoutSiblingIsProvisionsLayout(t *testing.T) {
+ for _, host := range []string{"shop.abc.example.com", strings.Repeat("a", MaxInstanceID+1) + ".example.com", strings.Repeat("b", MaxInstanceID), "app"} {
+ flat, nested := DefaultSocket(host), NestedSocket(host)
+ if got := registry.LayoutSibling(host, flat); got != nested {
+ t.Errorf("%s: sibling of flat = %q, want %q", host, got, nested)
+ }
+ if got := registry.LayoutSibling(host, nested); got != flat {
+ t.Errorf("%s: sibling of nested = %q, want %q", host, got, flat)
+ }
+ }
+}
diff --git a/internal/provision/plan9_b8_census_test.go b/internal/provision/plan9_b8_census_test.go
index 624e61fc6..1efefd276 100644
--- a/internal/provision/plan9_b8_census_test.go
+++ b/internal/provision/plan9_b8_census_test.go
@@ -652,6 +652,8 @@ var plan9B8CensusInventory = []censusEntry{
{"move.go", "moveMain", "key-site", "lit:instances", "3720fd1090c2f0d81d76157eacbd1a1e338a3bae6508167590339d2f60f2399e"},
{"schedule.go", "renderScheduleList", "key-site", "lit:instances", "af6d666083fbbc753eecc98809d3d307344cc15110362a7e93afab573749ea6e"},
{"internal/activator/layout.go", "LayoutInputs.sockets", "key-site", "lit:instances", "1d11ac5ac5be6a42e676e064771141fe8f4367c78cbb7e5c5cca072f40c27c42"},
+ // #338: the flat/nested socket sibling of a host, a socket path under /run/carlos/instances/<id>/, never a record key; it writes nothing.
+ {"internal/registry/aliassocket.go", "LayoutSibling", "key-site", "lit:instances", "675ab91403b73f0ce0a492d1ae09067d62e41ab202c20714b236501860d8435c"},
{"internal/activator/paths.go", "ExecBackend.pathsFor", "key-site", "lit:instances", "cbc01865e27934cb38baab9329a0867b899149531b4706a533a6956afc7c71b3"},
// Re-digested for fix-empty-app-key (census-ruling-fix-empty-app-key, platform-1e 2026-10-16): DayKey now returns an error for an empty or invalid account, app, box or date, and UpsertDay returns it before any Get or Put. Same single Put of the app-day file; no record key.
{"internal/analytics/day.go", "UpsertDay", "nonrecord", "sel:Put", "ab892656cdbce1c80f0c33441341cf9c94dd22f06716ffffbd6c025100adb1b8"},
diff --git a/internal/provision/testdata/plan14-root-reads-alias-socket-follow-338.tsv b/internal/provision/testdata/plan14-root-reads-alias-socket-follow-338.tsv
new file mode 100644
index 000000000..e94321d4b
--- /dev/null
+++ b/internal/provision/testdata/plan14-root-reads-alias-socket-follow-338.tsv
@@ -0,0 +1,28 @@
+# Census overlay alias-socket-follow-338, written by census-propose (#369). census-ruling-alias-socket-follow-338, approved on #280 before the merge; the approval card is docs/superpowers/notes/census-proposal-alias-socket-follow-338.md.
+# 0 body, 0 sites, 2 envelope: each changed unit re-frozen at its existing disposition with its claim appended.
+# 13 new dispositions: 4 reads re-frozen at their disposition with the claim, 9 new units frozen accepted-legacy, 0 quiet units retired while they read nothing, 0 other.
+@legacy e0d4ab950da1e773083f53902a8dbb7bbbf225cd09c08d5a73b3e1b35a393bfd internal/host/aliassocket.go liveSocket legacy accepted-legacy accepted-legacy;rev3=census-ruling-alias-socket-follow-338;basis=#338 repair: Lstat of a platform alias's or its source's socket path from the agent's own registry, to tell whether it exists as a socket; opens nothing file:Lstat@48 c162992c2382c8d739d1c242ca4befc62cb7172e4db1c9b83ae066c9e8651e52
+@legacy a23083c0f1fc91fd89d8370eb92c13d608e6e6be89208d57fe727c0a1f626952 internal/host/aliassocket.go repairPlatformAliases legacy accepted-legacy accepted-legacy;rev3=census-ruling-alias-socket-follow-338;basis=#338 repair, agent only (domainsLoop, every tick): lists the agent's registry, picks a platform alias whose socket is not live and the one same-tenant route whose other-layout socket it names, and asks RepointPlatformSocket; logs registry:Account@482,registry:Account@522,registry:App@401,registry:App@434,registry:App@443,registry:Host@1089,registry:Host@1151,registry:Host@1259,registry:Host@1347,registry:Host@1355,registry:Host@1460,registry:Host@1468,registry:Host@1559,registry:Host@1663,registry:Host@1700,registry:Host@582,registry:Host@954,registry:Platform@239,registry:Platform@370,registry:Socket@1113,registry:Socket@1159,registry:Socket@1267,registry:Socket@1671,registry:Socket@1681,registry:Socket@253,registry:Socket@276,registry:Socket@416,registry:Socket@590,registry:Socket@603,registry:Socket@909,whole:Route@1355,whole:Route@1468,whole:Route@1681,whole:Route@1700,whole:Route@224,whole:Route@355,whole:Route@618,whole:Route@635,whole:Route@644,whole:Route@690,whole:Route@810,whole:Route@909,whole:Route@954 1b916f3ac3dcd168b3cf65664ec7b9df7f7a4c545d9683670a1c3e5c74277ef0
+@legacy 32c76485289693182f7178f8059cc709f96745f053aa78de066838d4b8b63fad internal/host/layoutleg.go aliasLayout legacy accepted-legacy accepted-legacy;rev3=census-ruling-alias-socket-follow-338;basis=#338 status: a platform row's layout row is alias, with a reason naming its socket when Lstat says it is not a live socket registry:Socket@135,registry:Socket@199 0e12be801d8efd30ecc1356ccdab9a6a1a53872fbd7eaaec0e2ea153ef31b631
+@legacy 08722c2f082671ebb82221a99861a7cad32237e6167cac7b49f5038bdd91d7c1 internal/registry/aliassocket.go Registry.RepointPlatformSocket legacy accepted-legacy accepted-legacy;rev3=census-ruling-alias-socket-follow-338;basis=#338 repair door: one IMMEDIATE transaction re-reads both rows and moves only a platform row of the same effective account and app onto the source's socket, when it names the source's other-layout socket (CAS on host, platform, socket); refuses on a remote handle file:Exec@871,registry:Host@820,registry:Host@968,registry:Platform@415,registry:Socket@770,registry:Socket@782,registry:Socket@794,registry:Socket@828,registry:Socket@958,registry:Socket@976,whole:Route@302,whole:Route@314,whole:Route@525,whole:Route@663,whole:Route@667 6b3ca92a1bc9ebf468d17a9b29c286a4532f2d6294cd2c5aa8a994c6d79c18f0
+@legacy 98cdb61770e84795f33bbbaea2b9a3981cd820cad760951e306190ac247a498a internal/registry/aliassocket.go Registry.inImmediateTx legacy accepted-legacy accepted-legacy;rev3=census-ruling-alias-socket-follow-338;basis=#338: inTx without synchronous=FULL, BEGIN IMMEDIATE on the registry's own connection; refuses on a remote handle registry:remote@69,whole:claimTransaction@248,whole:remoteClient@71 7c57458ec963081c2e876e1e3accba55703314742afa866bcb753190cd655fe9
+@legacy 17bf54c2345b3f1b7218abb9090da7305c702b31d071a10464640f2071b6f26a internal/registry/aliassocket.go carriesAliases legacy accepted-legacy accepted-legacy;rev3=census-ruling-alias-socket-follow-338;basis=#338: predicate on a route's own columns (non-platform, non-sidecar, named app, socket) registry:App@83,registry:Platform@47,registry:Socket@100 be0aa9b2ec02593a3f8e8a0bf353a89435112abdf38bcffa094e6712b0e36754
+@legacy 64289018aad397f1493922974a586ee78972d281548bd55f0549f420533f7799 internal/registry/aliassocket.go carryAliasesTx legacy accepted-legacy accepted-legacy;rev3=census-ruling-alias-socket-follow-338;basis=#338: inside the caller's transaction, UPDATE socket of platform rows of the same effective account and app that named an old socket of the source; no other column, no other tenant file:Exec@242,registry:Account@133,registry:App@411,registry:Host@401,registry:Host@610,registry:Socket@199,registry:Socket@389,registry:Socket@625,whole:Route@84 2e24e0057fc7e761ba196acb3a0d3f5670fba77d8a66e40e71ee33d5b7824995
+@legacy d5afe09b8878a8b3fce5abc39c46602fb805210fc99aad3401b7ee4ef88bb137 internal/registry/aliassocket.go sameTenant legacy accepted-legacy accepted-legacy;rev3=census-ruling-alias-socket-follow-338;basis=#338: effective account and app equality, Upsert's tenant rule registry:Account@109,registry:Account@78,registry:App@43,registry:App@52 d72b55615e26f246854ce8f06d28422992e3a7fc880aa4680d588e306a6f962e
+@legacy 55f4304302acc40ed74f537dcf7bf187c08e73e9215fac1a54ead4b23fdf72bf internal/registry/registry.go upsertRoute legacy accepted-legacy accepted-legacy;rev3=census-ruling-alias-socket-follow-338;basis=#338: Upsert's unchanged statement moved into a helper so it can run on the database or inside a transaction file:Exec@56,whole:Route@3883 f843a4ae10a8b94d4578ffef72281d423439f35d394250b8b8f7d415f2ef0a7b
+@legacy ffb35068e747ef43496fd5677a162a612f3648f481cf4b200fd0f02bb7ef7bdc internal/registry/registry.go Registry.SetInstancePaths legacy accepted-legacy accepted-legacy;rev3=J1,J4;basis=route-and-input;rev3=census-ruling-alias-socket-follow-338;basis=#338: the same CAS UPDATE now runs in one IMMEDIATE transaction that also carries the row's same-tenant platform aliases from fromSock to toSock; a missed CAS carries nothing file:Exec@343,file:QueryRow@637,registry:remote@123,registry:remote@93,whole:Route@1012,whole:Route@1071,whole:remoteClient@125,whole:remoteClient@95 d0a1a2f13254d529054d664eb7107a3afaf570bf46b737a47cf595a1ce0ebe09
+internal/host/aliassocket.go liveSocket legacy accepted-legacy accepted-legacy;rev3=census-ruling-alias-socket-follow-338;basis=#338 repair: Lstat of a platform alias's or its source's socket path from the agent's own registry, to tell whether it exists as a socket; opens nothing file:Lstat@48 c162992c2382c8d739d1c242ca4befc62cb7172e4db1c9b83ae066c9e8651e52
+internal/host/aliassocket.go repairPlatformAliases legacy accepted-legacy accepted-legacy;rev3=census-ruling-alias-socket-follow-338;basis=#338 repair, agent only (domainsLoop, every tick): lists the agent's registry, picks a platform alias whose socket is not live and the one same-tenant route whose other-layout socket it names, and asks RepointPlatformSocket; logs registry:Account@482,registry:Account@522,registry:App@401,registry:App@434,registry:App@443,registry:Host@1089,registry:Host@1151,registry:Host@1259,registry:Host@1347,registry:Host@1355,registry:Host@1460,registry:Host@1468,registry:Host@1559,registry:Host@1663,registry:Host@1700,registry:Host@582,registry:Host@954,registry:Platform@239,registry:Platform@370,registry:Socket@1113,registry:Socket@1159,registry:Socket@1267,registry:Socket@1671,registry:Socket@1681,registry:Socket@253,registry:Socket@276,registry:Socket@416,registry:Socket@590,registry:Socket@603,registry:Socket@909,whole:Route@1355,whole:Route@1468,whole:Route@1681,whole:Route@1700,whole:Route@224,whole:Route@355,whole:Route@618,whole:Route@635,whole:Route@644,whole:Route@690,whole:Route@810,whole:Route@909,whole:Route@954 1b916f3ac3dcd168b3cf65664ec7b9df7f7a4c545d9683670a1c3e5c74277ef0
+internal/host/layoutleg.go aliasLayout legacy accepted-legacy accepted-legacy;rev3=census-ruling-alias-socket-follow-338;basis=#338 status: a platform row's layout row is alias, with a reason naming its socket when Lstat says it is not a live socket registry:Socket@135,registry:Socket@199 0e12be801d8efd30ecc1356ccdab9a6a1a53872fbd7eaaec0e2ea153ef31b631
+internal/registry/aliassocket.go Registry.RepointPlatformSocket legacy accepted-legacy accepted-legacy;rev3=census-ruling-alias-socket-follow-338;basis=#338 repair door: one IMMEDIATE transaction re-reads both rows and moves only a platform row of the same effective account and app onto the source's socket, when it names the source's other-layout socket (CAS on host, platform, socket); refuses on a remote handle file:Exec@871,registry:Host@820,registry:Host@968,registry:Platform@415,registry:Socket@770,registry:Socket@782,registry:Socket@794,registry:Socket@828,registry:Socket@958,registry:Socket@976,whole:Route@302,whole:Route@314,whole:Route@525,whole:Route@663,whole:Route@667 6b3ca92a1bc9ebf468d17a9b29c286a4532f2d6294cd2c5aa8a994c6d79c18f0
+internal/registry/aliassocket.go Registry.inImmediateTx legacy accepted-legacy accepted-legacy;rev3=census-ruling-alias-socket-follow-338;basis=#338: inTx without synchronous=FULL, BEGIN IMMEDIATE on the registry's own connection; refuses on a remote handle registry:remote@69,whole:claimTransaction@248,whole:remoteClient@71 7c57458ec963081c2e876e1e3accba55703314742afa866bcb753190cd655fe9
+internal/registry/aliassocket.go carriesAliases legacy accepted-legacy accepted-legacy;rev3=census-ruling-alias-socket-follow-338;basis=#338: predicate on a route's own columns (non-platform, non-sidecar, named app, socket) registry:App@83,registry:Platform@47,registry:Socket@100 be0aa9b2ec02593a3f8e8a0bf353a89435112abdf38bcffa094e6712b0e36754
+internal/registry/aliassocket.go carryAliasesTx legacy accepted-legacy accepted-legacy;rev3=census-ruling-alias-socket-follow-338;basis=#338: inside the caller's transaction, UPDATE socket of platform rows of the same effective account and app that named an old socket of the source; no other column, no other tenant file:Exec@242,registry:Account@133,registry:App@411,registry:Host@401,registry:Host@610,registry:Socket@199,registry:Socket@389,registry:Socket@625,whole:Route@84 2e24e0057fc7e761ba196acb3a0d3f5670fba77d8a66e40e71ee33d5b7824995
+internal/registry/aliassocket.go sameTenant legacy accepted-legacy accepted-legacy;rev3=census-ruling-alias-socket-follow-338;basis=#338: effective account and app equality, Upsert's tenant rule registry:Account@109,registry:Account@78,registry:App@43,registry:App@52 d72b55615e26f246854ce8f06d28422992e3a7fc880aa4680d588e306a6f962e
+internal/registry/registry.go upsertRoute legacy accepted-legacy accepted-legacy;rev3=census-ruling-alias-socket-follow-338;basis=#338: Upsert's unchanged statement moved into a helper so it can run on the database or inside a transaction file:Exec@56,whole:Route@3883 f843a4ae10a8b94d4578ffef72281d423439f35d394250b8b8f7d415f2ef0a7b
+internal/host/layoutleg.go layoutStatusReport diagnostic H3 no-effect;rev3=census-ruling-instance-egress-sizes-328-329;basis=#329 plan 3 Task 7: each activator-managed instance row gains a Size cell, rowSizeCell(armedSizeSource.Load(), rt.Host, word) (the added registry:Host site), which for an awake nested row reads that host's cgroup memory.max through readSizeInForce (a decision row, in the agent); still a status report with no effect on any decision.;rev3=census-ruling-alias-socket-follow-338;basis=#338: a platform socket row reports alias (aliasLayout) instead of external; reads Platform registry:Hibernate@1355,registry:Hibernate@1443,registry:Host@1176,registry:Host@1258,registry:Host@1297,registry:Host@1377,registry:Host@1593,registry:Host@901,registry:Kind@554,registry:Platform@1320,registry:Socket@1335,registry:Socket@1423,whole:Route@1400,whole:Route@153,whole:Route@348,whole:Route@639,whole:Route@677,whole:Route@681 ef81aabf610166689a4009f1b590e127442c380ebef71febd2752b3c808314c4
+internal/host/layoutleg.go unmanagedLayoutReport diagnostic H3 no-effect;rev3=census-ruling-alias-socket-follow-338;basis=#338: the same, before the nested-by-path-shape case so a repaired alias is not called nested registry:Hibernate@1124,registry:Hibernate@1201,registry:Hibernate@752,registry:Host@1146,registry:Host@1242,registry:Host@278,registry:Host@296,registry:Host@441,registry:Host@533,registry:Host@551,registry:Host@886,registry:Host@971,registry:Kind@194,registry:Platform@717,registry:Socket@1104,registry:Socket@1217,registry:Socket@732,whole:Route@180,whole:Route@909,whole:Route@958 2277d2bba5aeabb2caa1e7a31a403dba66d464c3285f2c0964f28871e3698703
+internal/registry/registry.go Registry.SetInstancePaths legacy accepted-legacy accepted-legacy;rev3=J1,J4;basis=route-and-input;rev3=census-ruling-alias-socket-follow-338;basis=#338: the same CAS UPDATE now runs in one IMMEDIATE transaction that also carries the row's same-tenant platform aliases from fromSock to toSock; a missed CAS carries nothing file:Exec@343,file:QueryRow@637,registry:remote@123,registry:remote@93,whole:Route@1012,whole:Route@1071,whole:remoteClient@125,whole:remoteClient@95 d0a1a2f13254d529054d664eb7107a3afaf570bf46b737a47cf595a1ce0ebe09
+internal/registry/registry.go Registry.Upsert authority E3 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); the remote arm, unchanged, in the process that holds a remote handle, root passes included: census-ruling-seeded-instances's body with two more columns (incarnation, serving_seq) bound through routeArgs; the conflict clause names them only to keep an existing row's pair (a fresh insert writes the mint's), and the tenant-change rule E3 names is unchanged; main's E3 authority retained; self-serve moves 1 Task 7;rev3=census-ruling-rootfs-apps-2;basis=main's body (with main's rate_limit rule and, from the merge of origin/main 3c33f2eb, the assets_off and asset_gen pair rule of edge asset cache plan 1, and, from the merge of 953b9fda, the incarnation and serving_seq pair of self-serve moves plan 1) plus the runtime column's conflict rule: a re-tenanted host takes the incoming runtime, the same tenant keeps the stored one (fixed at mint); the bind is routeArgs, re-frozen in rootfs-apps-2-new; the same nine sites, no read added;rev3=census-ruling-instance-egress-sizes-328-329;basis=#328/#329 plan 1 Task 4: the conflict clause gains egress_allow, size and policy_expires_at under the tenant-change rule (a re-tenanted host takes the incoming values, empty included; the same tenant keeps the stored value when the incoming one is empty, else takes it), bound through routeArgs; the same nine sites, no read added.;rev3=census-ruling-region-ha-p1a;basis=the conflict clause gains ha=MAX(routes.ha, excluded.ha), so no full-row write ever clears a stored born-HA mark and a fresh row takes the incoming value; the bind is routeArgs; the same nine sites, no read added;rev3=census-ruling-alias-socket-follow-338;basis=#338: a non-platform row with a socket and app is upserted in one IMMEDIATE transaction that then carries same-tenant platform aliases naming its other-layout socket (LayoutSibling) or its previous socket (same tenant only); the upsert statement and its claim-ownership refusal are unchanged; platform and other rows take the old single-statement path registry:Host@564,registry:Host@700,registry:Host@791,registry:Platform@836,registry:Socket@801,registry:Socket@904,registry:remote@47,registry:remote@77,registry:sql@207,whole:Route@128,whole:Route@136,whole:Route@181,whole:Route@214,whole:Route@636,whole:Route@727,whole:Route@819,whole:Route@866,whole:Route@874,whole:Route@951,whole:remoteClient@49,whole:remoteClient@79 33844302d6d4886e5f553f562f0834dd551c4e1697db22fb00dcd2f29c6aacd8
+@coverage internal/host e83cad942dd3c2a13525e73253ada346f14a62881de66142048a924b39f7327d
+@coverage internal/registry 35523d2fb75a87ca5614a1a2d74a6a1ddee55b1fed93a2fa2de2c18bb52cd1b1
diff --git a/internal/provision/testdata/plan14-root-reads-chain.tsv b/internal/provision/testdata/plan14-root-reads-chain.tsv
index df7c42564..6d87270ab 100644
--- a/internal/provision/testdata/plan14-root-reads-chain.tsv
+++ b/internal/provision/testdata/plan14-root-reads-chain.tsv
@@ -7,3 +7,4 @@ plan14-root-reads-edge-asset-cache-3.tsv f723ddc14e3c03c0d55b6f0c949567a2c9325e0
plan14-root-reads-remote-metrics-nested.tsv e923841657499fc729713abdd750cbd2d6019fc4db677b540be0fab4d2a160e4
plan14-root-reads-region-ha-p1a.tsv 125c5c411cd0a04000d9652800b51bc7c066081c00753fb1c7b6ee0b6e717dbd
plan14-root-reads-nearest-region-b.tsv f4e36134015ec6d09bada7be500c8faad22450afda12d033a8e3e24b1e8bb361
+plan14-root-reads-alias-socket-follow-338.tsv 5192052a23d2fdd6f5d48b5617fe28a9bb03458e1e931c060fbdc42c3d627927
diff --git a/internal/registry/aliassocket.go b/internal/registry/aliassocket.go
new file mode 100644
index 000000000..3c0fb0e6a
--- /dev/null
+++ b/internal/registry/aliassocket.go
@@ -0,0 +1,161 @@
+package registry
+
+import (
+ "context"
+ "crypto/sha256"
+ "encoding/hex"
+ "fmt"
+ "log"
+ "path/filepath"
+)
+
+// Platform aliases and the socket they copy (#338, #392).
+//
+// A platform row (Platform, the domains pass's <app>.<sqid>.<apps-domain>
+// apex) has no process of its own: mintedRoute copies its source route's
+// socket once, at mint time, and the edge dials that path. When the source
+// instance's socket moves (the layout pass nests or un-nests it, a move
+// lands it nested, `carlos add` re-adds it) an alias still naming the old
+// path answers 502. So every registry door that moves a source's socket
+// carries the same tenant's aliases with it, in the same transaction, and
+// the agent's repair (internal/host, aliassocket.go) fixes aliases left
+// stale before this existed.
+//
+// The one invariant every path here keeps: an alias is only ever pointed at
+// a socket of a row of its own tenant, the same effective account and the
+// same app. Another tenant's alias that names the same path stays put.
+
+// layoutMaxInstanceID and layoutInstanceID are provision.MaxInstanceID and
+// provision.InstanceID, which this package cannot import (provision imports
+// it). TestLayoutSiblingIsProvisionsLayout in internal/provision pins the
+// two together.
+const layoutMaxInstanceID = 40
+
+func layoutInstanceID(host string) string {
+ if len(host) <= layoutMaxInstanceID {
+ return host
+ }
+ sum := sha256.Sum256([]byte(host))
+ return "_" + host[:22] + "-" + hex.EncodeToString(sum[:8])
+}
+
+// LayoutSibling is host's socket in the other layout, given a socket of
+// host's in one of them: the nested <dir>/instances/<id>/app.sock for the
+// flat <dir>/<host>.sock, and the reverse. Any other path (a foreign
+// socket, another host's, a relative or unclean one) has no sibling: "".
+// It derives from the path alone, so it holds for any socket directory.
+func LayoutSibling(host, socket string) string {
+ if host == "" || socket == "" || !filepath.IsAbs(socket) || filepath.Clean(socket) != socket {
+ return ""
+ }
+ dir, base := filepath.Dir(socket), filepath.Base(socket)
+ id := layoutInstanceID(host)
+ // The nested shape first: for the host "app" its nested socket's base
+ // name is also host+".sock" (Astra r1 P2).
+ switch {
+ case base == "app.sock" && filepath.Base(dir) == id && filepath.Base(filepath.Dir(dir)) == "instances":
+ return filepath.Join(filepath.Dir(filepath.Dir(dir)), host+".sock")
+ case base == host+".sock":
+ return filepath.Join(dir, "instances", id, "app.sock")
+ }
+ return ""
+}
+
+// carriesAliases says whether src is a row whose aliases follow its socket:
+// a non-platform, non-sidecar route of a named app with a socket.
+func carriesAliases(src Route) bool {
+ return !src.Platform && !src.IsSidecar() && src.App != "" && src.Socket != ""
+}
+
+// sameTenant compares two rows' tenants as Upsert does: effective account
+// and app.
+func sameTenant(a, b Route) bool {
+ return a.App == b.App && EffectiveAccount(a.Account) == EffectiveAccount(b.Account)
+}
+
+// carryAliasesTx points every platform row of src's tenant that names one
+// of olds at src's socket. It runs inside the transaction that moved src.
+func carryAliasesTx(tx txer, src Route, olds ...string) error {
+ if !carriesAliases(src) {
+ return nil
+ }
+ acct := EffectiveAccount(src.Account)
+ for _, old := range olds {
+ if old == "" || old == src.Socket {
+ continue
+ }
+ res, err := tx.Exec(`UPDATE routes SET socket = ? WHERE platform = 1 AND host != ? AND app = ? AND `+
+ effectiveAccountSQL("account")+` = ? AND socket = ?`, src.Socket, src.Host, src.App, acct, old)
+ if err != nil {
+ return err
+ }
+ if n, err := res.RowsAffected(); err == nil && n > 0 {
+ log.Printf("registry: %d platform alias(es) of %s moved from %s to %s with it", n, src.Host, old, src.Socket)
+ }
+ }
+ return nil
+}
+
+// inImmediateTx runs fn in one BEGIN IMMEDIATE transaction at the
+// connection's usual synchronous level: inTx's form without FULL, for
+// writes that were a single statement before they carried aliases.
+func (r *Registry) inImmediateTx(fn func(tx txer) error) error {
+ if r.remote != nil {
+ return errRemoteMethod
+ }
+ tx, err := r.beginClaimTransaction(context.Background(), false)
+ if err != nil {
+ return err
+ }
+ defer tx.Rollback()
+ if err := fn(tx); err != nil {
+ return err
+ }
+ return tx.Commit()
+}
+
+// RepointPlatformSocket is the repair's door: it moves the platform row
+// alias onto source's socket, in one transaction, only when
+// - alias is a platform row and source is not (and is no sidecar),
+// - both rows are one tenant's: the same effective account and app,
+// - alias names source's socket in the other layout (LayoutSibling), the
+// shape a nesting or un-nesting before #338 left behind.
+//
+// It reports whether it changed the row. An alias that already names
+// source's socket, or anything else, is no change. A refusal is an error.
+// Whether either socket exists is the caller's question: the registry does
+// not look at the filesystem. The agent's own handle only, like the import
+// journal's doors: root never repairs.
+func (r *Registry) RepointPlatformSocket(alias, source string) (bool, error) {
+ changed := false
+ err := r.inImmediateTx(func(tx txer) error {
+ a, err := getRouteTx(tx, alias)
+ if err != nil {
+ return err
+ }
+ s, err := getRouteTx(tx, source)
+ if err != nil {
+ return err
+ }
+ switch {
+ case a == nil || s == nil:
+ return fmt.Errorf("registry: repoint %s onto %s: no such route", alias, source)
+ case !a.Platform:
+ return fmt.Errorf("registry: repoint %s: not a platform alias", alias)
+ case !carriesAliases(*s):
+ return fmt.Errorf("registry: repoint %s onto %s: the source is not an app route with a socket", alias, source)
+ case !sameTenant(*a, *s):
+ return fmt.Errorf("registry: repoint %s onto %s: another account or app", alias, source)
+ case a.Socket == s.Socket || a.Socket != LayoutSibling(s.Host, s.Socket):
+ return nil
+ }
+ res, err := tx.Exec(`UPDATE routes SET socket = ? WHERE host = ? AND platform = 1 AND socket = ?`, s.Socket, a.Host, a.Socket)
+ if err != nil {
+ return err
+ }
+ n, err := res.RowsAffected()
+ changed = err == nil && n == 1
+ return err
+ })
+ return changed, err
+}
diff --git a/internal/registry/aliassocket_test.go b/internal/registry/aliassocket_test.go
new file mode 100644
index 000000000..f5cbc84b6
--- /dev/null
+++ b/internal/registry/aliassocket_test.go
@@ -0,0 +1,198 @@
+package registry
+
+import (
+ "errors"
+ "strings"
+ "testing"
+)
+
+// The platform alias (a domains-minted apex, Platform) copies its source
+// instance's socket once, at mint time. These tests pin #338 and #392: every
+// registry door that moves an instance's socket moves the same tenant's
+// aliases that name it, in the same transaction, and never another tenant's.
+
+const (
+ aliasSrc = "shop-a.abc.example.com"
+ aliasApex = "shop.abc.example.com"
+ aliasOther = "shop.xyz.example.com"
+ aliasFlat = "/run/carlos/" + aliasSrc + ".sock"
+ aliasNested = "/run/carlos/instances/" + aliasSrc + "/app.sock"
+ aliasFlatDB = "/data/" + aliasSrc + ".db"
+ aliasNestDB = "/data/instances/" + aliasSrc + "/" + aliasSrc + ".db"
+ aliasAccount = "abc"
+)
+
+func aliasSource(sock, db string) Route {
+ return Route{Host: aliasSrc, Kind: "instance", App: "shop", Account: aliasAccount, Hibernate: true, Socket: sock, DBPath: db}
+}
+
+func aliasMint(host, account, sock string) Route {
+ return Route{Host: host, Kind: "instance", App: "shop", Account: account, Platform: true, Socket: sock}
+}
+
+func mustUpsert(t *testing.T, r *Registry, rts ...Route) {
+ t.Helper()
+ for _, rt := range rts {
+ if err := r.Upsert(rt); err != nil {
+ t.Fatalf("upsert %s: %v", rt.Host, err)
+ }
+ }
+}
+
+func socketOf(t *testing.T, r *Registry, host string) string {
+ t.Helper()
+ return mustRoute(t, r, host).Socket
+}
+
+// Nesting and un-nesting (the layout pass's one door) carry the alias both
+// ways. Another account's alias that happens to name the same path, and a
+// non-platform row on it, stay where they are.
+func TestSetInstancePathsCarriesTheTenantsAliases(t *testing.T) {
+ r := openTestRegistry(t)
+ mustUpsert(t, r,
+ aliasSource(aliasFlat, aliasFlatDB),
+ aliasMint(aliasApex, aliasAccount, aliasFlat),
+ aliasMint(aliasOther, "xyz", aliasFlat),
+ Route{Host: "hand.abc.example.com", Kind: "instance", App: "shop", Account: aliasAccount, Socket: aliasFlat},
+ )
+ if err := r.SetInstancePaths(aliasSrc, aliasFlatDB, aliasFlat, aliasNestDB, aliasNested); err != nil {
+ t.Fatal(err)
+ }
+ if got := socketOf(t, r, aliasApex); got != aliasNested {
+ t.Errorf("alias after nesting = %q, want %q", got, aliasNested)
+ }
+ if got := socketOf(t, r, aliasOther); got != aliasFlat {
+ t.Errorf("another account's alias moved to %q", got)
+ }
+ if got := socketOf(t, r, "hand.abc.example.com"); got != aliasFlat {
+ t.Errorf("a non-platform row moved to %q", got)
+ }
+ if err := r.SetInstancePaths(aliasSrc, aliasNestDB, aliasNested, aliasFlatDB, aliasFlat); err != nil {
+ t.Fatal(err)
+ }
+ if got := socketOf(t, r, aliasApex); got != aliasFlat {
+ t.Errorf("alias after un-nesting = %q, want %q", got, aliasFlat)
+ }
+ // A missed CAS moves nothing, the alias included.
+ if err := r.SetInstancePaths(aliasSrc, aliasNestDB, aliasNested, "/x", "/y"); !errors.Is(err, ErrPathsChanged) {
+ t.Fatalf("stale CAS = %v", err)
+ }
+ if got := socketOf(t, r, aliasApex); got != aliasFlat {
+ t.Errorf("alias moved on a missed CAS: %q", got)
+ }
+}
+
+// A row that lands with a new socket (a move landing, a re-mint, an
+// adoption's insert, `carlos add` over the host) carries the same tenant's
+// aliases that name its other-layout socket or its previous one.
+func TestUpsertCarriesTheTenantsAliases(t *testing.T) {
+ t.Run("insert nested over a flat alias", func(t *testing.T) {
+ r := openTestRegistry(t)
+ mustUpsert(t, r, aliasMint(aliasApex, aliasAccount, aliasFlat), aliasMint(aliasOther, "xyz", aliasFlat))
+ mustUpsert(t, r, aliasSource(aliasNested, aliasNestDB))
+ if got := socketOf(t, r, aliasApex); got != aliasNested {
+ t.Errorf("alias = %q, want %q", got, aliasNested)
+ }
+ if got := socketOf(t, r, aliasOther); got != aliasFlat {
+ t.Errorf("another account's alias moved to %q", got)
+ }
+ })
+ t.Run("rewrite from a foreign socket", func(t *testing.T) {
+ r := openTestRegistry(t)
+ mustUpsert(t, r, aliasSource("/srv/shop.sock", ""), aliasMint(aliasApex, aliasAccount, "/srv/shop.sock"))
+ mustUpsert(t, r, aliasSource(aliasNested, aliasNestDB))
+ if got := socketOf(t, r, aliasApex); got != aliasNested {
+ t.Errorf("alias = %q, want %q", got, aliasNested)
+ }
+ })
+ t.Run("a new tenant on the host takes nobody's alias", func(t *testing.T) {
+ r := openTestRegistry(t)
+ mustUpsert(t, r, aliasSource("/srv/shop.sock", ""), aliasMint(aliasApex, aliasAccount, "/srv/shop.sock"))
+ next := aliasSource(aliasNested, aliasNestDB)
+ next.Account = "xyz"
+ mustUpsert(t, r, next)
+ if got := socketOf(t, r, aliasApex); got != "/srv/shop.sock" {
+ t.Errorf("the previous tenant's alias followed a new tenant to %q", got)
+ }
+ })
+ t.Run("another app of the same account is left alone", func(t *testing.T) {
+ r := openTestRegistry(t)
+ other := aliasMint(aliasApex, aliasAccount, aliasFlat)
+ other.App = "blog"
+ mustUpsert(t, r, other, aliasSource(aliasNested, aliasNestDB))
+ if got := socketOf(t, r, aliasApex); got != aliasFlat {
+ t.Errorf("another app's alias moved to %q", got)
+ }
+ })
+ t.Run("a platform upsert carries nothing", func(t *testing.T) {
+ r := openTestRegistry(t)
+ mustUpsert(t, r, aliasMint(aliasApex, aliasAccount, aliasFlat))
+ mustUpsert(t, r, aliasMint("shop-2.abc.example.com", aliasAccount, aliasNested))
+ if got := socketOf(t, r, aliasApex); got != aliasFlat {
+ t.Errorf("a platform row moved another platform row to %q", got)
+ }
+ })
+}
+
+func TestLayoutSibling(t *testing.T) {
+ long := strings.Repeat("a", 50) + ".example.com"
+ for _, tc := range []struct{ host, sock, want string }{
+ {aliasSrc, aliasFlat, aliasNested},
+ {aliasSrc, aliasNested, aliasFlat},
+ {aliasSrc, "/srv/shop.sock", ""},
+ {aliasSrc, "/run/carlos/instances/other.example.com/app.sock", ""},
+ {aliasSrc, "/run/carlos/other.example.com.sock", ""},
+ {aliasSrc, "", ""},
+ {"app", "/run/carlos/app.sock", "/run/carlos/instances/app/app.sock"},
+ {"app", "/run/carlos/instances/app/app.sock", "/run/carlos/app.sock"},
+ {"", "/run/carlos/.sock", ""},
+ } {
+ if got := LayoutSibling(tc.host, tc.sock); got != tc.want {
+ t.Errorf("LayoutSibling(%q, %q) = %q, want %q", tc.host, tc.sock, got, tc.want)
+ }
+ }
+ nested := LayoutSibling(long, "/run/carlos/"+long+".sock")
+ if !strings.HasPrefix(nested, "/run/carlos/instances/_") || LayoutSibling(long, nested) != "/run/carlos/"+long+".sock" {
+ t.Errorf("long host round trip: %q", nested)
+ }
+}
+
+// RepointPlatformSocket is the repair's door: it moves an alias onto its
+// source's socket only when the alias names the source's other-layout
+// socket and both rows are one tenant's. Everything else is refused.
+func TestRepointPlatformSocketRefusesAcrossTenants(t *testing.T) {
+ r := openTestRegistry(t)
+ mustUpsert(t, r, aliasMint(aliasApex, aliasAccount, aliasFlat), aliasMint(aliasOther, "xyz", aliasFlat))
+ // Inserted with the source already nested: the Upsert carry would move
+ // the same tenant's alias at once, so put it back to the stale state
+ // the repair meets on a box today.
+ mustUpsert(t, r, aliasSource(aliasNested, aliasNestDB))
+ if _, err := r.sql.Exec(`UPDATE routes SET socket = ? WHERE host = ?`, aliasFlat, aliasApex); err != nil {
+ t.Fatal(err)
+ }
+
+ if changed, err := r.RepointPlatformSocket(aliasOther, aliasSrc); err == nil || changed {
+ t.Errorf("cross-account repoint = %v, %v; want a refusal", changed, err)
+ }
+ if got := socketOf(t, r, aliasOther); got != aliasFlat {
+ t.Errorf("another account's alias moved to %q", got)
+ }
+ changed, err := r.RepointPlatformSocket(aliasApex, aliasSrc)
+ if err != nil || !changed {
+ t.Fatalf("repoint = %v, %v", changed, err)
+ }
+ if got := socketOf(t, r, aliasApex); got != aliasNested {
+ t.Errorf("alias = %q, want %q", got, aliasNested)
+ }
+ // Idempotent: the alias no longer names the source's other socket.
+ if changed, err := r.RepointPlatformSocket(aliasApex, aliasSrc); err != nil || changed {
+ t.Errorf("second repoint = %v, %v; want no change", changed, err)
+ }
+ // Not a platform row, or a source that is itself a platform row: refused.
+ if _, err := r.RepointPlatformSocket(aliasSrc, aliasApex); err == nil {
+ t.Error("repoint of a non-platform row was accepted")
+ }
+ if _, err := r.RepointPlatformSocket("absent.example.com", aliasSrc); err == nil {
+ t.Error("repoint of an absent alias was accepted")
+ }
+}
diff --git a/internal/registry/registry.go b/internal/registry/registry.go
index 3c359dc3b..cf6ee2c8e 100644
--- a/internal/registry/registry.go
+++ b/internal/registry/registry.go
@@ -1302,8 +1302,37 @@ func (r *Registry) Upsert(t Route) error {
_, err := r.remote.call(nil, remoteRequest{Method: "Upsert", TValue: t}, nil)
return err
}
+ if !carriesAliases(t) {
+ return upsertRoute(r.sql, t)
+ }
+ // A row that can carry platform aliases (#338) is written in one
+ // transaction with them: the same tenant's aliases that named its
+ // previous socket, or its socket in the other layout (a move or a
+ // re-mint landing nested over an alias left flat), follow it.
+ return r.inImmediateTx(func(tx txer) error {
+ prior, err := getRouteTx(tx, t.Host)
+ if err != nil {
+ return err
+ }
+ if err := upsertRoute(tx, t); err != nil {
+ return err
+ }
+ cur, err := getRouteTx(tx, t.Host)
+ if err != nil || cur == nil {
+ return err
+ }
+ olds := []string{LayoutSibling(cur.Host, cur.Socket)}
+ if prior != nil && !prior.Platform && sameTenant(*prior, *cur) {
+ olds = append(olds, prior.Socket)
+ }
+ return carryAliasesTx(tx, *cur, olds...)
+ })
+}
- res, err := r.sql.Exec(`
+// upsertRoute is Upsert's statement, on the database or inside a
+// transaction.
+func upsertRoute(db txer, t Route) error {
+ res, err := db.Exec(`
INSERT INTO routes (`+routeCols+`)
VALUES (`+placeholders(routeColCount)+`)
ON CONFLICT(host) DO UPDATE SET
@@ -1957,32 +1986,42 @@ var ErrPathsChanged = errors.New("registry: instance paths changed underneath th
// learns what it holds now. It is SetDBPath's sibling; the two columns are
// swapped together because a row with one flat path and one nested path is
// neither layout, and every consumer would refuse it.
+//
+// The same transaction carries the row's platform aliases (#338): every
+// platform row of the same tenant that named fromSock names toSock after
+// it (carryAliasesTx). A missed compare-and-swap carries nothing.
func (r *Registry) SetInstancePaths(host, fromDB, fromSock, toDB, toSock string) error {
if r.remote != nil {
_, err := r.remote.call(nil, remoteRequest{Method: "SetInstancePaths", Host: host, FromDB: fromDB, FromSock: fromSock, ToDB: toDB, ToSock: toSock}, nil)
return err
}
- res, err := r.sql.Exec(`UPDATE routes SET db_path = ?, socket = ? WHERE host = ? AND db_path = ? AND socket = ?`, toDB, toSock, host, fromDB, fromSock)
- if err != nil {
- return err
- }
- n, err := res.RowsAffected()
- if err != nil {
- return err
- }
- if n == 0 {
- var curDB, curSock string
- serr := r.sql.QueryRow(`SELECT db_path, socket FROM routes WHERE host = ?`, host).Scan(&curDB, &curSock)
- if serr == sql.ErrNoRows {
- return fmt.Errorf("no route for host %q", host)
+ return r.inImmediateTx(func(tx txer) error {
+ res, err := tx.Exec(`UPDATE routes SET db_path = ?, socket = ? WHERE host = ? AND db_path = ? AND socket = ?`, toDB, toSock, host, fromDB, fromSock)
+ if err != nil {
+ return err
}
- if serr != nil {
- return serr
+ n, err := res.RowsAffected()
+ if err != nil {
+ return err
}
- return fmt.Errorf("%w: %s now holds db %q socket %q", ErrPathsChanged, host, curDB, curSock)
- }
- return nil
+ if n == 0 {
+ var curDB, curSock string
+ serr := tx.QueryRow(`SELECT db_path, socket FROM routes WHERE host = ?`, host).Scan(&curDB, &curSock)
+ if serr == sql.ErrNoRows {
+ return fmt.Errorf("no route for host %q", host)
+ }
+ if serr != nil {
+ return serr
+ }
+ return fmt.Errorf("%w: %s now holds db %q socket %q", ErrPathsChanged, host, curDB, curSock)
+ }
+ rt, err := getRouteTx(tx, host)
+ if err != nil || rt == nil {
+ return err
+ }
+ return carryAliasesTx(tx, *rt, fromSock)
+ })
}
// SetBacking stamps who owns a route's process: "" (an exec child of the