carlos / platform Public

region HA P3b T1: review round 1 fixes for names and reader gate

Restore legacy fixed-box updates and routing until group admission evidence
requires the stricter checks. Retain closed catch-all children, latch observed
group publishers, and scope the name census to producer functions.

Targeted tests, nine mutation witnesses, build, vet, formatting, and Darwin
and Windows cross-builds pass. Independent census review remains pending.
Co-Authored-By: GPT-6 Astra (codex) <noreply@openai.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev 9dfeecabb87ad4d4e200d2ca7b7c57d68066fceb parent 4573a81
10 files changed, +480 −88
  • internal/edge/edge.go +8 −8
  • internal/edge/group_names_test.go +127 −0
  • internal/edge/group_readers.go +1 −1
  • internal/edge/group_readers_test.go +42 −1
  • internal/edge/homemap.go +31 −15
  • internal/edgesfile/nameauthority.go +38 −12
  • internal/edgesfile/snapshot.go +25 −9
  • internal/host/group_names_test.go +127 −40
  • internal/host/systemleg.go +7 −1
  • internal/host/systemleg_test.go +74 −1

Intent

Human

<task-notification> <task-id>a3b7e040e0af1de66</task-id> <tool-use-id>toolu_012bwSgJ1G9K1DwCZFmpYdot</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/05c816f1-0a2d-43e3-9285-de8352549786/tasks/a3b7e040e0af1de66.output</output-file> <status>completed</status> <summary>Agent "Review Task 1 (spec + quality)" finished</summary> <note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note> <result>**Verdict: Needs fixes.** P1: 1, P2: 4, P3: 5. Because there is a P1, round 1 does not end the review. I ran one focused test through `go test -overlay`, so the worktree was not modified. It is used as evidence for P2-1. I deleted the scratch files afterwards and the tracked tree is clean. - **P1-1** (T1 update path / fixed-box byte-identity), `internal/host/systemleg.go:330-336`: the self-update gate checks that the cached fold is fresh and complete before it checks whether any group exists. So on today's fleet, with no group at all, a fixed box refuses every update when: - the home map is nil; - one edges file is unreadable or corrupt (blocked permanently, because routing carries that file forward); - a file's box field and key don't match; - a list read fails; - the 5-minute freshness window lapses. This contradicts the controller's instruction that updates must work exactly as today when no group is present. No test covers "no group plus an incomplete fold". - **P2-1** (name ownership vs dial eligibility / fixed-box byte-identity), `internal/edge/edge.go:1999-2013`: a custom alias a box serves itself now loses to any other box's copy of the same alias. The local claim drops its stamp, so a peer with a stamp, or with a higher lifetime pair, wins. The overlay test reproduced it: with a legacy peer publishing the same alias, the local box returned 503 "This service is starting." Before the change it served the alias itself. - **P2-2** (fixed-box byte-identity / single-hop), `edge.go:2021-2039`: when a local catch-all meets another box's exact name, three fixed-box answers change. A signed hop now gets a stale-hop refusal, a door call gets 404, and a failed backhaul gets 503 instead of the local answer. This applies on boxes with no admission fields. The comment at `edge.go:2041-2044` now describes a case that can no longer happen. - **P2-3** (name ownership vs dial eligibility, "do not infer an empty namespace"), `internal/edgesfile/nameauthority.go:70`: a closed catch-all reserves nothing for its child names. With no other catch-all, a child resolves as unknown host instead of 503 + Retry-After. - **P2-4** (census maintainability): `TestGroupNameClassCensus` hashes entire producer files, including all of `edge.go`. Any unrelated edit to those files on main or another branch will break the test at merge. - **P3-1:** the readiness snapshot is never given a list of known readers in production, even though a fixed-box roster exists. Task 3/8 must supply it. - **P3-2:** any box label starting `g-` counts as a group, not just the 22-character group reference. An operator-named fixed box like `g-web` would block its fleet's updates. - **P3-3:** every request on a local alias or catch-all now runs the name resolver. The cost is small but sits on the request path. - **P3-4:** `resolveHomeName` keeps a fallback that builds claims for snapshots assembled by hand, which is a second reading of the held bit. - **P3-5:** the refusal log line blames "group reader capability" even on fleets with no groups. Leave it for the copy pass. Two items need your call: - The bullet-6 deployment-command pieces are not in this diff and the report defers them to Task 3/8: the console `X-Carlos-Version` check, the inventory of readers that don't publish, and serialising release/rollback with the experiment record. Please confirm who owns them. - The maintenance re-admission and CONTINUE call sites don't exist yet (Task 3), so I couldn't verify those. The full review is at `/home/paulca/amadan.net/carlos/platform/.claude/worktrees/region-ha-p3b-build/.superpowers/sdd/2026-11-04-region-ha-p3b-group/task-1-review-r1.md`.</result> <usage><subagent_tokens>164363</subagent_tokens><tool_uses>40</tool_uses><duration_ms>528427</duration_ms></usage> </task-notification>

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

diff --git a/internal/edge/edge.go b/internal/edge/edge.go
index 1268e0d72..e667fa15f 100644
--- a/internal/edge/edge.go
+++ b/internal/edge/edge.go
@@ -2009,7 +2009,7 @@ func (e *Edge) ServeHTTP(w http.ResponseWriter, r *http.Request) {
class = edgesfile.NameAlias
}
local := edgesfile.NameClaim{Name: name, Class: class, Account: registry.EffectiveAccount(up.route.Account), App: up.route.App,
- Incarnation: up.route.Incarnation, ServingSeq: up.route.ServingSeq, Eligible: true, Local: true}
+ Stamp: int64(up.route.ClaimStamp), Incarnation: up.route.Incarnation, ServingSeq: up.route.ServingSeq, Eligible: true, Local: true}
if class == edgesfile.NameAlias {
local.TargetHost = up.route.Host
}
@@ -2018,7 +2018,7 @@ func (e *Edge) ServeHTTP(w http.ResponseWriter, r *http.Request) {
AdmissionResponse(w, r)
return
}
- if resolved.State == edgesfile.NameDialable && !resolved.Serving.Local {
+ if resolved.State == edgesfile.NameDialable && !resolved.Serving.Local && (resolved.AdmissionAware || (!hopped && !isDoor)) {
if hopped {
e.homes.Load().staleHopRefusal(w, host)
return
@@ -2032,15 +2032,15 @@ func (e *Edge) ServeHTTP(w http.ResponseWriter, r *http.Request) {
}
// A known remote owner must not fall through to another local app
// when its mesh key or transport is unavailable.
- AdmissionResponse(w, r)
- return
+ if resolved.AdmissionAware {
+ AdmissionResponse(w, r)
+ return
+ }
}
}
- // A regional deny entry the gate let through to the exact-home arm above
- // (a star match whose exact name another box served) that the arm did
- // not answer: no mesh key, or the map moved between the two reads. The
- // entry has no proxy; it is refused, never served.
+ // A regional deny entry has no local proxy. Refuse it if the legacy
+ // exact-home arm kept the local answer (hop, door, or no mesh key).
if ok && up.regional == regionalDeny {
e.regionalRefuse(w, up, "no bound target on this box")
return
diff --git a/internal/edge/group_names_test.go b/internal/edge/group_names_test.go
index e1ee44b2f..dfe7e6003 100644
--- a/internal/edge/group_names_test.go
+++ b/internal/edge/group_names_test.go
@@ -1,7 +1,10 @@
package edge
import (
+ "context"
"encoding/json"
+ "fmt"
+ "net"
"net/http"
"net/http/httptest"
"slices"
@@ -14,6 +17,130 @@ import (
"github.com/carlosframework/platform/internal/release"
)
+func TestGroupNamesLegacyLocalAnswers(t *testing.T) {
+ for _, tc := range []string{"alias-stamp", "alias-lifetime", "alias-admission-stamp", "alias-admission-lifetime", "catchall-hop", "catchall-door", "catchall-no-key", "catchall-backhaul"} {
+ t.Run(tc, func(t *testing.T) {
+ reg := openReg(t)
+ app := e2eApp(t, "local")
+ primary := "*.example.com"
+ alias := strings.HasPrefix(tc, "alias")
+ if alias {
+ primary = "shop.b.example.net"
+ }
+ if err := reg.Upsert(registry.Route{Host: primary, Account: "abc", App: "shop", Kind: "service", Status: "ready", Addr: app.Listener.Addr().String(), Incarnation: 1, ServingSeq: 1}); err != nil {
+ t.Fatal(err)
+ }
+ if tc == "alias-admission-stamp" {
+ rt, err := reg.Get(primary)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := reg.AdoptClaimRoute(t.Context(), *rt, registry.ClaimOwnership{ClaimIncarnation: "one", ClaimStamp: 7, ClaimOwner: "local", ClaimRowID: "one"}); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if alias {
+ if err := reg.UpsertAlias(registry.RouteAlias{Alias: "tickets.example.com", Host: primary, Account: "abc", App: "shop", DNSStatus: "pointing"}); err != nil {
+ t.Fatal(err)
+ }
+ }
+ e, err := New(reg, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(e.probers.Stop)
+ peer := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { _, _ = w.Write([]byte("peer")) }))
+ defer peer.Close()
+ s := release.NewDirStore(t.TempDir())
+ host := "tickets.example.com"
+ row := map[string]any{"role": "home", "alias": alias, "account": "abc", "app": "shop"}
+ if alias {
+ row["target_host"] = primary
+ }
+ if tc == "alias-stamp" || tc == "alias-admission-stamp" {
+ row["stamp"] = 5
+ }
+ if tc == "alias-lifetime" {
+ row["incarnation"], row["serving_seq"] = 2, 1
+ }
+ if tc == "alias-admission-lifetime" {
+ row["incarnation"], row["serving_seq"] = 1, 0
+ }
+ body, _ := json.Marshal(map[string]any{"v": 1, "box": "peer", "eip": "192.0.2.2", "hosts": map[string]any{host: row}})
+ if strings.Contains(tc, "admission") {
+ body = append([]byte(`{"box_role":"serve","admitted":true,"drained":false,`), body[1:]...)
+ }
+ putJSON(t, s, edgesfile.Key("peer"), string(body))
+ m := newHomeMap(s, "local")
+ refreshHomeMap(t, m)
+ e.homes.Store(m)
+ req := httptest.NewRequest(http.MethodGet, "https://"+host+"/", nil)
+ key := []byte("group-name-test-key-32-bytes-long!")
+ if tc == "catchall-hop" {
+ m.keyCurrent = key
+ req.Header.Set(hopHeader, "1")
+ req.Header.Set(hopAuthHeader, signHop(key, host, time.Now()))
+ }
+ if tc == "catchall-door" {
+ req = req.WithContext(context.WithValue(req.Context(), doorCallerKey{}, doorCaller{Account: "abc", App: "shop"}))
+ }
+ if tc == "catchall-backhaul" {
+ m.keyCurrent = key
+ tr := peer.Client().Transport.(*http.Transport).Clone()
+ tr.DialContext = func(ctx context.Context, network, _ string) (net.Conn, error) {
+ return (&net.Dialer{}).DialContext(ctx, network, peer.Listener.Addr().String())
+ }
+ e.backhaulTransports.Store("192.0.2.2", tr)
+ t.Cleanup(tr.CloseIdleConnections)
+ }
+ w := httptest.NewRecorder()
+ e.ServeHTTP(w, req)
+ want := "local|"
+ if tc == "catchall-backhaul" {
+ want = "peer"
+ }
+ if w.Code != 200 || !strings.HasPrefix(w.Body.String(), want) {
+ t.Fatalf("legacy response = %d %q, want %s", w.Code, w.Body.String(), want)
+ }
+ })
+ }
+}
+
+func TestGroupNamesClosedCatchallChildren(t *testing.T) {
+ for _, alias := range []bool{false, true} {
+ t.Run(fmt.Sprint(alias), func(t *testing.T) {
+ e, err := New(openReg(t), nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(e.probers.Stop)
+ s := release.NewDirStore(t.TempDir())
+ body, _ := json.Marshal(map[string]any{"v": 1, "box": "closed", "eip": "192.0.2.1", "box_role": "booting", "admitted": false, "drained": false, "hosts": map[string]any{"*.example.com": map[string]any{"role": "home", "alias": alias, "wildcard": true, "account": "a", "app": "shop", "target_host": "shop.a.test"}}})
+ putJSON(t, s, edgesfile.Key("closed"), string(body))
+ m := newHomeMap(s, "local")
+ refreshHomeMap(t, m)
+ e.homes.Store(m)
+ if got := m.resolveName("new.example.com", nil, false); got.State != edgesfile.NameHeld {
+ t.Errorf("child = %+v, want held", got)
+ }
+ if _, _, _, _, ok := m.Owner("new.example.com"); ok {
+ t.Error("closed child has dial owner")
+ }
+ w := httptest.NewRecorder()
+ w.Header().Set(holderHeader, "old")
+ e.ServeHTTP(w, httptest.NewRequest(http.MethodGet, "https://new.example.com/", nil))
+ if w.Code != 503 || w.Header().Get("Retry-After") != "10" || w.Header().Get(holderHeader) != "" {
+ t.Errorf("child response = %d %v", w.Code, w.Header())
+ }
+ putJSON(t, s, edgesfile.Key("exact"), `{"v":1,"box":"exact","eip":"192.0.2.2","hosts":{"new.example.com":{"role":"home","account":"b","app":"shop"}}}`)
+ refreshHomeMap(t, m)
+ if got := m.resolveName("new.example.com", nil, false); got.State != edgesfile.NameDialable || got.Serving.Box != "exact" {
+ t.Errorf("exact did not win: %+v", got)
+ }
+ })
+ }
+}
+
func TestGroupNamesBeforeAdmission(t *testing.T) {
for _, tc := range []struct {
name, key, role string
diff --git a/internal/edge/group_readers.go b/internal/edge/group_readers.go
index b040c9fbd..097897ba0 100644
--- a/internal/edge/group_readers.go
+++ b/internal/edge/group_readers.go
@@ -13,7 +13,7 @@ func (e *Edge) GroupReaderSnapshot() edgesfile.ReaderSnapshot {
return edgesfile.ReaderSnapshot{}
}
s := m.snapshot()
- out := edgesfile.ReaderSnapshot{Self: m.self, Complete: s.readerComplete, CheckedAt: s.readerCheckedAt}
+ out := edgesfile.ReaderSnapshot{Self: m.self, Complete: s.readerComplete, CheckedAt: s.readerCheckedAt, GroupObserved: s.groupObserved}
for key, f := range s.files {
p := edgesfile.PlacementView{Key: key, Box: f.Box, Region: f.Region, Placement: f.Placement, AdmissionFields: f.AdmissionFields}
if key != edgesfile.Key(f.Box) {
diff --git a/internal/edge/group_readers_test.go b/internal/edge/group_readers_test.go
index 90bcb4202..b0e869e7d 100644
--- a/internal/edge/group_readers_test.go
+++ b/internal/edge/group_readers_test.go
@@ -15,6 +15,7 @@ type groupReaderStore struct {
release.Store
badList, badGet bool
reads int
+ missingKey string
}
func (s *groupReaderStore) List(ctx context.Context, key string) ([]string, error) {
@@ -26,7 +27,7 @@ func (s *groupReaderStore) List(ctx context.Context, key string) ([]string, erro
}
func (s *groupReaderStore) Get(ctx context.Context, key string) ([]byte, string, error) {
s.reads++
- if s.badGet && key == edgesfile.Key("peer") {
+ if s.badGet && key == edgesfile.Key("peer") || key == s.missingKey {
return nil, "", os.ErrNotExist
}
return s.Store.Get(ctx, key)
@@ -93,3 +94,43 @@ func TestGroupReadersReadyCachedFold(t *testing.T) {
t.Fatal("known listed publisher missing its file admitted")
}
}
+
+func TestGroupReadersObservedAcrossFailedFolds(t *testing.T) {
+ for _, tc := range []string{"parsed", "corrupt-first-read", "missing-first-read", "box-field"} {
+ t.Run(tc, func(t *testing.T) {
+ s := &groupReaderStore{Store: release.NewDirStore(t.TempDir())}
+ ref := "g-0123456789abcdef0123"
+ key := edgesfile.Key(ref)
+ body := []byte(`{"v":1,"box":"` + ref + `","hosts":{}}`)
+ if tc == "corrupt-first-read" {
+ body = []byte(`{"v":`)
+ }
+ if tc == "box-field" {
+ key = edgesfile.Key("peer")
+ }
+ if _, err := s.Put(t.Context(), key, body, ""); err != nil {
+ t.Fatal(err)
+ }
+ if tc == "missing-first-read" {
+ s.missingKey = key
+ }
+ m := newHomeMap(s, "self")
+ e := &Edge{}
+ e.homes.Store(m)
+ _ = m.Refresh(t.Context())
+ if !e.GroupReaderSnapshot().GroupObserved {
+ t.Fatal("group observation lost")
+ }
+ if err := s.Delete(t.Context(), key); err != nil {
+ t.Fatal(err)
+ }
+ _ = m.Refresh(t.Context())
+ s.badList = true
+ _ = m.Refresh(t.Context())
+ snap := e.GroupReaderSnapshot()
+ if !snap.GroupObserved || snap.Complete || len(snap.Files) != 0 {
+ t.Fatalf("history after incomplete empty fold: %+v", snap)
+ }
+ })
+ }
+}
diff --git a/internal/edge/homemap.go b/internal/edge/homemap.go
index 8ae3dca3b..3730c65f9 100644
--- a/internal/edge/homemap.go
+++ b/internal/edge/homemap.go
@@ -271,6 +271,7 @@ type homeEntry struct {
// homeSnapshot is one poll's result, swapped in whole and immutable once
// published, so a reader holds no lock past the pointer read.
type homeSnapshot struct {
+ groupObserved bool
departureComplete bool
readerCheckedAt time.Time
readerComplete bool
@@ -510,6 +511,17 @@ func (m *homeMap) clock() time.Time {
return time.Now()
}
+func (m *homeMap) noteGroupPublisher() {
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ next := *m.snap
+ next.groupObserved = true
+ // A prior complete absence must not look like retirement evidence while
+ // this refresh is still reading the newly observed publisher.
+ next.readerComplete = false
+ m.snap = &next
+}
+
// refreshHosts rebuilds the whole map from one list plus a get per key — no
// delta cleverness, for certMirror.Refresh's reason: a full rebuild is what
// makes a RETIRED box's hosts actually leave the map.
@@ -546,6 +558,9 @@ func (m *homeMap) refreshHosts(ctx context.Context) error {
continue
}
tried++
+ if edgesfile.IsGroupReference(strings.TrimSuffix(name, ".json")) {
+ m.noteGroupPublisher()
+ }
body, etag, err := m.s.Get(ctx, key)
if errors.Is(err, os.ErrNotExist) {
// Routing can drop a concurrently deleted row. The reader gate
@@ -564,6 +579,9 @@ func (m *homeMap) refreshHosts(ctx context.Context) error {
err = perr
} else {
f.etag = etag
+ if edgesfile.IsGroupReference(f.Box) {
+ m.noteGroupPublisher()
+ }
next[key] = f
continue
}
@@ -591,7 +609,7 @@ func (m *homeMap) refreshHosts(ctx context.Context) error {
// deterministic; say so once a refresh.
log.Printf("edge: home map: %d host(s) published by two boxes at the same installation stamp, e.g. %s", len(tied), tied[0])
}
- snap := &homeSnapshot{files: next, hosts: hosts, read: true, departureComplete: failed == 0, readerComplete: failed == 0 && !readerMissing}
+ snap := &homeSnapshot{groupObserved: m.snapshot().groupObserved, files: next, hosts: hosts, read: true, departureComplete: failed == 0, readerComplete: failed == 0 && !readerMissing}
m.mu.Lock()
m.snap = snap
wake := m.hostsWake
@@ -874,7 +892,8 @@ func foldHomes(files map[string]edgesFileView, self string, privateDial bool) (m
role = edgeRoleWildcard
}
c := edgesfile.NameClaim{Source: k, Name: host, Class: edgesfile.NameClassOf(role, h.Alias), Account: h.Account, App: h.App,
- TargetHost: h.TargetHost, Stamp: h.Stamp, Incarnation: h.Incarnation, ServingSeq: h.ServingSeq,
+ AdmissionAware: len(f.BoxRole) > 0 || len(f.Admitted) > 0 || len(f.Drained) > 0,
+ TargetHost: h.TargetHost, Stamp: h.Stamp, Incarnation: h.Incarnation, ServingSeq: h.ServingSeq,
Eligible: h.Role == edgeRoleHome && f.HomeEligible() && addr != "", Dial: addr, Box: f.Box}
claims[host] = append(claims[host], c)
if entries[host] == nil {
@@ -1088,7 +1107,15 @@ func (m *homeMap) lookupHome(host string) (homeEntry, bool) {
func (m *homeMap) resolveName(host string, local []edgesfile.NameClaim, exact bool) edgesfile.NameResolution {
var hosts map[string]homeEntry
if m != nil && m.self != "" {
- hosts = m.snapshot().hosts
+ snap := m.snapshot()
+ hosts = snap.hosts
+ own := snap.files[edgesfile.Key(m.self)]
+ if len(own.BoxRole) > 0 || len(own.Admitted) > 0 || len(own.Drained) > 0 {
+ local = slices.Clone(local)
+ for i := range local {
+ local[i].AdmissionAware = true
+ }
+ }
}
return resolveHomeName(host, local, exact, hosts)
}
@@ -1098,18 +1125,7 @@ func resolveHomeName(host string, local []edgesfile.NameClaim, exact bool, hosts
if hosts != nil {
add := func(name string) {
if h, ok := hosts[name]; ok {
- if len(h.claims) > 0 {
- peers = append(peers, h.claims...)
- return
- }
- // Some callers assemble an immutable snapshot directly.
- class := edgesfile.NameCertificate
- if h.dial {
- class = edgesfile.NameClassOf(edgeRoleHome, h.alias)
- }
- peers = append(peers, edgesfile.NameClaim{Name: name, Class: class, Account: h.account, App: h.app,
- TargetHost: h.targetHost, Stamp: h.stamp, Incarnation: h.incarnation, ServingSeq: h.servingSeq,
- Eligible: h.dial, Dial: h.eip, Box: h.box})
+ peers = append(peers, h.claims...)
}
}
add(host)
diff --git a/internal/edgesfile/nameauthority.go b/internal/edgesfile/nameauthority.go
index 17073c1f0..098a05e56 100644
--- a/internal/edgesfile/nameauthority.go
+++ b/internal/edgesfile/nameauthority.go
@@ -28,15 +28,17 @@ type NameClaim struct {
Stamp int64
Incarnation, ServingSeq uint64
Eligible bool
+ AdmissionAware bool
Local bool
Dial, Box string
}
type NameResolution struct {
- State NameState
- RouteExists bool
- Authority NameClaim
- Serving NameClaim
+ State NameState
+ RouteExists bool
+ AdmissionAware bool
+ Authority NameClaim
+ Serving NameClaim
}
func (c NameClaim) order() DialOrder {
@@ -55,9 +57,11 @@ func NameClassOf(role string, alias bool) NameClass {
}
// ResolveNameAuthority first chooses ownership, then a serving claim of that
-// owner and target. A closed wildcard cannot reserve a new concrete name.
+// owner and target. A closed wildcard yields to an eligible catch-all, but
+// retains its children when no serving catch-all claims them.
func ResolveNameAuthority(name string, local []NameClaim, peers []NameClaim) NameResolution {
var exact, fallback []NameClaim
+ aware := false
wildcard := ""
if i := strings.IndexByte(name, '.'); i > 0 {
wildcard = "*" + name[i:]
@@ -69,14 +73,25 @@ func ResolveNameAuthority(name string, local []NameClaim, peers []NameClaim) Nam
}
if c.Name == name {
exact = append(exact, c)
- } else if c.Name == wildcard && c.Eligible {
+ aware = aware || c.AdmissionAware
+ } else if c.Name == wildcard {
fallback = append(fallback, c)
+ aware = aware || c.AdmissionAware
}
}
}
claims := exact
if len(claims) == 0 {
claims = fallback
+ var eligible []NameClaim
+ for _, c := range fallback {
+ if c.Eligible {
+ eligible = append(eligible, c)
+ }
+ }
+ if len(eligible) > 0 {
+ claims = eligible
+ }
// A concrete name already served by a local catch-all keeps that
// answer. Peer wildcards only supply a fallback when local has none.
for _, c := range fallback {
@@ -89,18 +104,29 @@ func ResolveNameAuthority(name string, local []NameClaim, peers []NameClaim) Nam
if len(claims) == 0 {
return NameResolution{}
}
+ out := NameResolution{State: NameHeld, AdmissionAware: aware}
+ for _, c := range claims {
+ if c.Class == NameRoute {
+ out.RouteExists = true
+ }
+ }
+ // Legacy boxes always serve their own exact aliases, including during
+ // move overlap. Admission-aware ownership is the only new override.
+ if !aware {
+ for _, c := range exact {
+ if c.Local && c.Eligible && c.Class == NameAlias {
+ out.State, out.Authority, out.Serving = NameDialable, c, c
+ return out
+ }
+ }
+ }
owner := claims[0]
for _, c := range claims[1:] {
if DialBeats(c.order(), owner.order()) {
owner = c
}
}
- out := NameResolution{State: NameHeld, Authority: owner}
- for _, c := range claims {
- if c.Class == NameRoute {
- out.RouteExists = true
- }
- }
+ out.Authority = owner
same := func(c NameClaim) bool {
return c.Name == owner.Name && c.Class == owner.Class && c.Account != "" && c.App != "" &&
c.Account == owner.Account && c.App == owner.App && c.TargetHost == owner.TargetHost
diff --git a/internal/edgesfile/snapshot.go b/internal/edgesfile/snapshot.go
index f022b9f09..e721b32a7 100644
--- a/internal/edgesfile/snapshot.go
+++ b/internal/edgesfile/snapshot.go
@@ -316,11 +316,15 @@ const NamesCapability = "names-2"
// from the serialized deployment preflight; new unpublished group launches are
// excluded from that inventory only after their launch digest is verified.
type ReaderSnapshot struct {
- Self string
- Files []PlacementView
- KnownReaders []string
- Complete bool
- CheckedAt time.Time
+ // GroupObserved is latched in agent-owned memory by the deployment fold.
+ // It survives failed reads and disappearance; only a complete retirement
+ // readback permits an old target afterwards. It is never root authority.
+ GroupObserved bool
+ Self string
+ Files []PlacementView
+ KnownReaders []string
+ Complete bool
+ CheckedAt time.Time
}
func (s ReaderSnapshot) Fresh(now time.Time) bool {
@@ -372,18 +376,30 @@ func GroupReadersReady(s ReaderSnapshot, self string, now time.Time) bool {
}
// HasGroupNamespace includes empty booting publishers and retained names in
-// undialable, draining, or silent files. g- is reserved by the box reference
-// protocol; malformed group references are conservatively included too.
+// undialable, draining, or silent files. Fixed labels may also start with g-.
func (s ReaderSnapshot) HasGroupNamespace() bool {
for _, f := range s.Files {
- if strings.HasPrefix(f.Box, "g-") || strings.HasPrefix(strings.TrimPrefix(f.Key, Prefix), "g-") {
+ if IsGroupReference(f.Box) || IsGroupReference(strings.TrimSuffix(strings.TrimPrefix(f.Key, Prefix), ".json")) {
return true
}
}
for _, ref := range s.KnownReaders {
- if strings.HasPrefix(ref, "g-") {
+ if IsGroupReference(ref) {
return true
}
}
return false
}
+
+// IsGroupReference matches groupReferenceOf's g- plus twenty lowercase hex digits.
+func IsGroupReference(ref string) bool {
+ if len(ref) != 22 || !strings.HasPrefix(ref, "g-") {
+ return false
+ }
+ for _, c := range ref[2:] {
+ if !(c >= '0' && c <= '9' || c >= 'a' && c <= 'f') {
+ return false
+ }
+ }
+ return true
+}
diff --git a/internal/host/group_names_test.go b/internal/host/group_names_test.go
index 83f5344b3..27875162a 100644
--- a/internal/host/group_names_test.go
+++ b/internal/host/group_names_test.go
@@ -1,10 +1,12 @@
package host
import (
+ "bytes"
"crypto/sha256"
"encoding/json"
"fmt"
"go/ast"
+ "go/format"
"go/parser"
"go/token"
"os"
@@ -218,8 +220,7 @@ func TestGroupNameClassCensus(t *testing.T) {
if len(got) != len(required) {
t.Errorf("class inventory: %v", got)
}
- // Discover registry name writers, including newly added source files.
- // A new producer cannot avoid the inventory by moving to another file.
+ seen := map[string]bool{}
for _, dir := range []string{".", "../domains", "../provision", "../edge"} {
files, err := os.ReadDir(dir)
if err != nil {
@@ -234,40 +235,18 @@ func TestGroupNameClassCensus(t *testing.T) {
if err != nil {
t.Fatal(err)
}
- parsed, err := parser.ParseFile(token.NewFileSet(), path, body, 0)
- if err != nil {
- t.Fatal(err)
- }
- produces := false
- ast.Inspect(parsed, func(n ast.Node) bool {
- call, ok := n.(*ast.CallExpr)
- if !ok {
- return true
- }
- sel, ok := call.Fun.(*ast.SelectorExpr)
- if !ok {
- return true
- }
- switch sel.Sel.Name {
- case "Upsert", "UpsertAlias", "UpsertPath", "UpsertWildcardDomain":
- produces = true
- }
- return true
- })
- if produces {
- if _, ok := groupNameProducerInventory[path]; !ok {
- t.Errorf("unlisted producer %s %x: add its name-class consequence and inventory row", path, sha256.Sum256(body))
+ for name, hash := range groupNameProducers(t, body) {
+ key := path + ":" + name
+ seen[key] = true
+ if want := groupNameProducerInventory[key]; want != hash {
+ t.Errorf("producer %q: %q, inventory its name-class consequence", key, hash)
}
}
}
}
- for path, want := range groupNameProducerInventory {
- body, err := os.ReadFile(path)
- if err != nil {
- t.Fatal(err)
- }
- if hash := fmt.Sprintf("%x", sha256.Sum256(body)); hash != want {
- t.Errorf("producer %s changed (%s): inventory every name derivation and add its consequence row", path, hash)
+ for key := range groupNameProducerInventory {
+ if !seen[key] {
+ t.Errorf("removed producer %s: update inventory", key)
}
}
for _, schema := range []struct {
@@ -281,6 +260,8 @@ func TestGroupNameClassCensus(t *testing.T) {
{registry.RouteAlias{}, "Alias Host Account App DNSStatus DNSCheckedAt CertExpiresAt CreatedAt"},
{registry.RoutePath{}, "Host Prefix Target Account App"},
{registry.WildcardDomain{}, "Host Account App CreatedAt"},
+ {registry.RegionalDomain{}, "Host Target Account App Region CreatedAt"},
+ {edgesfile.NameClaim{}, "Source Name Class Account App TargetHost Stamp Incarnation ServingSeq Eligible AdmissionAware Local Dial Box"},
} {
typ := reflect.TypeOf(schema.value)
var fields []string
@@ -293,13 +274,119 @@ func TestGroupNameClassCensus(t *testing.T) {
}
}
+// Discover name writers and direct name construction, including new files.
+// Hash each producer function, without comments or unrelated declarations.
+func groupNameProducers(t *testing.T, body []byte) map[string]string {
+ t.Helper()
+ fs := token.NewFileSet()
+ parsed, err := parser.ParseFile(fs, "producer.go", body, 0)
+ if err != nil {
+ t.Fatal(err)
+ }
+ out := map[string]string{}
+ for _, decl := range parsed.Decls {
+ fn, ok := decl.(*ast.FuncDecl)
+ if !ok || fn.Body == nil {
+ continue
+ }
+ produces := fn.Name.Name == "PlatformAliasFold" || fn.Name.Name == "deriveInstanceAliases" || fn.Name.Name == "deriveRegional"
+ ast.Inspect(fn.Body, func(n ast.Node) bool {
+ switch n := n.(type) {
+ case *ast.CallExpr:
+ if sel, ok := n.Fun.(*ast.SelectorExpr); ok {
+ switch sel.Sel.Name {
+ case "Upsert", "UpsertAlias", "UpsertPath", "UpsertWildcardDomain", "UpsertRegionalDomain":
+ produces = true
+ }
+ }
+ case *ast.CompositeLit:
+ var name string
+ switch typ := n.Type.(type) {
+ case *ast.Ident:
+ name = typ.Name
+ case *ast.SelectorExpr:
+ name = typ.Sel.Name
+ }
+ switch name {
+ case "Route", "RouteAlias", "RoutePath", "WildcardDomain", "RegionalDomain", "edgeHost", "upstream":
+ if len(n.Elts) > 0 {
+ produces = true
+ }
+ }
+ }
+ return true
+ })
+ if !produces {
+ continue
+ }
+ var normalized bytes.Buffer
+ if err := format.Node(&normalized, fs, fn); err != nil {
+ t.Fatal(err)
+ }
+ name := fn.Name.Name
+ if fn.Recv != nil {
+ var recv bytes.Buffer
+ if err := format.Node(&recv, fs, fn.Recv.List[0].Type); err != nil {
+ t.Fatal(err)
+ }
+ name = recv.String() + "." + name
+ }
+ out[name] = fmt.Sprintf("%x", sha256.Sum256(normalized.Bytes()))
+ }
+ return out
+}
+
+func TestGroupNameProducerCensusScope(t *testing.T) {
+ base := []byte(`package fixture
+func produce(r Registry) { r.Upsert(Route{Host: "one"}) }
+func unrelated() { println("before") }
+`)
+ original := groupNameProducers(t, base)
+ unrelated := groupNameProducers(t, bytes.ReplaceAll(base, []byte("before"), []byte("after")))
+ if !reflect.DeepEqual(original, unrelated) {
+ t.Error("unrelated function changed producer inventory")
+ }
+ changed := groupNameProducers(t, bytes.ReplaceAll(base, []byte("one"), []byte("two")))
+ if reflect.DeepEqual(original, changed) {
+ t.Error("changed name derivation escaped inventory")
+ }
+ added := groupNameProducers(t, append(base, []byte(`func another(r Registry) { r.UpsertAlias(RouteAlias{Alias: "new"}) }`)...))
+ if len(added) != len(original)+1 {
+ t.Error("new name producer escaped inventory")
+ }
+}
+
var groupNameProducerInventory = map[string]string{
- "../provision/sidecar_reconcile.go": "f6260269532e84fe27acf8c7bde6d7aaa6b463b2f978e9c315609e569fbff636",
- "rootinventory.go": "d5f00f6c9a01049ff4a91342a8dfb253e90a186cfbd57bd02a84f2e2e8bfcf51",
- "edgesfile.go": "ce5543790e9df9019fa65457822210adff1dc1b2c6b9fd0084a1d7d4f75998eb",
- "../domains/aliases.go": "ce4e04b06bb9fa0685b5f912a756178ed10e5763cfafd4843daf0b6d5702ef90",
- "../domains/reconcile.go": "3c0ba9ccb35b7d7623896f69b225aeecde8154845bad99a301a1186793b78a7e",
- "../provision/reconcile.go": "7df62fbd5589e02bd316d772c006a6543ad8ff84db349a8abb4687bdd745321b",
- "../edge/edge.go": "f5fee9844b67382fcb1e5efe2a56e2a52a34ba9516b0f80f182ae4a3c09c8d42",
- "../edge/platformalias.go": "a1124d267bd53bbf9c64f7f12dc2a5923d5e32276b2551a0001a054f84f6c1db",
+ "../domains/aliases.go:ReconcileAliasesReport": "c022beb479d23f0be5f0cb1c591daf9f479507bb7acd2fb9262c1392357c0c61",
+ "../domains/aliases.go:deriveInstanceAliases": "47b40b392927d9c50cab6c350083af24565e4e148cd1b5ddc257e9803153c0c2",
+ "../domains/aliases.go:deriveRegional": "79fd7c432e6b0a9ffd945312851e52af2c450769416ef44ff9a4bea681b44cde",
+ "../domains/reconcile.go:Reconcile": "8b2848535d0a15117d578ac28c7486997c6ad8960b58b6dca5d4b35cde14eed0",
+ "../domains/reconcile.go:mintedRoute": "dbd2211f62fc606661c6d8258ecfbf18f0b3c865e775522c5b363d01c442fca9",
+ "../edge/assetcatch.go:*Edge.AssetOwners": "2b9ce5620a6defa16f12cb38d389ac59aa594049d37d84746f0a76419ab05b5f",
+ "../edge/assetcatch.go:*Edge.serveAssetFar": "7d358ec272ae74c05764504550bad461096a09d0bfcc108dcbe5485f8f68d643",
+ "../edge/edge.go:*Edge.Reload": "f2877c1f1eb8344c4f4a5ddd84a01f36960d2269837f5eedd61edf9affd12ff7",
+ "../edge/platformalias.go:PlatformAliasFold": "a18e4963cf88320ef3fb94b666b02838dc12cc3e9b2df3f2cbe2576ca682735f",
+ "../edge/regional.go:*Edge.foldRegional": "b413fad6a8e17530ce0e99c79c521e0a6782b82c04d61d256442b8defe6a427b",
+ "../provision/forward.go:forwardRowFor": "cefd4d7016afe1725f7a25dfb81aa7a2e6a2a06057e94e8f236b85e9a42f601d",
+ "../provision/reconcile.go:Reconcile": "5aa887831c7029eab5ca974eb37cedb4536d09a38ea3de2f0dc88d1e3a2c19b9",
+ "../provision/reconcile.go:RouteFor": "ed78b348dc5b1b1afa6e6df1de0643808402472d455592c39ec19e6fbb059c64",
+ "../provision/reconcile.go:mintHeld": "9fe4ad876c727af36cc06bd0105baf344748c61e6f21ced48e5288a323851344",
+ "../provision/seedreconcile.go:purgeAbortedFromLocal": "889e93e6fbd74adf614ba184bcd2f554196eccc4506829c65326a3502e98d89a",
+ "../provision/seedrollback.go:removeOrphanedLocal": "6dd05836ac1d346de23ad555d50bb6c8fcd574cf05b6dfbf916eb0b220d88586",
+ "../provision/sidecar_reconcile.go:ReconcileSidecars": "6dd1733236c4b2e2114f895b3f0c59cb4d6216d70dd43390a33cab637f887539",
+ "../provision/sidecar_reconcile.go:sidecarRouteFor": "71f4f6298081b670a1bc6bfcb1f3f92cc1ceffc0960714caa0743b9519de0b13",
+ "claimretire_transport.go:ClaimRootHTTP.retire": "a60c74d0e0461e0a432f9a338aa25799cc0cd9d163c7b6eb803cfb33d55d7c2a",
+ "claimunit_binding.go:claimUnitShape.route": "f38fd6e10aba680354ee908c255fd34e731fe2d1a22fffd41ac449e8b763dd2c",
+ "claimunit_policy.go:claimUnitShapeCheck": "45f16830e5ed834995ca573a710f1e390a504b7eb78c3c0465ac70e7f306e50c",
+ "claimunit_policy.go:rootClaimRestartShape": "1d0370516c32482b1784f4bd4ab0deb042c31120d81f4dc8c417f52b24ef76ac",
+ "edgesfile.go:edgesFileWriteClaims": "3c3e7252b87e5dc7eb9b2fd7bd7cf757874be7fe4be0f17943495b45c35f5450",
+ "movesheldenv.go:composeHeldEnv": "17ad3714758d1c07a71375734c125496855a16ca800eb814bde58283d3a5318b",
+ "movesheldrelease_root.go:heldReleaseRoute": "10bf824edc963319a38a47b91877b865977b1dc4a27c6e7680c46704289a7df7",
+ "movesstage.go:heldReleasePublished": "edad51c04a01657b77a9fc469404db5fde51cff1f2c61e243d6a717fb6224e85",
+ "movesstage.go:heldReleaseReady": "dc3808a59841b680980d9f664253fa62f064bb4af52fe4ba28ca3cf52bab2719",
+ "movesstage.go:heldReleaseStaged": "f83db93e5a81919ba93e4bb69b78008d54b4b28f7ee233e279dfb4086cf60c1d",
+ "rootinventory.go:ClaimRootHTTP.commitRootInventoryPending": "29f5c33f94232cc950bdaa95d3b37867382be11d242ad3085bed808490ca6bca",
+ "rootrecord_claim.go:rootClaimRecord": "e7f73adcaa45e4dfefc5743f43e9ab83567ac95a74ae0557e789478a58e64da4",
+ "rootroute.go:rootRecordRoute": "765c71d7baeb75901a8af796fe909841ca9e0b700febf9a62305f909fd821dd6",
+ "steering_loop.go:steeredRoutesFromRecords": "166200e4058e42ca94727f44cab1db003543b3391544f7b4ca8d26b596f63e16",
}
diff --git a/internal/host/systemleg.go b/internal/host/systemleg.go
index b035d82f1..6abbc9c94 100644
--- a/internal/host/systemleg.go
+++ b/internal/host/systemleg.go
@@ -42,6 +42,7 @@ type systemLeg struct {
readers func() edgesfile.ReaderSnapshot
namesRelease namesReleasePin
readerRefusedAt time.Time
+ groupObserved bool
pending *systemPending
// backoff is ONE retry ladder for everything that can go wrong after the
// deadline — an unreachable store on the fetch, an unwritable /data on
@@ -329,10 +330,15 @@ var firstNames2Release = namesReleasePin{}
func (l *systemLeg) groupReaderTargetAllowed(p *systemPending, now time.Time) bool {
s := l.readers()
+ hasGroup := s.HasGroupNamespace()
+ l.groupObserved = l.groupObserved || s.GroupObserved || hasGroup
+ if !l.groupObserved {
+ return true
+ }
if !s.Fresh(now) {
return false
}
- if !s.HasGroupNamespace() {
+ if !hasGroup {
return true
}
floor, pinned := release.ParseReleaseVersion(l.namesRelease.FirstRelease)
diff --git a/internal/host/systemleg_test.go b/internal/host/systemleg_test.go
index 7629b8f6e..5b287ed27 100644
--- a/internal/host/systemleg_test.go
+++ b/internal/host/systemleg_test.go
@@ -393,6 +393,79 @@ func TestSystemLegGroupReaderRollback(t *testing.T) {
}
}
+func TestSystemLegGroupReaderLegacyEvidence(t *testing.T) {
+ for _, tc := range []string{"nil-fold", "unreadable", "corrupt", "mismatched-key", "list-failure", "freshness-lapse", "fixed-g-label", "group-seen-incomplete", "group-seen-nil", "group-seen-retired"} {
+ t.Run(tc, func(t *testing.T) {
+ f := newLegFixture(t, "stable", "v3")
+ f.now = time.Now()
+ f.promote("v1.0.0", []byte("old reader"), 0)
+ s := &readerStore{Store: f.store}
+ box := "peer"
+ if tc == "fixed-g-label" {
+ box = "g-web"
+ }
+ if strings.HasPrefix(tc, "group-seen") {
+ box = "g-01234567890123456789"
+ }
+ body := `{"v":1,"box":"` + box + `","capabilities":["names-2"],"hosts":{}}`
+ if tc == "corrupt" {
+ body = `{"v":`
+ }
+ if tc == "mismatched-key" {
+ body = strings.ReplaceAll(body, `"peer"`, `"different"`)
+ }
+ if _, err := s.Put(t.Context(), edgesfile.Key(box), []byte(body), ""); err != nil {
+ t.Fatal(err)
+ }
+ var foldStore release.Store = s
+ if tc == "unreadable" {
+ foldStore = unreadableLegEdges{s}
+ }
+ if tc == "list-failure" {
+ s.listErr = true
+ }
+ e := readerFold(t, foldStore)
+ f.leg.readers = e.GroupReaderSnapshot
+ f.leg.observe(t.Context())
+ if strings.HasPrefix(tc, "group-seen") {
+ f.leg.tick(t.Context(), time.Now())
+ if f.request() != nil {
+ t.Fatal("group allowed old reader")
+ }
+ }
+ snap := e.GroupReaderSnapshot()
+ switch tc {
+ case "nil-fold", "group-seen-nil":
+ snap = edgesfile.ReaderSnapshot{}
+ case "freshness-lapse":
+ snap.CheckedAt = time.Now().Add(-6 * time.Minute)
+ case "group-seen-retired":
+ snap.Files = nil
+ case "group-seen-incomplete":
+ snap.Files = nil
+ snap.Complete = false
+ }
+ f.leg.readers = func() edgesfile.ReaderSnapshot { return snap }
+ fetches := f.countFetches()
+ f.leg.tick(t.Context(), time.Now())
+ want := !strings.HasPrefix(tc, "group-seen") || tc == "group-seen-retired"
+ _, markerErr := f.marker()
+ if (f.request() != nil) != want || (markerErr == nil) != want || (*fetches == 1) != want {
+ t.Fatalf("request=%v marker=%v fetches=%d want permit=%v", f.request(), markerErr, *fetches, want)
+ }
+ })
+ }
+}
+
+type unreadableLegEdges struct{ release.Store }
+
+func (s unreadableLegEdges) Get(ctx context.Context, key string) ([]byte, string, error) {
+ if strings.HasPrefix(key, edgesfile.Prefix) {
+ return nil, "", errors.New("edges read failed")
+ }
+ return s.Store.Get(ctx, key)
+}
+
func testSystemLegGroupReaderRollbackPaths(t *testing.T) {
for _, tc := range []string{"booting", "empty-booting", "standby", "retained-no-dial", "missing-fold", "stale-fold", "incomplete-fold", "arrival-during-spread", "cached", "deferred", "retouch", "unknown-upload", "unknown-newer-tag", "known-missing", "verified", "verified-upload", "retired", "fixed-old", "fixed-upload"} {
t.Run(tc, func(t *testing.T) {
@@ -454,7 +527,7 @@ func testSystemLegGroupReaderRollbackPaths(t *testing.T) {
sn := e.GroupReaderSnapshot()
switch tc {
case "missing-fold":
- return edgesfile.ReaderSnapshot{}
+ return edgesfile.ReaderSnapshot{GroupObserved: sn.GroupObserved}
case "stale-fold":
sn.CheckedAt = f.now.Add(-6 * time.Minute)
case "incomplete-fold":