carlos / platform Public

Regional domains (#447) Task 9: regional readiness on the placements GET

placementsView answers a regional claim per placement, in claim order:
a box counts when fresh, at the regional floor and publishing an EIP;
no-serving-box, below-floor and no-address per region; then
evidence-incomplete (snapshot not EvidenceComplete, or a fresh heartbeat
without aliases_read), route-collision and settling hold every region at
once, first match wins. The PUT answers the same view. Single mode keeps
Task 1's rule.

A regional claim's DNS advice on the domain list, per-host GET and
settings page points at the placements read (draft RD-44) instead of
the single-edge advice and records.

W8 TestPlacementsGetRegionalReadiness, Review Focus 1
TestPlacementsGetShowsADeletedTarget, TestPlacementsPutAnswersTheRegionalView,
TestRegionalDomainGetsNoSingleEdgeDNSAdvice, and W13
TestFailedAliasReadIsIncompleteEvidence through the real statusTick,
CollectBox, heartbeat store, edges writer and console server.

Mutation checks (each failed its leg, then restored and cmp'd):
M1 barrier ignores aliases_read: W13 step 1 PUT 200, claim written.
M2 GET ignores aliases_read: W13 step 3 ready; W8 aliases_read legs.
M3 no EvidenceComplete; M4 floor ignored when counting; M5 no
created_at settle; M6 no collision; M7 any placement serves;
M8 alias publish not settling.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev 9ef198a0c22207b523d284d5c38d91d8dc975c0e parent bd8b679
6 files changed, +812 −7
  • docs/superpowers/plans/2026-10-28-regional-domains-447-copy.md +1 −0
  • internal/console/apidomains.go +7 −1
  • internal/console/apiplacements.go +134 −6
  • internal/console/apiplacements_test.go +275 −0
  • internal/console/appsettings.go +4 −0
  • internal/host/aliasesread_e2e_test.go +391 −0
diff --git a/docs/superpowers/plans/2026-10-28-regional-domains-447-copy.md b/docs/superpowers/plans/2026-10-28-regional-domains-447-copy.md
index 8e4c149b0..7fbbdb99a 100644
--- a/docs/superpowers/plans/2026-10-28-regional-domains-447-copy.md
+++ b/docs/superpowers/plans/2026-10-28-regional-domains-447-copy.md
@@ -83,6 +83,7 @@ count.
| RD-29 | internal/console/domaincatchall.go | an instance catch-all cannot cover a regional domain. | draft |
| RD-40 | internal/console/apiplacements.go | given a regional domain | draft |
| RD-41 | internal/console/apiplacements.go | <box> does not say which release it runs. try again when every server runs <floor> or later. | draft |
+| RD-44 | internal/console/apiplacements.go | <host> is a regional domain. carlos domains placements shows the addresses to point DNS at in each region. | draft |
## Release floor (operators: internal/release, internal/console, system.go)
diff --git a/internal/console/apidomains.go b/internal/console/apidomains.go
index 58c55dd5f..dde148016 100644
--- a/internal/console/apidomains.go
+++ b/internal/console/apidomains.go
@@ -1374,7 +1374,13 @@ func (s *Server) domainItem(ctx context.Context, c domains.Claim, readings map[s
// record) — pointing them at "create this record" guidance would blame
// them for our outage. Only "" (no answer yet) and "elsewhere" (a real,
// wrong answer) earn guidance.
- if item.DNSStatus != "pointing" && item.DNSStatus != "unresolved" {
+ switch {
+ case c.Regional():
+ // Each region has its own addresses, which the placements read
+ // gives: the single-edge advice and its records would send every
+ // region's visitors to every edge.
+ item.Guidance = regionalDNSGuidance(c.Host)
+ case item.DNSStatus != "pointing" && item.DNSStatus != "unresolved":
item.Guidance = domainGuidance(c.Host, targets)
// The structured form of the SAME advice, emitted under exactly the
// same condition so the two can never disagree about whether there is
diff --git a/internal/console/apiplacements.go b/internal/console/apiplacements.go
index acf973e65..0edf6655a 100644
--- a/internal/console/apiplacements.go
+++ b/internal/console/apiplacements.go
@@ -4,7 +4,8 @@ package console
// which boxes serve its target in each region, the addresses they answer on
// and whether the region is ready for DNS. The PUT (spec §6.2): the only way
// into regional mode, creating a regional claim or replacing the set on the
-// caller's own. The regional rules of the GET's view come later (Task 9).
+// caller's own. Both answer placementsView: one entry for a single-mode
+// claim, one per region for a regional claim (Task 9).
import (
"context"
@@ -129,12 +130,15 @@ func (s *Server) handleAPIDomainPlacementsGet(w http.ResponseWriter, r *http.Req
// placementsView is the GET body from one claim and one joined snapshot. Pure.
//
-// Every claim is single mode until the regional claim lands (Task 2), and
-// Task 9 adds the regional rules. Single mode has one entry, the route's:
-// every fresh box publishing the target under home is listed, whatever its
-// placement, and counts when it publishes an address. The regional floor
-// does not apply to a single-mode claim, which every release serves.
+// Single mode has one entry, the route's: every fresh box publishing the
+// target under home is listed, whatever its placement, and counts when it
+// publishes an address. The regional floor does not apply to a single-mode
+// claim, which every release serves (controller ruling). A regional claim
+// answers regionalPlacementsView.
func (s *Server) placementsView(c domains.Claim, snap edgesfile.Snapshot, boxes []status.Box, now time.Time) placementsAnswer {
+ if c.Regional() {
+ return s.regionalPlacementsView(c, snap, boxes, now)
+ }
target := c.Route
if target == "" {
// A first-route claim: the hostname is its own route.
@@ -167,6 +171,122 @@ func (s *Server) placementsView(c domains.Claim, snap edgesfile.Snapshot, boxes
Wildcard: c.Wildcard, Catchall: c.Catchall, Placements: []placementState{p}}
}
+// regionalPlacementsView is placementsView for a regional claim (spec §8):
+// one entry per placement in claim order. A placement's serving boxes are
+// the fresh boxes whose placement is the region's code and that publish the
+// target under home; one counts when its heartbeat is at the regional floor
+// and it publishes an address, and the region is ready when one counts. No
+// region's boxes stand in for another's. Not ready: no-serving-box (none
+// serves), below-floor (some serve, none at the floor), no-address (some
+// at the floor, none with an address). Then regionalHold, which holds every
+// region at once.
+func (s *Server) regionalPlacementsView(c domains.Claim, snap edgesfile.Snapshot, boxes []status.Box, now time.Time) placementsAnswer {
+ heartbeats := freshHeartbeats(boxes, now)
+ out := placementsAnswer{Host: c.Host, Mode: "regional", Route: c.Route,
+ Wildcard: c.Wildcard, Catchall: c.Catchall, Placements: make([]placementState, 0, len(c.Placements))}
+ for _, pl := range c.Placements {
+ p := placementState{Region: s.homeRegionOut(pl.Region), Target: pl.Host, Boxes: []placementBox{}}
+ serving := servingBoxes(snap, pl.Region, pl.Host)
+ atFloor := false
+ for _, f := range serving {
+ hb, fresh := heartbeats[f.Box]
+ floor := fresh && boxAtRegionalFloor(hb)
+ atFloor = atFloor || floor
+ b := placementBox{Box: f.Box, EIP: f.EIP, AWSRegion: f.Region, Counted: floor && f.EIP != ""}
+ if hb.Metrics != nil {
+ b.Release = hb.Metrics.Release
+ }
+ p.Ready = p.Ready || b.Counted
+ p.Boxes = append(p.Boxes, b)
+ }
+ switch {
+ case p.Ready:
+ case len(serving) == 0:
+ p.Reason = reasonNoServingBox
+ case !atFloor:
+ p.Reason = reasonBelowFloor
+ default:
+ p.Reason = reasonNoAddress
+ }
+ out.Placements = append(out.Placements, p)
+ }
+ if reason := regionalHold(c, snap, heartbeats); reason != "" {
+ for i := range out.Placements {
+ out.Placements[i].Ready, out.Placements[i].Reason = false, reason
+ }
+ }
+ return out
+}
+
+// regionalHold is the reason that holds every region of a regional claim
+// at once (spec §8), or "". First match wins:
+//
+// - evidence-incomplete: the snapshot is not EvidenceComplete (an edges
+// file or heartbeat that did not read, a fresh box with no edges file,
+// a file with no heartbeat), or a fresh heartbeat does not say its
+// alias read succeeded (no metrics, aliases_read false or absent);
+// - route-collision: a fresh file publishes the host or "*."+host under
+// home without the alias mark (an entry that does not decode counts:
+// nothing can vouch for it);
+// - settling: a fresh heartbeat was generated before the claim's
+// created_at (one that does not parse counts), or lists the host or
+// "*."+host among its alias rows, or a fresh file publishes either
+// under home as an alias. Every fresh box must report after creation
+// with no ordinary row for the name before DNS points at it.
+func regionalHold(c domains.Claim, snap edgesfile.Snapshot, heartbeats map[string]status.Box) string {
+ if !snap.EvidenceComplete() {
+ return reasonEvidenceIncomplete
+ }
+ for _, hb := range heartbeats {
+ if hb.Metrics == nil || !hb.Metrics.AliasesRead {
+ return reasonEvidenceIncomplete
+ }
+ }
+ keys := []string{c.Host, "*." + c.Host}
+ published := func(alias bool) bool {
+ for _, f := range snap.Files {
+ if !f.Fresh {
+ continue
+ }
+ for _, k := range keys {
+ raw, ok := f.Hosts[k]
+ if !ok {
+ continue
+ }
+ var h edgesfile.Host
+ if err := json.Unmarshal(raw, &h); err != nil {
+ if !alias {
+ return true
+ }
+ continue
+ }
+ if h.Role == edgesfile.RoleHome && h.Alias == alias {
+ return true
+ }
+ }
+ }
+ return false
+ }
+ if published(false) {
+ return reasonRouteCollision
+ }
+ created, err := time.Parse(time.RFC3339, c.CreatedAt)
+ for _, hb := range heartbeats {
+ if err != nil || hb.GeneratedAt.Before(created) {
+ return reasonSettling
+ }
+ for _, k := range keys {
+ if _, ok := hb.Metrics.Aliases[k]; ok {
+ return reasonSettling
+ }
+ }
+ }
+ if published(true) {
+ return reasonSettling
+ }
+ return ""
+}
+
// freshHeartbeats is each box's heartbeat by label, fresh ones only.
func freshHeartbeats(boxes []status.Box, now time.Time) map[string]status.Box {
out := make(map[string]status.Box, len(boxes))
@@ -261,6 +381,14 @@ func placementsNoReleaseMsg(box, floor string) string {
return fmt.Sprintf("%s does not say which release it runs. try again when every server runs %s or later.", box, floor)
}
+// regionalDNSGuidance (RD-44, draft) is a regional domain's DNS advice on
+// the domain list, the per-host GET and the settings page, in place of the
+// single-edge advice (domainGuidance), which names every edge for one
+// route. Where to point DNS is per region, and the placements read says it.
+func regionalDNSGuidance(host string) string {
+ return fmt.Sprintf("%s is a regional domain. carlos domains placements shows the addresses to point DNS at in each region.", host)
+}
+
// placementsControlPlaneVerb (RD-40) completes controlPlaneRefusal's
// sentence: "<app> is marked as the control plane, so it cannot be ...".
const placementsControlPlaneVerb = "given a regional domain"
diff --git a/internal/console/apiplacements_test.go b/internal/console/apiplacements_test.go
index ac0d51e32..4331acf81 100644
--- a/internal/console/apiplacements_test.go
+++ b/internal/console/apiplacements_test.go
@@ -10,6 +10,7 @@ import (
"context"
"encoding/json"
"net/http"
+ "strings"
"testing"
"time"
@@ -214,3 +215,277 @@ func TestBoxAtRegionalFloor(t *testing.T) {
t.Error("a heartbeat with no metrics is at the floor")
}
}
+
+// putRegionalWorldClaim writes the world's regional claim on rdHost (ie and
+// uk, Route rdIE) through the real claim writer, created at created.
+func (w *regionalWorld) putRegionalWorldClaim(t *testing.T, created time.Time) {
+ t.Helper()
+ c := domains.Claim{Host: rdHost, Account: w.fx.sqid, App: "shop", Route: rdIE,
+ CreatedAt: created.UTC().Format(time.RFC3339), CreatedBy: "paul@keymail.dev",
+ Placements: []domains.Placement{{Region: "", Host: rdIE}, {Region: "uk", Host: rdUK}}}
+ if changed, err := domains.SetClaimPlacements(context.Background(), w.fx.rel, c, nil, ""); err != nil || !changed {
+ t.Fatalf("SetClaimPlacements: changed=%v err=%v", changed, err)
+ }
+}
+
+// regionalEntry is one placement of a regional GET, boxes decoded.
+type regionalEntry struct {
+ Region, Target string
+ Ready bool
+ Reason string
+ Boxes []placementsBoxResp
+}
+
+// getRegional is the placements GET of rdHost: its mode and route, and
+// each entry in order.
+func (w *regionalWorld) getRegional(t *testing.T) (placementsResp, []regionalEntry) {
+ t.Helper()
+ code, _, out := rawReq(t, http.MethodGet, placementsURL(w.fx, "shop", rdHost), w.token, "")
+ if code != http.StatusOK {
+ t.Fatalf("placements GET = %d %s, want 200", code, out)
+ }
+ var got placementsResp
+ if err := json.Unmarshal([]byte(out), &got); err != nil {
+ t.Fatalf("placements body %s: %v", out, err)
+ }
+ entries := make([]regionalEntry, 0, len(got.Placements))
+ for _, p := range got.Placements {
+ e := regionalEntry{Region: p.Region, Target: p.Target, Ready: p.Ready, Reason: p.Reason}
+ if err := json.Unmarshal(p.Boxes, &e.Boxes); err != nil || e.Boxes == nil {
+ t.Fatalf("boxes %s: %v (never null)", p.Boxes, err)
+ }
+ entries = append(entries, e)
+ }
+ return got, entries
+}
+
+// requireRegionalStates fails unless the GET's two entries (ie, then uk)
+// read as want: "" for ready, a reason otherwise.
+func (w *regionalWorld) requireRegionalStates(t *testing.T, what, wantIE, wantUK string) []regionalEntry {
+ t.Helper()
+ got, entries := w.getRegional(t)
+ if got.Mode != "regional" || got.Host != rdHost || got.Route != rdIE || len(entries) != 2 ||
+ entries[0].Region != "ie" || entries[0].Target != rdIE || entries[1].Region != "uk" || entries[1].Target != rdUK {
+ t.Fatalf("%s: answer = %+v %+v, want regional %s, ie=%s then uk=%s", what, got, entries, rdHost, rdIE, rdUK)
+ }
+ for i, want := range []string{wantIE, wantUK} {
+ e := entries[i]
+ if e.Ready != (want == "") || e.Reason != want {
+ t.Errorf("%s: %s = ready %v reason %q, want reason %q", what, e.Region, e.Ready, e.Reason, want)
+ }
+ }
+ return entries
+}
+
+// TestPlacementsGetRegionalReadiness (W8): each region of a regional claim
+// is ready only from a fresh box in that region, at the floor, publishing
+// the target under home and an EIP. No region stands in for another.
+// Incomplete evidence, a real route at the name and a box that has not
+// reported since the claim was created each hold every region at once.
+func TestPlacementsGetRegionalReadiness(t *testing.T) {
+ w := newRegionalWorld(t, "code-rdget-ready")
+ w.putRegionalWorldClaim(t, time.Now().Add(-time.Minute))
+ reset := func() {
+ w.putBox(t, rdBox("annie", "", "203.0.113.10", rdIE))
+ w.putBox(t, rdBox("betty", "uk", "203.0.113.20", rdUK))
+ }
+
+ entries := w.requireRegionalStates(t, "both serving", "", "")
+ wantIE := placementsBoxResp{Box: "annie", EIP: "203.0.113.10", AWSRegion: "eu-west-1", Release: rdFloor(), Counted: true}
+ wantUK := placementsBoxResp{Box: "betty", EIP: "203.0.113.20", AWSRegion: "eu-west-1", Release: rdFloor(), Counted: true}
+ if len(entries[0].Boxes) != 1 || entries[0].Boxes[0] != wantIE || len(entries[1].Boxes) != 1 || entries[1].Boxes[0] != wantUK {
+ t.Fatalf("boxes = %+v / %+v, want [%+v] / [%+v]", entries[0].Boxes, entries[1].Boxes, wantIE, wantUK)
+ }
+
+ // Per placement: uk's box below the floor, then without an address,
+ // then serving nothing. ie stays ready throughout.
+ old := rdBox("betty", "uk", "203.0.113.20", rdUK)
+ old.Release = "v0.30.2"
+ w.putBox(t, old)
+ entries = w.requireRegionalStates(t, "uk below the floor", "", reasonBelowFloor)
+ if b := entries[1].Boxes; len(b) != 1 || b[0].Box != "betty" || b[0].Counted || b[0].Release != "v0.30.2" {
+ t.Fatalf("uk boxes = %+v, want betty listed, not counted", b)
+ }
+ w.putBox(t, rdBox("betty", "uk", "", rdUK))
+ w.requireRegionalStates(t, "uk with no address", "", reasonNoAddress)
+ // One box at the floor without an address beside one below it with
+ // one: the region has a box at the floor, so the gap is the address.
+ cara := rdBox("cara", "uk", "203.0.113.21", rdUK)
+ cara.Release = "v0.30.2"
+ w.putBox(t, cara)
+ w.requireRegionalStates(t, "uk at the floor without an address, below it with one", "", reasonNoAddress)
+ cara.At = time.Now().Add(-time.Hour) // retired: stale, ignored
+ w.putBox(t, cara)
+ w.putBox(t, rdBox("betty", "uk", "203.0.113.20"))
+ w.requireRegionalStates(t, "uk serving nothing", "", reasonNoServingBox)
+
+ // A ready ie never makes uk ready: annie (home) publishing uk's target
+ // is not a box in uk.
+ w.putBox(t, rdBox("annie", "", "203.0.113.10", rdIE, rdUK))
+ w.requireRegionalStates(t, "uk's target served only from home", "", reasonNoServingBox)
+ // A stale box in uk publishing the target does not count either.
+ stale := rdBox("betty", "uk", "203.0.113.20", rdUK)
+ stale.At = time.Now().Add(-time.Hour)
+ w.putBox(t, stale)
+ w.requireRegionalStates(t, "uk's box stale", "", reasonNoServingBox)
+ reset()
+ w.requireRegionalStates(t, "reset", "", "")
+
+ // Incomplete evidence: every region, whatever its boxes say.
+ dora := rdBox("dora", "uk", "203.0.113.22")
+ dora.NoEdges = true // a fresh heartbeat with no edges file
+ w.putBox(t, dora)
+ w.requireRegionalStates(t, "a fresh box with no edges file", reasonEvidenceIncomplete, reasonEvidenceIncomplete)
+ dora.At = time.Now().Add(-time.Hour)
+ w.putBox(t, dora)
+ w.requireRegionalStates(t, "that box retired", "", "")
+ unread := rdBox("betty", "uk", "203.0.113.20", rdUK)
+ unread.AliasesRead = false
+ w.putBox(t, unread)
+ w.requireRegionalStates(t, "aliases_read false", reasonEvidenceIncomplete, reasonEvidenceIncomplete)
+ // A heartbeat from a binary that predates the field: no key at all.
+ hb, err := json.Marshal(map[string]any{"generated_at": time.Now().UTC(), "label": "betty", "region": "eu-west-1",
+ "metrics": map[string]any{"release": rdFloor()}})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if strings.Contains(string(hb), "aliases_read") {
+ t.Fatalf("fixture heartbeat carries the key: %s", hb)
+ }
+ putFixtureObject(t, w.fx.rel, "status/boxes/betty.json", hb)
+ w.requireRegionalStates(t, "no aliases_read key", reasonEvidenceIncomplete, reasonEvidenceIncomplete)
+ bare := rdBox("betty", "uk", "203.0.113.20", rdUK)
+ bare.NoMetrics = true
+ w.putBox(t, bare)
+ w.requireRegionalStates(t, "no metrics", reasonEvidenceIncomplete, reasonEvidenceIncomplete)
+ reset()
+
+ // A real route at the name, or at "*."+name: route-collision.
+ for _, key := range []string{rdHost, "*." + rdHost} {
+ b := rdBox("annie", "", "203.0.113.10", rdIE)
+ b.Hosts[key] = edgesfile.Host{Role: edgesfile.RoleHome}
+ w.putBox(t, b)
+ w.requireRegionalStates(t, "a real route at "+key, reasonRouteCollision, reasonRouteCollision)
+ }
+ reset()
+
+ // Settling: a fresh box that has not reported since the claim was
+ // created; one that lists the name, or "*."+name, as an alias row; a
+ // file publishing either as an alias.
+ before := rdBox("betty", "uk", "203.0.113.20", rdUK)
+ before.At = time.Now().Add(-2 * time.Minute)
+ w.putBox(t, before)
+ w.requireRegionalStates(t, "betty reported before created_at", reasonSettling, reasonSettling)
+ reset()
+ for _, key := range []string{rdHost, "*." + rdHost} {
+ b := rdBox("betty", "uk", "203.0.113.20", rdUK)
+ b.Aliases = map[string]status.AliasReading{key: {Route: rdUK}}
+ w.putBox(t, b)
+ w.requireRegionalStates(t, "betty lists "+key+" as an alias row", reasonSettling, reasonSettling)
+ reset()
+ a := rdBox("annie", "", "203.0.113.10", rdIE)
+ a.Hosts[key] = edgesfile.Host{Role: edgesfile.RoleHome, Alias: true}
+ w.putBox(t, a)
+ w.requireRegionalStates(t, "annie publishes "+key+" as an alias", reasonSettling, reasonSettling)
+ reset()
+ }
+
+ // First match wins: incomplete evidence over a collision, a collision
+ // over settling.
+ b := rdBox("annie", "", "203.0.113.10", rdIE)
+ b.Hosts[rdHost] = edgesfile.Host{Role: edgesfile.RoleHome}
+ w.putBox(t, b)
+ w.putBox(t, before)
+ w.requireRegionalStates(t, "a collision while settling", reasonRouteCollision, reasonRouteCollision)
+ w.putBox(t, unread)
+ w.requireRegionalStates(t, "a collision with incomplete evidence", reasonEvidenceIncomplete, reasonEvidenceIncomplete)
+}
+
+// TestPlacementsGetShowsADeletedTarget (Review Focus 1): once uk's box no
+// longer publishes its target (the instance was deleted or moved), uk is
+// not ready, and ie, whose instance still serves, stays ready.
+func TestPlacementsGetShowsADeletedTarget(t *testing.T) {
+ w := newRegionalWorld(t, "code-rdget-deleted")
+ w.putRegionalWorldClaim(t, time.Now().Add(-time.Minute))
+ w.requireRegionalStates(t, "both serving", "", "")
+ w.putBox(t, rdBox("betty", "uk", "203.0.113.20"))
+ entries := w.requireRegionalStates(t, "uk's route gone", "", reasonNoServingBox)
+ if len(entries[1].Boxes) != 0 {
+ t.Fatalf("uk boxes = %+v, want none", entries[1].Boxes)
+ }
+}
+
+// The PUT answers the regional view it built from its own snapshot: right
+// after creation every box reported before created_at, so every region is
+// settling.
+func TestPlacementsPutAnswersTheRegionalView(t *testing.T) {
+ w := newRegionalWorld(t, "code-rdput-view")
+ for _, b := range []regionalBox{rdBox("annie", "", "203.0.113.10", rdIE), rdBox("betty", "uk", "203.0.113.20", rdUK)} {
+ b.At = time.Now().Add(-time.Minute)
+ w.putBox(t, b)
+ }
+ code, out := w.put(t, rdHost, rdBoth())
+ if code != http.StatusOK {
+ t.Fatalf("PUT = %d %s", code, out)
+ }
+ var got placementsResp
+ if err := json.Unmarshal([]byte(out), &got); err != nil {
+ t.Fatal(err)
+ }
+ if got.Mode != "regional" || len(got.Placements) != 2 {
+ t.Fatalf("answer = %s, want the regional view", out)
+ }
+ for _, p := range got.Placements {
+ if p.Ready || p.Reason != reasonSettling {
+ t.Errorf("%s = ready %v reason %q, want settling", p.Region, p.Ready, p.Reason)
+ }
+ }
+}
+
+// A regional domain is never given the single-edge DNS advice (one set of
+// edge addresses for every region): the list row, the per-host GET and the
+// settings page point at the placements read instead, and send no records.
+// An ordinary claim beside it keeps its advice.
+func TestRegionalDomainGetsNoSingleEdgeDNSAdvice(t *testing.T) {
+ w := newRegionalWorld(t, "code-rd-dnsadvice")
+ w.putRegionalWorldClaim(t, time.Now())
+ attachShopClaim(t, w.fx, w.fx.sqid, "shop", "plain.example.com", rdIE)
+ want := regionalDNSGuidance(rdHost)
+
+ status, out := getJSON(t, domainsURL(w.fx, w.fx.sqid, "shop"), w.token)
+ if status != http.StatusOK {
+ t.Fatalf("list = %d %v", status, out)
+ }
+ rows := map[string]map[string]any{}
+ for _, r := range out["domains"].([]any) {
+ row := r.(map[string]any)
+ rows[row["host"].(string)] = row
+ }
+ status, got := getJSON(t, domainGetURL(w.fx, w.fx.sqid, "shop", rdHost), w.token)
+ if status != http.StatusOK {
+ t.Fatalf("GET %s = %d %v", rdHost, status, got)
+ }
+ for what, row := range map[string]map[string]any{"list": rows[rdHost], "GET": got["domain"].(map[string]any)} {
+ if row == nil || row["guidance"] != want || row["records"] != nil {
+ t.Errorf("%s row = %v, want guidance %q and no records", what, row, want)
+ }
+ }
+ if plain := rows["plain.example.com"]; plain == nil || plain["guidance"] == want || plain["records"] == nil {
+ t.Errorf("ordinary row = %v, want its own DNS advice and records", plain)
+ }
+
+ acct, err := w.fx.st.AccountBySqid(w.fx.sqid)
+ if err != nil || acct == nil {
+ t.Fatalf("account %s: %v", w.fx.sqid, err)
+ }
+ views := map[string]DomainView{}
+ for _, dv := range w.fx.srv.settingsDomains(context.Background(), acct, "shop", nil) {
+ views[dv.Domain] = dv
+ }
+ if dv := views[rdHost]; dv.Guidance != want {
+ t.Errorf("settings row = %+v, want guidance %q", dv, want)
+ }
+ if dv := views["plain.example.com"]; dv.Guidance == "" || dv.Guidance == want {
+ t.Errorf("ordinary settings row = %+v, want its own DNS advice", dv)
+ }
+}
diff --git a/internal/console/appsettings.go b/internal/console/appsettings.go
index 14279af71..cf2dc70ae 100644
--- a/internal/console/appsettings.go
+++ b/internal/console/appsettings.go
@@ -755,6 +755,10 @@ func (s *Server) settingsDomains(ctx context.Context, acct *Account, app string,
continue
}
dv := claimDomainView(c.Host, s.dnsTargets(ctx))
+ if c.Regional() {
+ // Not the single-edge advice: see domainItem.
+ dv.Guidance = regionalDNSGuidance(c.Host)
+ }
dv.State, dv.Reason, dv.Detail = state(c)
if c.Pending {
// The proof comes first: until it is published nothing else on
diff --git a/internal/host/aliasesread_e2e_test.go b/internal/host/aliasesread_e2e_test.go
new file mode 100644
index 000000000..bcc2787bd
--- /dev/null
+++ b/internal/host/aliasesread_e2e_test.go
@@ -0,0 +1,391 @@
+package host
+
+import (
+ "context"
+ "database/sql"
+ "encoding/json"
+ "errors"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/console"
+ "github.com/carlosframework/platform/internal/domains"
+ "github.com/carlosframework/platform/internal/provision"
+ "github.com/carlosframework/platform/internal/registry"
+ "github.com/carlosframework/platform/internal/release"
+ "github.com/carlosframework/platform/internal/status"
+)
+
+// The world of TestFailedAliasReadIsIncompleteEvidence: app shop of the ops
+// account, an instance at home (named ie) and one in uk, a box serving
+// each, and the console over the same deployment store.
+const (
+ arHost = "shop.example.com"
+ arIE = "shop-ie.example.net"
+ arUK = "shop-uk.example.net"
+ arAddr = "owner@example.com"
+)
+
+// arBox is one box: its own registry, as its agent opens it, and the
+// identity its edges file publishes.
+type arBox struct {
+ name, placement, eip string
+ path string
+ reg *registry.Registry
+}
+
+// arWorld is the deployment store, the console's doors over it and the
+// two boxes.
+type arWorld struct {
+ t *testing.T
+ s release.Store
+ base, token string
+ annie *arBox
+ betty *arBox
+}
+
+func newAliasReadWorld(t *testing.T) *arWorld {
+ t.Helper()
+ ctx := context.Background()
+ t.Setenv("CARLOS_HOST_CLAIM", "")
+ s := release.NewDirStore(t.TempDir())
+
+ // The console, built as the offline move's end-to-end world builds it
+ // (movesoffline_e2e_test.go): the real server over the deployment
+ // store, an owner of the ops account holding app shop, a CLI token.
+ seed, pubB64, err := release.GenerateKey()
+ if err != nil {
+ t.Fatal(err)
+ }
+ relPriv, err := release.ParseSigningKey(seed, "test")
+ if err != nil {
+ t.Fatal(err)
+ }
+ relPub, err := release.ParsePublicKey(pubB64, "test")
+ if err != nil {
+ t.Fatal(err)
+ }
+ dir := t.TempDir()
+ cst, err := console.Open(filepath.Join(dir, "console.db"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { cst.Close() })
+ var srv *console.Server
+ ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { srv.ServeHTTP(w, r) }))
+ t.Cleanup(ts.Close)
+ if srv, err = console.NewServer(console.Config{Origin: ts.URL, Keymail: "http://keymail.invalid",
+ Registry: filepath.Join(dir, "registry.db"), Releases: s, ReleasePub: relPub, Key: relPriv, AppScheme: "http",
+ HomeRegion: "ie"}, cst); err != nil {
+ t.Fatal(err)
+ }
+ now := time.Now()
+ if err := cst.AddMember(console.OpsAccountID, arAddr, console.RoleOwner, now); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := cst.CreateAppIn(console.OpsAccountID, "shop", arAddr, now); err != nil {
+ t.Fatal(err)
+ }
+ userCode, deviceCode, err := cst.NewCLIAuth("owner@laptop", "127.0.0.1", now)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := cst.ApproveCLIAuth(userCode, arAddr, now); err != nil {
+ t.Fatal(err)
+ }
+ _, token, _, err := cst.PollCLIAuth(deviceCode, now)
+ if err != nil || token == "" {
+ t.Fatalf("no CLI token: %v", err)
+ }
+
+ // The deployment: the ops account's manifest, shop's, and its two
+ // instance records.
+ acct := release.OpsAccount
+ manifest, err := json.Marshal(map[string]any{"id": console.OpsAccountID, "sqid": acct, "name": "ops", "created_at": now})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := s.Put(ctx, domains.AccountManifestKey(acct), manifest, ""); err != nil {
+ t.Fatal(err)
+ }
+ if err := provision.PutManifest(ctx, s, acct, "shop", provision.Manifest{Schema: 1, App: "shop", Domain: "example.net"}); err != nil {
+ t.Fatal(err)
+ }
+ for _, r := range []struct{ host, region string }{{arIE, ""}, {arUK, "uk"}} {
+ if err := provision.CreateRecord(ctx, s, provision.Record{Schema: 1, Host: r.host, Slug: strings.SplitN(r.host, ".", 2)[0],
+ App: "shop", Account: acct, Region: r.region, Channel: "stable", CreatedAt: now.UTC(), CreatedBy: arAddr}); err != nil {
+ t.Fatal(err)
+ }
+ }
+
+ w := &arWorld{t: t, s: s, base: ts.URL + "/api/cli/apps/" + acct + "/shop/domains/", token: token}
+ w.annie = w.box("annie", "", "203.0.113.10", arIE)
+ w.betty = w.box("betty", "uk", "203.0.113.20", arUK)
+ return w
+}
+
+// box opens a box's registry with its instance's route, ready, and
+// publishes its edges file through the production writer.
+func (w *arWorld) box(name, placement, eip, serves string) *arBox {
+ w.t.Helper()
+ b := &arBox{name: name, placement: placement, eip: eip, path: filepath.Join(w.t.TempDir(), "registry.db")}
+ reg, err := registry.Open(b.path)
+ if err != nil {
+ w.t.Fatal(err)
+ }
+ w.t.Cleanup(func() { reg.Close() })
+ b.reg = reg
+ if err := reg.Upsert(registry.Route{Host: serves, Kind: "instance", Socket: "/run/carlos/" + serves + ".sock",
+ Status: "ready", Account: release.OpsAccount, App: "shop", Region: placement}); err != nil {
+ w.t.Fatal(err)
+ }
+ if err := reg.SetProvisioned(serves, true); err != nil {
+ w.t.Fatal(err)
+ }
+ var last []byte
+ if err := edgesFileWrite(context.Background(), w.s, reg, edgesFile{Box: name, Region: "eu-west-1", Placement: placement}, eip, &last, false); err != nil {
+ w.t.Fatal(err)
+ }
+ return b
+}
+
+// tick is the box's status loop once: the real statusTick, its heartbeat
+// naming a release at the regional floor.
+func (w *arWorld) tick(b *arBox) {
+ w.t.Helper()
+ p := status.Probes{MachineID: b.name, Release: "v" + release.RegionalDomainsFloor.String()}
+ if err := statusTick(context.Background(), w.s, b.reg, p, false, b.name); err != nil {
+ w.t.Fatal(err)
+ }
+}
+
+// breakAliasRead makes the box's alias read fail, every other read still
+// working, by renaming the table through a second handle on the file; the
+// row it holds survives for restoreAliasRead.
+func (w *arWorld) breakAliasRead(b *arBox) { w.renameAliases(b, "route_aliases", "route_aliases_away") }
+
+func (w *arWorld) restoreAliasRead(b *arBox) {
+ w.renameAliases(b, "route_aliases_away", "route_aliases")
+}
+
+func (w *arWorld) renameAliases(b *arBox, from, to string) {
+ w.t.Helper()
+ db, err := sql.Open("sqlite", b.path)
+ if err != nil {
+ w.t.Fatal(err)
+ }
+ defer db.Close()
+ if _, err := db.Exec("PRAGMA busy_timeout=5000"); err != nil {
+ w.t.Fatal(err)
+ }
+ if _, err := db.Exec("ALTER TABLE " + from + " RENAME TO " + to); err != nil {
+ w.t.Fatal(err)
+ }
+}
+
+// heartbeat is the box's latest heartbeat as stored.
+func (w *arWorld) heartbeat(b *arBox) (raw []byte, box status.Box) {
+ w.t.Helper()
+ raw, _, err := w.s.Get(context.Background(), "status/boxes/"+b.name+".json")
+ if err != nil {
+ w.t.Fatal(err)
+ }
+ if err := json.Unmarshal(raw, &box); err != nil {
+ w.t.Fatal(err)
+ }
+ return raw, box
+}
+
+// do is one request to the console's domain doors for shop.
+func (w *arWorld) do(method, path, body string) (int, string) {
+ w.t.Helper()
+ req, err := http.NewRequest(method, w.base+path, strings.NewReader(body))
+ if err != nil {
+ w.t.Fatal(err)
+ }
+ req.Header.Set("Authorization", "Bearer "+w.token)
+ req.Header.Set("Content-Type", "application/json")
+ res, err := http.DefaultClient.Do(req)
+ if err != nil {
+ w.t.Fatal(err)
+ }
+ defer res.Body.Close()
+ raw, _ := io.ReadAll(res.Body)
+ return res.StatusCode, string(raw)
+}
+
+// put is the regional PUT of arHost: ie and uk.
+func (w *arWorld) put() (int, string) {
+ w.t.Helper()
+ return w.do(http.MethodPut, arHost+"/placements",
+ `{"placements":[{"region":"ie","host":"`+arIE+`"},{"region":"uk","host":"`+arUK+`"}]}`)
+}
+
+// requireNoClaim fails unless no claim object exists for arHost.
+func (w *arWorld) requireNoClaim(what string) {
+ w.t.Helper()
+ if _, _, err := w.s.Get(context.Background(), domains.ClaimKey(arHost)); !errors.Is(err, os.ErrNotExist) {
+ w.t.Fatalf("%s: claim %s: %v, want none written", what, arHost, err)
+ }
+}
+
+// reasons is the placements GET's (ready, reason) per region.
+func (w *arWorld) reasons(what string) map[string]string {
+ w.t.Helper()
+ code, out := w.do(http.MethodGet, arHost+"/placements", "")
+ if code != http.StatusOK {
+ w.t.Fatalf("%s: GET = %d %s", what, code, out)
+ }
+ var got struct {
+ Mode string `json:"mode"`
+ Placements []struct {
+ Region string `json:"region"`
+ Ready bool `json:"ready"`
+ Reason string `json:"reason"`
+ } `json:"placements"`
+ }
+ if err := json.Unmarshal([]byte(out), &got); err != nil || got.Mode != "regional" || len(got.Placements) != 2 {
+ w.t.Fatalf("%s: GET = %s (%v), want the regional view of two regions", what, out, err)
+ }
+ r := map[string]string{}
+ for _, p := range got.Placements {
+ if p.Ready {
+ r[p.Region] = "ready"
+ } else {
+ r[p.Region] = p.Reason
+ }
+ }
+ return r
+}
+
+func (w *arWorld) requireReasons(what, want string) {
+ w.t.Helper()
+ if got := w.reasons(what); got["ie"] != want || got["uk"] != want {
+ w.t.Fatalf("%s: GET = %v, want %q in ie and uk", what, got, want)
+ }
+}
+
+// TestFailedAliasReadIsIncompleteEvidence (W13, #447 ruling 5a), through the
+// real statusTick, CollectBox, heartbeat store, production edges writer and
+// console server. Box betty, current, holds a retained route_aliases row for
+// shop.example.com whose DNS status is not pointing, so its edges file
+// leaves it out; with its alias read failing its heartbeat names a current
+// release and has no aliases_read. Nothing else can see the row:
+//
+// 1. the regional PUT answers 503 and writes nothing;
+// 2. with the read healthy, the same PUT 409s on the row the heartbeat lists;
+// 3. with the claim written directly and the read failing again, a
+// heartbeat after created_at: the GET says evidence-incomplete in every
+// region, never ready;
+// 4. the row gone and the read healthy, both regions are ready (the
+// control: step 3's boxes do serve);
+// 5. a heartbeat decoded from a pre-field binary's JSON (no key at all) is
+// judged as a failed read: the GET says evidence-incomplete and an
+// update PUT answers 503.
+//
+// Mutation check (recorded in the task report): with the barrier
+// (regionalReadyRefusal) ignoring aliases_read, step 1's PUT writes the
+// claim.
+func TestFailedAliasReadIsIncompleteEvidence(t *testing.T) {
+ w := newAliasReadWorld(t)
+ if err := w.betty.reg.UpsertAlias(registry.RouteAlias{Alias: arHost, Host: arUK, Account: release.OpsAccount, App: "shop",
+ DNSStatus: "elsewhere", CreatedAt: time.Now().Unix()}); err != nil {
+ t.Fatal(err)
+ }
+ // Republished with the row in place: not pointing, so withheld.
+ var last []byte
+ if err := edgesFileWrite(context.Background(), w.s, w.betty.reg, edgesFile{Box: "betty", Region: "eu-west-1", Placement: "uk"}, w.betty.eip, &last, false); err != nil {
+ t.Fatal(err)
+ }
+ if raw, _, err := w.s.Get(context.Background(), edgesFileKey("betty")); err != nil || strings.Contains(string(raw), `"`+arHost+`"`) {
+ t.Fatalf("betty's edges file = %s (%v), want the alias withheld", raw, err)
+ }
+
+ // 1. The read fails: a current release, no aliases_read, no rows.
+ w.tick(w.annie)
+ w.breakAliasRead(w.betty)
+ w.tick(w.betty)
+ raw, hb := w.heartbeat(w.betty)
+ if hb.Metrics == nil || hb.Metrics.Release == "" || hb.Metrics.AliasesRead || len(hb.Metrics.Aliases) != 0 ||
+ strings.Contains(string(raw), "aliases_read") {
+ t.Fatalf("betty's heartbeat = %s, want a current release, no aliases_read and no alias rows", raw)
+ }
+ if code, out := w.put(); code != http.StatusServiceUnavailable {
+ t.Fatalf("PUT with betty's alias read failing = %d %s, want 503", code, out)
+ }
+ w.requireNoClaim("the PUT with the read failing")
+
+ // 2. The read healthy: the heartbeat lists the row, and the PUT refuses.
+ w.restoreAliasRead(w.betty)
+ w.tick(w.betty)
+ if _, hb := w.heartbeat(w.betty); hb.Metrics == nil || !hb.Metrics.AliasesRead {
+ t.Fatalf("betty's healthy heartbeat = %+v, want aliases_read", hb.Metrics)
+ } else if _, listed := hb.Metrics.Aliases[arHost]; !listed {
+ t.Fatalf("betty's healthy heartbeat lists %v, want %s", hb.Metrics.Aliases, arHost)
+ }
+ if code, out := w.put(); code != http.StatusConflict {
+ t.Fatalf("PUT with the row listed = %d %s, want 409", code, out)
+ }
+ w.requireNoClaim("the PUT with the row listed")
+
+ // 3. The claim written directly; betty still holds the row, its read
+ // failing, and both boxes report after created_at.
+ claim := domains.Claim{Host: arHost, Account: release.OpsAccount, App: "shop", Route: arIE,
+ CreatedAt: time.Now().Add(-time.Minute).UTC().Format(time.RFC3339), CreatedBy: arAddr,
+ Placements: []domains.Placement{{Region: "", Host: arIE}, {Region: "uk", Host: arUK}}}
+ if changed, err := domains.SetClaimPlacements(context.Background(), w.s, claim, nil, ""); err != nil || !changed {
+ t.Fatalf("SetClaimPlacements: changed=%v err=%v", changed, err)
+ }
+ w.breakAliasRead(w.betty)
+ w.tick(w.annie)
+ w.tick(w.betty)
+ w.requireReasons("betty's read failing", "evidence-incomplete")
+
+ // 4. The control: the row gone and the read healthy, both are ready.
+ w.restoreAliasRead(w.betty)
+ if err := w.betty.reg.DeleteAlias(arHost); err != nil {
+ t.Fatal(err)
+ }
+ w.tick(w.betty)
+ w.requireReasons("betty healthy, no row", "ready")
+
+ // 5. A pre-field binary's heartbeat: the same body with no key.
+ raw, _ = w.heartbeat(w.betty)
+ var doc map[string]any
+ if err := json.Unmarshal(raw, &doc); err != nil {
+ t.Fatal(err)
+ }
+ metrics, _ := doc["metrics"].(map[string]any)
+ if metrics["aliases_read"] != true {
+ t.Fatalf("betty's heartbeat = %s, want aliases_read true before it is removed", raw)
+ }
+ delete(metrics, "aliases_read")
+ old, err := json.Marshal(doc)
+ if err != nil {
+ t.Fatal(err)
+ }
+ _, etag, err := w.s.Get(context.Background(), "status/boxes/betty.json")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := w.s.Put(context.Background(), "status/boxes/betty.json", old, etag); err != nil {
+ t.Fatal(err)
+ }
+ w.requireReasons("a pre-field heartbeat", "evidence-incomplete")
+ before, _, err := w.s.Get(context.Background(), domains.ClaimKey(arHost))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if code, out := w.do(http.MethodPut, arHost+"/placements", `{"placements":[{"region":"ie","host":"`+arIE+`"}]}`); code != http.StatusServiceUnavailable {
+ t.Fatalf("update PUT with a pre-field heartbeat = %d %s, want 503", code, out)
+ }
+ if after, _, err := w.s.Get(context.Background(), domains.ClaimKey(arHost)); err != nil || string(after) != string(before) {
+ t.Fatalf("the claim changed under a refused update: %s (%v), was %s", after, err, before)
+ }
+}