carlos / platform Public

region HA P3b T1: gate group readers and fixed-box rollback

Publish names-2, share cached reader readiness, and refuse unsafe system
updates before staging or root requests. Cut boxroles to a Get-only store.

Targeted regression, mutations 7-9, build, vet, Darwin/Windows builds and
census dry run pass. Release pins and independent census approval remain.
Co-Authored-By: GPT-6 Astra (codex) <noreply@openai.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev 9a7cf450c62ddae3fa0a345ab8817be69c2ccee3 parent 7e03a8c
17 files changed, +725 −33
  • internal/boxroles/imports_test.go +28 −0
  • internal/boxroles/roles.go +6 −4
  • internal/boxroles/roles_test.go +0 −3
  • internal/edge/group_readers.go +37 −0
  • internal/edge/group_readers_test.go +95 −0
  • internal/edge/homemap.go +14 −3
  • internal/edge/testdata/edges-forward-hub.json +1 −1
  • internal/edgesfile/snapshot.go +82 −0
  • internal/host/agent.go +2 −0
  • internal/host/edgesfile.go +10 −2
  • internal/host/edgesfile_test.go +12 −12
  • internal/host/group_admission.go +38 −0
  • internal/host/group_names_test.go +5 −1
  • internal/host/group_readers_test.go +171 −0
  • internal/host/movesoffline_test.go +5 −5
  • internal/host/systemleg.go +45 −2
  • internal/host/systemleg_test.go +174 −0

Intent

Human

<task-notification> <task-id>b04mr09ih</task-id> <tool-use-id>toolu_015DoLmoUA2E8uDCq93Dz1zH</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/05c816f1-0a2d-43e3-9285-de8352549786/tasks/b04mr09ih.output</output-file> <status>completed</status> <summary>Background command "D=/home/paulca/amadan.net/carlos/platform/.claude/worktrees/region-ha-p3b-build/.superpowers/sdd/2026-11-04-region-ha-p3b-group; $D/wait-astra.sh t1a $D/task-1-report.md" completed (exit code 0)</summary> </task-notification>

Human

<task-notification> <task-id>b0umsisl9</task-id> <tool-use-id>toolu_01P6TsjprsQL6Ci5jzetKPsX</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/05c816f1-0a2d-43e3-9285-de8352549786/tasks/b0umsisl9.output</output-file> <status>completed</status> <summary>Background command "D=/home/paulca/amadan.net/carlos/platform/.claude/worktrees/region-ha-p3b-build/.superpowers/sdd/2026-11-04-region-ha-p3b-group; $D/wait-astra.sh t2 $D/task-2-report.md" completed (exit code 0)</summary> </task-notification>

Attributed to this commit: 23.0 g CO₂e (2,653,316 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/boxroles/imports_test.go b/internal/boxroles/imports_test.go
new file mode 100644
index 000000000..8f481bb0e
--- /dev/null
+++ b/internal/boxroles/imports_test.go
@@ -0,0 +1,28 @@
+package boxroles
+
+import (
+ "go/parser"
+ "go/token"
+ "strconv"
+ "strings"
+ "testing"
+)
+
+func TestAdmissionCoreImports(t *testing.T) {
+ for _, dir := range []string{".", "../groupadmission"} {
+ pkgs, err := parser.ParseDir(token.NewFileSet(), dir, nil, parser.ImportsOnly)
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, p := range pkgs {
+ for name, f := range p.Files {
+ for _, imp := range f.Imports {
+ path, _ := strconv.Unquote(imp.Path.Value)
+ if strings.Contains(path, "aws") || strings.HasSuffix(path, "/release") {
+ t.Errorf("%s imports %s", name, path)
+ }
+ }
+ }
+ }
+ }
+}
diff --git a/internal/boxroles/roles.go b/internal/boxroles/roles.go
index 3d717d13e..c1cedd8d4 100644
--- a/internal/boxroles/roles.go
+++ b/internal/boxroles/roles.go
@@ -11,10 +11,12 @@ import (
"regexp"
"strings"
"time"
-
- "github.com/carlosframework/platform/internal/release"
)
+type Getter interface {
+ Get(context.Context, string) ([]byte, string, error)
+}
+
type Role string
const (
@@ -47,7 +49,7 @@ func Key(target string) (string, error) {
}
// Read always charges both point reads, including when the first fails.
-func Read(ctx context.Context, s release.Store, ref, region string) (Role, error) {
+func Read(ctx context.Context, s Getter, ref, region string) (Role, error) {
if !ValidLabel(ref, 63) || !ValidLabel(region, 32) {
return Booting, errors.New("boxroles: invalid box or region")
}
@@ -66,7 +68,7 @@ func Read(ctx context.Context, s release.Store, ref, region string) (Role, error
}
return Serve, nil
}
-func read(ctx context.Context, s release.Store, key string) (*Record, error) {
+func read(ctx context.Context, s Getter, key string) (*Record, error) {
body, _, err := s.Get(ctx, key)
if errors.Is(err, os.ErrNotExist) {
return nil, nil
diff --git a/internal/boxroles/roles_test.go b/internal/boxroles/roles_test.go
index 8120020d0..1fed4e6cd 100644
--- a/internal/boxroles/roles_test.go
+++ b/internal/boxroles/roles_test.go
@@ -6,12 +6,9 @@ import (
"os"
"strings"
"testing"
-
- "github.com/carlosframework/platform/internal/release"
)
type roleStore struct {
- release.Store
bodies map[string]string
gets []string
fail string
diff --git a/internal/edge/group_readers.go b/internal/edge/group_readers.go
new file mode 100644
index 000000000..b040c9fbd
--- /dev/null
+++ b/internal/edge/group_readers.go
@@ -0,0 +1,37 @@
+package edge
+
+import (
+ "encoding/json"
+ "github.com/carlosframework/platform/internal/edgesfile"
+)
+
+// GroupReaderSnapshot reads the deployment-wide cache, without cloud I/O or
+// serving filters. A failed refresh invalidates completeness, not routing.
+func (e *Edge) GroupReaderSnapshot() edgesfile.ReaderSnapshot {
+ m := e.homes.Load()
+ if m == nil {
+ return edgesfile.ReaderSnapshot{}
+ }
+ s := m.snapshot()
+ out := edgesfile.ReaderSnapshot{Self: m.self, Complete: s.readerComplete, CheckedAt: s.readerCheckedAt}
+ 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) {
+ out.Complete = false
+ }
+ var caps []json.RawMessage
+ valid := placementField(f.Capabilities, &caps)
+ for _, raw := range caps {
+ var cap string
+ valid = placementField(raw, &cap) && valid
+ p.Capabilities = append(p.Capabilities, cap)
+ }
+ if !valid {
+ out.Complete = false
+ }
+ // A retained group file counts even with no host or dial. No per-host
+ // copy is needed for this whole-publisher capability check.
+ out.Files = append(out.Files, p)
+ }
+ return out
+}
diff --git a/internal/edge/group_readers_test.go b/internal/edge/group_readers_test.go
new file mode 100644
index 000000000..90bcb4202
--- /dev/null
+++ b/internal/edge/group_readers_test.go
@@ -0,0 +1,95 @@
+package edge
+
+import (
+ "context"
+ "errors"
+ "os"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/edgesfile"
+ "github.com/carlosframework/platform/internal/release"
+)
+
+type groupReaderStore struct {
+ release.Store
+ badList, badGet bool
+ reads int
+}
+
+func (s *groupReaderStore) List(ctx context.Context, key string) ([]string, error) {
+ s.reads++
+ if s.badList {
+ return nil, errors.New("list failed")
+ }
+ return s.Store.List(ctx, key)
+}
+func (s *groupReaderStore) Get(ctx context.Context, key string) ([]byte, string, error) {
+ s.reads++
+ if s.badGet && key == edgesfile.Key("peer") {
+ return nil, "", os.ErrNotExist
+ }
+ return s.Store.Get(ctx, key)
+}
+
+func TestGroupReadersReadyCachedFold(t *testing.T) {
+ s := &groupReaderStore{Store: release.NewDirStore(t.TempDir())}
+ key := edgesfile.Key("peer")
+ body := []byte(`{"v":1,"box":"peer","region":"far","placement":"different-pool","capabilities":["names-2"],"generation":"2000-01-01T00:00:00Z","hosts":{}}`)
+ etag, err := s.Put(t.Context(), key, body, "")
+ if err != nil {
+ t.Fatal(err)
+ }
+ now := time.Now()
+ m := newHomeMap(s, "self")
+ m.now = func() time.Time { return now }
+ e := &Edge{}
+ e.homes.Store(m)
+ ready := func() bool { return edgesfile.GroupReadersReady(e.GroupReaderSnapshot(), "self", now) }
+ if ready() {
+ t.Fatal("unread cache admitted")
+ }
+ if err := m.Refresh(t.Context()); err != nil {
+ t.Fatal(err)
+ }
+ reads := s.reads
+ if !ready() {
+ t.Fatal("complete upgraded fold refused")
+ }
+ if reads != s.reads {
+ t.Fatal("predicate performed I/O")
+ }
+ now = now.Add(6 * time.Minute)
+ if ready() {
+ t.Fatal("stale cache admitted")
+ }
+ if err := m.Refresh(t.Context()); err != nil {
+ t.Fatal(err)
+ }
+ if !ready() {
+ t.Fatal("fresh read of unchanged capability refused")
+ }
+ // A fixed box rewrites on changes, not a heartbeat. Its old generation
+ // does not retire it or make freshly read capability bytes untrustworthy.
+ if _, err := s.Put(t.Context(), key, []byte(`{"v":`), etag); err != nil {
+ t.Fatal(err)
+ }
+ _ = m.Refresh(t.Context())
+ if ready() {
+ t.Fatal("carried-forward parse granted completeness")
+ }
+ if len(e.GroupReaderSnapshot().Files) != 1 {
+ t.Fatal("lost retained peer")
+ }
+ s.badList = true
+ _ = m.Refresh(t.Context())
+ if ready() {
+ t.Fatal("failed listing admitted")
+ }
+ s.badList = false
+ s.badGet = true
+ _ = m.Refresh(t.Context())
+ if ready() {
+ t.Fatal("known listed publisher missing its file admitted")
+ }
+}
diff --git a/internal/edge/homemap.go b/internal/edge/homemap.go
index df7354823..8ae3dca3b 100644
--- a/internal/edge/homemap.go
+++ b/internal/edge/homemap.go
@@ -272,6 +272,8 @@ type homeEntry struct {
// published, so a reader holds no lock past the pointer read.
type homeSnapshot struct {
departureComplete bool
+ readerCheckedAt time.Time
+ readerComplete bool
// files is the parsed per-box file, keyed by its BUCKET key. This is the
// carry-forward unit: an object that could not be read (or could not be
// parsed) this poll keeps its previous parse, per box, so one bad file
@@ -473,6 +475,13 @@ func (m *homeMap) refresh(ctx context.Context, readHosts bool) error {
if readHosts {
hostsErr = m.refreshHosts(ctx)
}
+ // Readers use the same full fold and change-index validation as routing.
+ m.mu.Lock()
+ current := *m.snap
+ current.readerComplete = hostsErr == nil && current.read && current.readerComplete
+ current.readerCheckedAt = m.clock()
+ m.snap = &current
+ m.mu.Unlock()
keysErr := m.refreshKeys(ctx)
if hostsErr == nil {
m.health.MapLoaded()
@@ -527,6 +536,7 @@ func (m *homeMap) refreshHosts(ctx context.Context) error {
// BUCKET would not hand over, which is the one that says "this is not an
// object fault at all" when it covers everything (see below).
var tried, failed, unread int
+ var readerMissing bool
var lastErr error
for _, key := range keys {
// The prefix is flat and every member is <box>.json. Anything else
@@ -538,8 +548,9 @@ func (m *homeMap) refreshHosts(ctx context.Context) error {
tried++
body, etag, err := m.s.Get(ctx, key)
if errors.Is(err, os.ErrNotExist) {
- // Raced a delete between the list and the get — the box was
- // retired mid-poll. Not a fault; it is simply gone.
+ // Routing can drop a concurrently deleted row. The reader gate
+ // cannot use this partial inventory as retirement evidence.
+ readerMissing = true
continue
}
// ONE bad object is not a bad poll, whichever way it went bad.
@@ -580,7 +591,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}
+ snap := &homeSnapshot{files: next, hosts: hosts, read: true, departureComplete: failed == 0, readerComplete: failed == 0 && !readerMissing}
m.mu.Lock()
m.snap = snap
wake := m.hostsWake
diff --git a/internal/edge/testdata/edges-forward-hub.json b/internal/edge/testdata/edges-forward-hub.json
index 5a4b0ed97..e1d4c328e 100644
--- a/internal/edge/testdata/edges-forward-hub.json
+++ b/internal/edge/testdata/edges-forward-hub.json
@@ -1 +1 @@
-{"v":1,"box":"hub","eip":"198.51.100.7","hibernation_configured":false,"serves_shared_pool":false,"accepts_inbound":false,"burst_notices":true,"moves_protocol":0,"seeds_protocol":0,"addrs":null,"generation":"2026-10-30T00:00:00Z","hosts":{"*.bah-certonly.example.com":{"role":"wildcard","platform":false,"wildcard":true},"*.bah-certs.example.com":{"role":"wildcard","platform":false,"wildcard":true},"*.bah-regional.example.com":{"role":"wildcard","platform":false,"wildcard":true},"*.bah-wild.example.com":{"role":"home","platform":false,"alias":true,"wildcard":true,"account":"bah","app":"shop","target_host":"shop.bah.example.com"},"bah-certonly.example.com":{"role":"home","platform":false,"alias":true,"account":"bah","app":"shop","target_host":"shop.bah.example.com"},"shop.bah-custom.example.com":{"role":"home","platform":false,"alias":true,"account":"bah","app":"shop","target_host":"shop.bah.example.com"},"shop.bah.example.com":{"role":"home","platform":true,"account":"bah","app":"shop"},"tickets.example.com":{"role":"home","platform":false,"alias":true,"account":"bah","app":"shop","target_host":"shop.bah.example.com"}}}
+{"v":1,"box":"hub","eip":"198.51.100.7","hibernation_configured":false,"serves_shared_pool":false,"accepts_inbound":false,"burst_notices":true,"capabilities":["names-2"],"moves_protocol":0,"seeds_protocol":0,"addrs":null,"generation":"2026-10-30T00:00:00Z","hosts":{"*.bah-certonly.example.com":{"role":"wildcard","platform":false,"wildcard":true},"*.bah-certs.example.com":{"role":"wildcard","platform":false,"wildcard":true},"*.bah-regional.example.com":{"role":"wildcard","platform":false,"wildcard":true},"*.bah-wild.example.com":{"role":"home","platform":false,"alias":true,"wildcard":true,"account":"bah","app":"shop","target_host":"shop.bah.example.com"},"bah-certonly.example.com":{"role":"home","platform":false,"alias":true,"account":"bah","app":"shop","target_host":"shop.bah.example.com"},"shop.bah-custom.example.com":{"role":"home","platform":false,"alias":true,"account":"bah","app":"shop","target_host":"shop.bah.example.com"},"shop.bah.example.com":{"role":"home","platform":true,"account":"bah","app":"shop"},"tickets.example.com":{"role":"home","platform":false,"alias":true,"account":"bah","app":"shop","target_host":"shop.bah.example.com"}}}
diff --git a/internal/edgesfile/snapshot.go b/internal/edgesfile/snapshot.go
index b4e4886ce..f022b9f09 100644
--- a/internal/edgesfile/snapshot.go
+++ b/internal/edgesfile/snapshot.go
@@ -4,11 +4,13 @@ import (
"context"
"encoding/json"
"log"
+ "slices"
"strings"
"sync"
"time"
"github.com/carlosframework/platform/internal/boxchoice"
+ "github.com/carlosframework/platform/internal/lbhealth"
"github.com/carlosframework/platform/internal/release"
"github.com/carlosframework/platform/internal/status"
)
@@ -305,3 +307,83 @@ func LiveSnapshot(ctx context.Context, s release.Store, now time.Time) (boxchoic
}
return snap.BoxChoice(), nil
}
+
+// NamesCapability is the closed-namespace reader protocol, independent of HA mode.
+const NamesCapability = "names-2"
+
+// ReaderSnapshot projects the complete cached deployment fold, before any
+// serving, address, pool or region filter. KnownReaders is an optional inventory
+// 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
+}
+
+func (s ReaderSnapshot) Fresh(now time.Time) bool {
+ if !s.Complete || s.CheckedAt.IsZero() || now.Before(s.CheckedAt) || now.Sub(s.CheckedAt) > lbhealth.RefreshWindow {
+ return false
+ }
+ seen := map[string]bool{}
+ for _, f := range s.Files {
+ if f.Box == "" || f.Key != Key(f.Box) || seen[f.Box] {
+ return false
+ }
+ seen[f.Box] = true
+ }
+ for _, ref := range s.KnownReaders {
+ if ref != s.Self && !seen[ref] {
+ return false
+ }
+ }
+ return true
+}
+
+// GroupReadersReady is shared by first publication and launch/maintenance
+// admission. Self is the running names-2 build, not its previous edges file.
+// Silence never removes a publisher from this inventory.
+func GroupReadersReady(s ReaderSnapshot, self string, now time.Time) bool {
+ s.Self = self
+ if self == "" || !s.Fresh(now) {
+ return false
+ }
+ seen := map[string]bool{self: true}
+ for _, f := range s.Files {
+ if f.Box == "" || f.Key != Key(f.Box) || seen[f.Box] && f.Box != self {
+ return false
+ }
+ seen[f.Box] = true
+ if f.Box == self {
+ continue
+ }
+ if !slices.Contains(f.Capabilities, NamesCapability) {
+ return false
+ }
+ }
+ for _, ref := range s.KnownReaders {
+ if !seen[ref] {
+ return false
+ }
+ }
+ return true
+}
+
+// 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.
+func (s ReaderSnapshot) HasGroupNamespace() bool {
+ for _, f := range s.Files {
+ if strings.HasPrefix(f.Box, "g-") || strings.HasPrefix(strings.TrimPrefix(f.Key, Prefix), "g-") {
+ return true
+ }
+ }
+ for _, ref := range s.KnownReaders {
+ if strings.HasPrefix(ref, "g-") {
+ return true
+ }
+ }
+ return false
+}
diff --git a/internal/host/agent.go b/internal/host/agent.go
index 8d23be426..0a71009a4 100644
--- a/internal/host/agent.go
+++ b/internal/host/agent.go
@@ -1097,6 +1097,7 @@ func runAgent(args []string, buildClaims ClaimFactory) {
edgeOpts = append(edgeOpts, admissionOption)
}
edge.RunWithActivatorReady(args, act, cache, func(e *edge.Edge) {
+ armedGroupReaders.Store(&groupReaderSource{snapshot: e.GroupReaderSnapshot})
// Edge-held streams (spec 2026-10-28 §3.2, §3.7): the activator
// signals the edge's held streams when a host may have become
// admissible. act is nil when hibernation is not armed; no route
@@ -3453,6 +3454,7 @@ func fastConvergeLoop(reg *registry.Registry, svc *activator.Service, sd *schedu
// in a loop of its own because the spread deadline needs a seconds
// cadence to run down on, and this is the loop that already has one.
d.systemLeg = newSystemLeg(store, pub, os.Getenv, dd, optDir)
+ d.systemLeg.readers = cachedGroupReaders
// One observe at arming, on restartSeed's precedent: the leg below only
// re-observes on a serial move or at its hourly floor, so a box that
// (re)starts under an already-promoted pointer would otherwise sit on the
diff --git a/internal/host/edgesfile.go b/internal/host/edgesfile.go
index 99d113ee2..9269b3c41 100644
--- a/internal/host/edgesfile.go
+++ b/internal/host/edgesfile.go
@@ -18,6 +18,7 @@ import (
"github.com/carlosframework/platform/internal/appconfig"
"github.com/carlosframework/platform/internal/boxroles"
"github.com/carlosframework/platform/internal/edge"
+ "github.com/carlosframework/platform/internal/edgesfile"
"github.com/carlosframework/platform/internal/instancectl"
"github.com/carlosframework/platform/internal/registry"
"github.com/carlosframework/platform/internal/release"
@@ -197,9 +198,9 @@ const capLifetimes1 = "lifetimes-1"
// offline-move-1 is added per pass by withOfflineCapability.
func edgesFileCapabilities(getenv func(string) string) []string {
if !regionHAEnabled(getenv) {
- return []string{capLifetimes1}
+ return []string{capLifetimes1, edgesfile.NamesCapability}
}
- return []string{capLifetimes1, capRegionHA1}
+ return []string{capLifetimes1, capRegionHA1, edgesfile.NamesCapability}
}
// withOfflineCapability is caps with offline-move-1 and offline-stage-1 when
@@ -953,6 +954,13 @@ func edgesFileWriteClaims(ctx context.Context, s release.Store, reg *registry.Re
f := ident
f.V, f.EIP, f.Hosts, f.Generation = 1, eip, hosts, ""
f = snapshotBoxRole(f)
+ // First group publication has the same reader barrier as CONTINUE.
+ if a, ok := f.RoleSource.(*fixedAdmission); ok && !a.state.Admitted() && !a.groupReadersReady(time.Now()) {
+ return errGroupReadersNotReady
+ }
+ if !slices.Contains(f.Capabilities, edgesfile.NamesCapability) {
+ f.Capabilities = append(slices.Clone(f.Capabilities), edgesfile.NamesCapability)
+ }
f.BurstNotices = true
f.PrivateIP, f.PrivateCIDR = private.Private, private.PrivateCIDR
// Before the gate copy, so an address change is a reason to write.
diff --git a/internal/host/edgesfile_test.go b/internal/host/edgesfile_test.go
index 43ae61091..df5e3487c 100644
--- a/internal/host/edgesfile_test.go
+++ b/internal/host/edgesfile_test.go
@@ -327,7 +327,7 @@ func TestEdgesFileRawWireBodyMatchesSchema(t *testing.T) {
t.Fatalf("generation %q is not RFC3339: %v", probe.Generation, err)
}
- want := `{"v":1,"box":"quiet-harbour","eip":"203.0.113.10","hibernation_configured":false,"serves_shared_pool":false,"accepts_inbound":false,"burst_notices":true,"moves_protocol":0,"seeds_protocol":0,"addrs":null,"generation":"` +
+ want := `{"v":1,"box":"quiet-harbour","eip":"203.0.113.10","hibernation_configured":false,"serves_shared_pool":false,"accepts_inbound":false,"burst_notices":true,"capabilities":["names-2"],"moves_protocol":0,"seeds_protocol":0,"addrs":null,"generation":"` +
probe.Generation + `","hosts":{"app.example.com":{"role":"home","platform":false}}}`
if string(got) != want {
t.Fatalf("raw wire body =\n%s\nwant\n%s", got, want)
@@ -370,7 +370,7 @@ func TestEdgesFileRawWireBodyRegionField(t *testing.T) {
t.Fatal(err)
}
gen := genOf(t, got)
- want := `{"v":1,"box":"quiet-harbour","eip":"203.0.113.10","hibernation_configured":false,"serves_shared_pool":false,"accepts_inbound":false,"burst_notices":true,"moves_protocol":0,"seeds_protocol":0,"addrs":null,"generation":"` +
+ want := `{"v":1,"box":"quiet-harbour","eip":"203.0.113.10","hibernation_configured":false,"serves_shared_pool":false,"accepts_inbound":false,"burst_notices":true,"capabilities":["names-2"],"moves_protocol":0,"seeds_protocol":0,"addrs":null,"generation":"` +
gen + `","hosts":{"app.example.com":{"role":"home","platform":false}}}`
if string(got) != want {
t.Fatalf("raw wire body (region unset) =\n%s\nwant\n%s", got, want)
@@ -389,7 +389,7 @@ func TestEdgesFileRawWireBodyRegionField(t *testing.T) {
t.Fatal(err)
}
gen := genOf(t, got)
- want := `{"v":1,"box":"quiet-harbour","eip":"203.0.113.10","region":"eu-west-1","hibernation_configured":false,"serves_shared_pool":false,"accepts_inbound":false,"burst_notices":true,"moves_protocol":0,"seeds_protocol":0,"addrs":null,"generation":"` +
+ want := `{"v":1,"box":"quiet-harbour","eip":"203.0.113.10","region":"eu-west-1","hibernation_configured":false,"serves_shared_pool":false,"accepts_inbound":false,"burst_notices":true,"capabilities":["names-2"],"moves_protocol":0,"seeds_protocol":0,"addrs":null,"generation":"` +
gen + `","hosts":{"app.example.com":{"role":"home","platform":false}}}`
if string(got) != want {
t.Fatalf("raw wire body (region set) =\n%s\nwant\n%s", got, want)
@@ -943,7 +943,7 @@ func TestEdgesFileRawWireBodyPlacementField(t *testing.T) {
if err := json.Unmarshal(got, &probe); err != nil {
t.Fatal(err)
}
- want := `{"v":1,"box":"quiet-harbour","eip":"203.0.113.10","region":"eu-west-2","placement":"uk","hibernation_configured":false,"serves_shared_pool":false,"accepts_inbound":false,"burst_notices":true,"moves_protocol":0,"seeds_protocol":0,"addrs":null,"generation":"` +
+ want := `{"v":1,"box":"quiet-harbour","eip":"203.0.113.10","region":"eu-west-2","placement":"uk","hibernation_configured":false,"serves_shared_pool":false,"accepts_inbound":false,"burst_notices":true,"capabilities":["names-2"],"moves_protocol":0,"seeds_protocol":0,"addrs":null,"generation":"` +
probe.Generation + `","hosts":{"app.example.com":{"role":"home","platform":false}}}`
if string(got) != want {
t.Fatalf("raw wire body (placement set) =\n%s\nwant\n%s", got, want)
@@ -1356,13 +1356,13 @@ func TestEdgesFileCapabilityFollowsTheFlag(t *testing.T) {
}
}
// lifetimes-1 is the lifetimes cutover's box floor, published always.
- if got := edgesFileCapabilities(env("")); !slices.Equal(got, []string{"lifetimes-1"}) {
+ if got := edgesFileCapabilities(env("")); !slices.Equal(got, []string{"lifetimes-1", "names-2"}) {
t.Fatalf("unset: %v", got)
}
- if got := edgesFileCapabilities(env("1")); !slices.Equal(got, []string{"lifetimes-1", "region-ha-1"}) {
+ if got := edgesFileCapabilities(env("1")); !slices.Equal(got, []string{"lifetimes-1", "region-ha-1", "names-2"}) {
t.Fatalf("set: %v", got)
}
- if got := edgesFileCapabilities(env("0")); !slices.Equal(got, []string{"lifetimes-1"}) {
+ if got := edgesFileCapabilities(env("0")); !slices.Equal(got, []string{"lifetimes-1", "names-2"}) {
t.Fatalf("\"0\" is off: %v", got)
}
}
@@ -1386,8 +1386,8 @@ func TestEdgesFilePublishesTheLifetimesFloor(t *testing.T) {
t.Fatal(err)
}
var f edgesfile.PlacementView
- if err := json.Unmarshal(b1, &f); err != nil || !slices.Equal(f.Capabilities, []string{capLifetimes1}) {
- t.Fatalf("capabilities = %v (%v), want [lifetimes-1]", f.Capabilities, err)
+ if err := json.Unmarshal(b1, &f); err != nil || !slices.Equal(f.Capabilities, []string{capLifetimes1, edgesfile.NamesCapability}) {
+ t.Fatalf("capabilities = %v (%v), want [lifetimes-1 names-2]", f.Capabilities, err)
}
if err := edgesFileWrite(context.Background(), s, reg, ident, "203.0.113.10", &last, false); err != nil {
t.Fatal(err)
@@ -1416,7 +1416,7 @@ func TestEdgesFileRawWireBodyCarriesBoxEvidence(t *testing.T) {
}
for key, want := range map[string]string{
"box_id": `"i-0abc"`,
- "capabilities": `["region-ha-1"]`,
+ "capabilities": `["region-ha-1","names-2"]`,
"headroom": `{"mem_free_mib":2210,"disk_free_mib":31200,"awake":14}`,
} {
if string(raw[key]) != want {
@@ -1435,7 +1435,7 @@ func TestEdgesFileOmitsBoxEvidenceWhenAbsent(t *testing.T) {
t.Fatal(err)
}
body, _, _ := s.Get(context.Background(), "control/edges/annie.json")
- for _, key := range []string{"box_id", "capabilities", "draining", "headroom"} {
+ for _, key := range []string{"box_id", "draining", "headroom"} {
if bytes.Contains(body, []byte(`"`+key+`"`)) {
t.Errorf("%s present in %s", key, body)
}
@@ -1785,7 +1785,7 @@ func TestEdgesFileAddrsEmptyAndUnreadable(t *testing.T) {
}
return strings.Replace(string(body), probe.Generation, "GEN", 1)
}
- const head = `{"v":1,"box":"%s","eip":"203.0.113.10","hibernation_configured":false,"serves_shared_pool":false,"accepts_inbound":false,"burst_notices":true,"moves_protocol":0,"seeds_protocol":0,`
+ const head = `{"v":1,"box":"%s","eip":"203.0.113.10","hibernation_configured":false,"serves_shared_pool":false,"accepts_inbound":false,"burst_notices":true,"capabilities":["names-2"],"moves_protocol":0,"seeds_protocol":0,`
const tail = `,"generation":"GEN","hosts":{"app.example.com":{"role":"home","platform":false}}}`
r := &addrsReader{}
diff --git a/internal/host/group_admission.go b/internal/host/group_admission.go
index 0e0d1782b..e970f6f1e 100644
--- a/internal/host/group_admission.go
+++ b/internal/host/group_admission.go
@@ -13,6 +13,7 @@ import (
"github.com/carlosframework/platform/internal/activator"
"github.com/carlosframework/platform/internal/boxroles"
"github.com/carlosframework/platform/internal/edge"
+ "github.com/carlosframework/platform/internal/edgesfile"
"github.com/carlosframework/platform/internal/groupadmission"
"github.com/carlosframework/platform/internal/hadeparture"
"github.com/carlosframework/platform/internal/lbhealth"
@@ -23,6 +24,8 @@ var armedFixedAdmission atomic.Pointer[fixedAdmission]
type fixedAdmission struct {
group bool
+ readers func() edgesfile.ReaderSnapshot
+ readerSelf string
mu sync.Mutex
state groupadmission.State
health *lbhealth.State
@@ -125,6 +128,9 @@ func (a *fixedAdmission) tick(ctx context.Context) {
default:
}
}
+ if !a.state.Admitted() && !a.groupReadersReady(time.Now()) {
+ return
+ }
if !a.state.Ready() {
a.logWaitingLocked(time.Now())
return
@@ -244,3 +250,35 @@ func (a *fixedAdmission) logWaitingLocked(now time.Time) {
}
log.Printf("tenant admission is still closed. waiting for: %s", strings.Join(missing, ", "))
}
+
+var errGroupReadersNotReady = errors.New("group_readers_not_ready")
+
+// groupReadersReady gates publication and initial/maintenance admission only.
+// Later dependency failures must not clear the admitted health latch.
+func (a *fixedAdmission) groupReadersReady(now time.Time) bool {
+ if a == nil || !a.group {
+ return true
+ }
+ read, self := a.readers, a.readerSelf
+ if read == nil {
+ read = cachedGroupReaders
+ }
+ snapshot := read()
+ if self == "" {
+ self = snapshot.Self
+ }
+ return edgesfile.GroupReadersReady(snapshot, self, now)
+}
+
+type groupReaderSource struct {
+ snapshot func() edgesfile.ReaderSnapshot
+}
+
+var armedGroupReaders atomic.Pointer[groupReaderSource]
+
+func cachedGroupReaders() edgesfile.ReaderSnapshot {
+ if s := armedGroupReaders.Load(); s != nil {
+ return s.snapshot()
+ }
+ return edgesfile.ReaderSnapshot{}
+}
diff --git a/internal/host/group_names_test.go b/internal/host/group_names_test.go
index 9d12fafc0..83f5344b3 100644
--- a/internal/host/group_names_test.go
+++ b/internal/host/group_names_test.go
@@ -90,6 +90,10 @@ func TestGroupNamesBeforeAdmission(t *testing.T) {
}
return ""
}, admissionHealth())
+ admission.readerSelf = "g-closed"
+ admission.readers = func() edgesfile.ReaderSnapshot {
+ return edgesfile.ReaderSnapshot{Complete: true, CheckedAt: now}
+ }
if err := reconcileSerialized(ctx, s, reg, provision.ReconcileConfig{DataDir: t.TempDir()}); err != nil {
t.Fatal(err)
}
@@ -292,7 +296,7 @@ func TestGroupNameClassCensus(t *testing.T) {
var groupNameProducerInventory = map[string]string{
"../provision/sidecar_reconcile.go": "f6260269532e84fe27acf8c7bde6d7aaa6b463b2f978e9c315609e569fbff636",
"rootinventory.go": "d5f00f6c9a01049ff4a91342a8dfb253e90a186cfbd57bd02a84f2e2e8bfcf51",
- "edgesfile.go": "60c4706b89b776da6a1f5830f66cd640d7c0ae0a12babfd588f2e042333a510a",
+ "edgesfile.go": "ce5543790e9df9019fa65457822210adff1dc1b2c6b9fd0084a1d7d4f75998eb",
"../domains/aliases.go": "ce4e04b06bb9fa0685b5f912a756178ed10e5763cfafd4843daf0b6d5702ef90",
"../domains/reconcile.go": "3c0ba9ccb35b7d7623896f69b225aeecde8154845bad99a301a1186793b78a7e",
"../provision/reconcile.go": "7df62fbd5589e02bd316d772c006a6543ad8ff84db349a8abb4687bdd745321b",
diff --git a/internal/host/group_readers_test.go b/internal/host/group_readers_test.go
new file mode 100644
index 000000000..8c185bb3d
--- /dev/null
+++ b/internal/host/group_readers_test.go
@@ -0,0 +1,171 @@
+package host
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "github.com/carlosframework/platform/internal/boxroles"
+ "github.com/carlosframework/platform/internal/edge"
+ "github.com/carlosframework/platform/internal/groupadmission"
+ "os"
+ "slices"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/edgesfile"
+ "github.com/carlosframework/platform/internal/release"
+)
+
+func TestGroupReadersReady(t *testing.T) {
+ t.Run("admission", testGroupReadersReadyAdmission)
+ s := release.NewDirStore(t.TempDir())
+ reg := edgesTestRegistry(t)
+ var last []byte
+ if err := edgesFilePass(t.Context(), s, reg, edgesFile{Box: "fixed", Capabilities: edgesFileCapabilities(func(string) string { return "" })}, "192.0.2.1", &last); err != nil {
+ t.Fatal(err)
+ }
+ body, _, err := s.Get(t.Context(), edgesfile.Key("fixed"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ var f edgesfile.PlacementView
+ if err := json.Unmarshal(body, &f); err != nil {
+ t.Fatal(err)
+ }
+ if !slices.Contains(f.Capabilities, "names-2") {
+ t.Fatalf("upgraded writer capabilities = %v, missing names-2", f.Capabilities)
+ }
+}
+
+// readerFold uses the production home map, including its complete deployment
+// LIST/GET and parser, with no request-time store reads.
+func readerFold(t *testing.T, store release.Store) *edge.Edge {
+ t.Helper()
+ e, err := edge.New(edgesTestRegistry(t), nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ e.EnableStatic(store, nil, "")
+ e.ArmHomeMap()
+ return e
+}
+
+type readerStore struct {
+ release.Store
+ puts, gets, lists int
+ badKey string
+ listErr bool
+}
+
+func (s *readerStore) Get(ctx context.Context, key string) ([]byte, string, error) {
+ s.gets++
+ if key == s.badKey {
+ return nil, "", os.ErrNotExist
+ }
+ return s.Store.Get(ctx, key)
+}
+func (s *readerStore) List(ctx context.Context, prefix string) ([]string, error) {
+ s.lists++
+ if s.listErr {
+ return nil, errors.New("unreadable")
+ }
+ return s.Store.List(ctx, prefix)
+}
+func (s *readerStore) Put(ctx context.Context, key string, body []byte, match string) (string, error) {
+ s.puts++
+ return s.Store.Put(ctx, key, body, match)
+}
+
+type readerCompleter struct{ calls int }
+
+func (c *readerCompleter) Complete(context.Context, groupadmission.Launch) error {
+ c.calls++
+ return nil
+}
+
+func testGroupReadersReadyAdmission(t *testing.T) {
+ for _, tc := range []string{"all-upgraded", "peer-downgraded-before-continue", "old-other-region", "old-other-pool", "malformed", "malformed-null-element", "missing-listed-file", "incomplete-list", "unknown-freshness", "stale-fold", "known-missing", "self-old", "empty-new-launch", "unknown-identity"} {
+ t.Run(tc, func(t *testing.T) {
+ s := &readerStore{Store: release.NewDirStore(t.TempDir())}
+ body := `{"v":1,"box":"peer","region":"other-region","placement":"other-pool","capabilities":["names-2"],"hosts":{}}`
+ if strings.HasPrefix(tc, "old-") {
+ body = strings.ReplaceAll(body, `"names-2"`, `"lifetimes-1"`)
+ }
+ if tc == "malformed" {
+ body = strings.ReplaceAll(body, `["names-2"]`, `{}`)
+ }
+ if tc == "malformed-null-element" {
+ body = strings.ReplaceAll(body, `["names-2"]`, `["names-2",null]`)
+ }
+ if tc == "self-old" {
+ body = strings.ReplaceAll(strings.ReplaceAll(body, `"peer"`, `"self"`), `"names-2"`, `"old"`)
+ }
+ key := edgesfile.Key("peer")
+ if tc == "self-old" {
+ key = edgesfile.Key("self")
+ }
+ if tc == "unknown-identity" {
+ body = strings.ReplaceAll(body, `"box":"peer"`, `"box":"someone-else"`)
+ }
+ if tc != "empty-new-launch" {
+ if _, err := s.Put(t.Context(), key, []byte(body), ""); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if tc == "missing-listed-file" {
+ s.badKey = key
+ }
+ if tc == "incomplete-list" {
+ s.listErr = true
+ }
+ e := readerFold(t, s)
+ sn := e.GroupReaderSnapshot()
+ if tc == "unknown-freshness" {
+ sn.CheckedAt = time.Time{}
+ }
+ if tc == "stale-fold" {
+ sn.CheckedAt = time.Now().Add(-6 * time.Minute)
+ }
+ if tc == "known-missing" {
+ sn.KnownReaders = []string{"live-without-file"}
+ }
+ a := &fixedAdmission{group: true, readerSelf: "self", readers: func() edgesfile.ReaderSnapshot { return sn }, health: admissionHealth(), opened: make(chan struct{}), known: true, role: boxroles.Serve}
+ a.observe(groupadmission.Facts{EnvLoaded: true, Reconciled: true, TerminationStarted: true})
+ reg := edgesTestRegistry(t)
+ puts, gets, lists := s.puts, s.gets, s.lists
+ var last []byte
+ err := edgesFilePass(t.Context(), s, reg, edgesFile{Box: "self", RoleSource: a}, "192.0.2.1", &last)
+ want := tc == "all-upgraded" || tc == "peer-downgraded-before-continue" || tc == "self-old" || tc == "empty-new-launch"
+ if (err == nil) != want {
+ t.Fatalf("publication err=%v want permitted=%v", err, want)
+ }
+ // A previously successful booting write is already latched when
+ // readiness is checked again for CONTINUE or maintenance admission.
+ a.observe(groupadmission.Facts{RolePublished: true})
+ if tc == "peer-downgraded-before-continue" {
+ sn.Files[0].Capabilities = nil
+ want = false
+ puts, gets, lists = s.puts, s.gets, s.lists
+ }
+ completer := &readerCompleter{}
+ // Task 3 supplies the real hook. Its common predicate is exercised at
+ // the same State.Admit boundary now, before any CONTINUE.
+ err = a.state.Admit(t.Context(), &groupadmission.Launch{}, completer, func() bool { return a.groupReadersReady(time.Now()) })
+ if (err == nil) != want || (completer.calls == 1) != want {
+ t.Fatalf("admit=%v CONTINUE=%d", err, completer.calls)
+ }
+ if !want && (s.puts != puts || s.gets != gets || s.lists != lists) {
+ t.Fatalf("refusal performed store I/O: puts=%d gets=%d lists=%d", s.puts-puts, s.gets-gets, s.lists-lists)
+ }
+ if want {
+ // The latch survives loss of shared evidence.
+ sn.Complete = false
+ a.tick(t.Context())
+ if !a.state.Admitted() {
+ t.Fatal("dependency failure cleared admission")
+ }
+ }
+ })
+ }
+}
diff --git a/internal/host/movesoffline_test.go b/internal/host/movesoffline_test.go
index 45cbea708..73d84ec62 100644
--- a/internal/host/movesoffline_test.go
+++ b/internal/host/movesoffline_test.go
@@ -928,7 +928,7 @@ func TestOfflineCapabilityAndAnIncapableBox(t *testing.T) {
if armedOfflineCapable() {
t.Fatal("capable with no worker armed")
}
- if got := withOfflineCapability(edgesFileCapabilities(env()), armedOfflineCapable()); !slices.Equal(got, []string{capLifetimes1}) {
+ if got := withOfflineCapability(edgesFileCapabilities(env()), armedOfflineCapable()); !slices.Equal(got, []string{capLifetimes1, "names-2"}) {
t.Fatalf("no worker armed: %v", got)
}
wdCap := newOffWorld(t)
@@ -937,11 +937,11 @@ func TestOfflineCapabilityAndAnIncapableBox(t *testing.T) {
if !armedOfflineCapable() {
t.Fatal("a capable armed worker does not publish")
}
- if got := withOfflineCapability(edgesFileCapabilities(env()), armedOfflineCapable()); !slices.Equal(got, []string{capLifetimes1, capOfflineMove1, capOfflineStage1}) {
+ if got := withOfflineCapability(edgesFileCapabilities(env()), armedOfflineCapable()); !slices.Equal(got, []string{capLifetimes1, "names-2", capOfflineMove1, capOfflineStage1}) {
t.Fatalf("capable box: %v", got)
}
base := edgesFileCapabilities(env("CARLOS_REGION_HA", "1"))
- if got := withOfflineCapability(base, true); !slices.Equal(got, []string{capLifetimes1, capRegionHA1, capOfflineMove1, capOfflineStage1}) || !slices.Equal(base, []string{capLifetimes1, capRegionHA1}) {
+ if got := withOfflineCapability(base, true); !slices.Equal(got, []string{capLifetimes1, capRegionHA1, "names-2", capOfflineMove1, capOfflineStage1}) || !slices.Equal(base, []string{capLifetimes1, capRegionHA1, "names-2"}) {
t.Fatalf("region HA too: %v (base %v)", got, base)
}
for _, kv := range [][]string{
@@ -1132,11 +1132,11 @@ func TestOfflineDormantIsMain(t *testing.T) {
if json.Unmarshal(b1, &m1) != nil || json.Unmarshal(b2, &m2) != nil {
t.Fatal("edges files do not parse")
}
- if caps, _ := m2["capabilities"].([]any); len(caps) != 3 || caps[0] != capLifetimes1 || caps[1] != capOfflineMove1 || caps[2] != capOfflineStage1 {
+ if caps, _ := m2["capabilities"].([]any); len(caps) != 4 || caps[0] != capLifetimes1 || caps[1] != "names-2" || caps[2] != capOfflineMove1 || caps[3] != capOfflineStage1 {
t.Fatalf("capabilities: %v", m2["capabilities"])
}
// The plain file carries the lifetimes floor alone.
- if caps, _ := m1["capabilities"].([]any); len(caps) != 1 || caps[0] != capLifetimes1 {
+ if caps, _ := m1["capabilities"].([]any); len(caps) != 2 || caps[0] != capLifetimes1 || caps[1] != "names-2" {
t.Fatalf("fixture: the plain file's capabilities are %v", m1["capabilities"])
}
delete(m1, "capabilities")
diff --git a/internal/host/systemleg.go b/internal/host/systemleg.go
index 3396c851c..b035d82f1 100644
--- a/internal/host/systemleg.go
+++ b/internal/host/systemleg.go
@@ -14,6 +14,7 @@ import (
"runtime"
"time"
+ "github.com/carlosframework/platform/internal/edgesfile"
"github.com/carlosframework/platform/internal/release"
"github.com/carlosframework/platform/internal/version"
)
@@ -38,7 +39,10 @@ type systemLeg struct {
fetchTo func(ctx context.Context, key, dst, wantSHA256 string) error
logf func(format string, args ...any)
- pending *systemPending
+ readers func() edgesfile.ReaderSnapshot
+ namesRelease namesReleasePin
+ readerRefusedAt time.Time
+ 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
// the request, and root's own "deferred" — because they are all the same
@@ -81,7 +85,8 @@ func newSystemLeg(store release.Store, pub ed25519.PublicKey, getenv func(string
fetchTo: func(ctx context.Context, key, dst, wantSHA256 string) error {
return release.FetchToFile(ctx, store, key, dst, systemArtifactLimit, wantSHA256)
},
- logf: log.Printf,
+ logf: log.Printf,
+ namesRelease: firstNames2Release,
}
// Once, here at arming, rather than on every tick that reads the value.
if invalid != "" {
@@ -187,6 +192,13 @@ func (l *systemLeg) tick(ctx context.Context, now time.Time) {
if now.Before(p.deadline) || now.Before(l.backoffUntil) {
return
}
+ if l.readers != nil && !l.groupReaderTargetAllowed(p, now) {
+ if l.readerRefusedAt.IsZero() || now.Sub(l.readerRefusedAt) >= time.Minute {
+ l.printf("agent: system update %s refused: group reader capability or retirement evidence is unknown", p.version)
+ l.readerRefusedAt = now
+ }
+ return
+ }
if !p.requested {
if !p.noop {
if err := l.fetch(ctx, p); err != nil {
@@ -303,3 +315,34 @@ func (l *systemLeg) forget(version string) {
os.RemoveAll(filepath.Dir(systemCachePath(l.dataDir, version)))
}
}
+
+// firstNames2Release is deliberately unprepared. Release preparation pins the
+// first tag and independently verified artifact SHA-256s by platform here.
+// Add verified later/local/upload artifacts explicitly; a caller-supplied
+// version, even above FirstRelease, never grants reader capability.
+type namesReleasePin struct {
+ FirstRelease string
+ Digests map[string][]string
+}
+
+var firstNames2Release = namesReleasePin{}
+
+func (l *systemLeg) groupReaderTargetAllowed(p *systemPending, now time.Time) bool {
+ s := l.readers()
+ if !s.Fresh(now) {
+ return false
+ }
+ if !s.HasGroupNamespace() {
+ return true
+ }
+ floor, pinned := release.ParseReleaseVersion(l.namesRelease.FirstRelease)
+ if !pinned || release.BelowFloor(p.version, floor) {
+ return false
+ }
+ for _, digest := range l.namesRelease.Digests[l.platform] {
+ if len(digest) == 64 && digest == p.artifact.SHA256 {
+ return true
+ }
+ }
+ return false
+}
diff --git a/internal/host/systemleg_test.go b/internal/host/systemleg_test.go
index 56865a2ab..7629b8f6e 100644
--- a/internal/host/systemleg_test.go
+++ b/internal/host/systemleg_test.go
@@ -1,11 +1,14 @@
package host
import (
+ "bytes"
"context"
"crypto/ed25519"
"crypto/sha256"
"encoding/hex"
+ "encoding/json"
"errors"
+ "github.com/carlosframework/platform/internal/edgesfile"
"os"
"path/filepath"
"strings"
@@ -364,3 +367,174 @@ func TestFastTickRunsTheSystemLeg(t *testing.T) {
t.Fatalf("one serial move → %d observes", observes)
}
}
+
+// This first witness uses the signed pointer and the real artifact/root request path.
+func TestSystemLegGroupReaderRollback(t *testing.T) {
+ t.Run("paths", testSystemLegGroupReaderRollbackPaths)
+ f := newLegFixture(t, "stable", "v2")
+ f.promote("v1", []byte("old reader"), 0)
+ // A group is already published, including its retained namespace.
+ if _, err := f.store.Put(t.Context(), "control/edges/g-01234567890123456789.json", []byte(`{"v":1,"box":"g-01234567890123456789","region":"other","placement":"other-pool","box_role":"serve","admitted":true,"drained":false,"capabilities":["names-2"],"hosts":{"held.example":{"role":"home"}}}`), ""); err != nil {
+ t.Fatal(err)
+ }
+ e := readerFold(t, f.store)
+ f.leg.readers = e.GroupReaderSnapshot
+ f.now = time.Now()
+ f.leg.observe(t.Context())
+ f.leg.tick(t.Context(), f.now)
+ if f.request() != nil {
+ t.Error("old reader wrote root request with group publisher present")
+ }
+ if _, err := f.marker(); err == nil {
+ t.Error("old reader touched root marker")
+ }
+ if _, err := os.Stat(systemCachePath(f.dd, "v1")); err == nil {
+ t.Error("old reader fetched artifact")
+ }
+}
+
+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) {
+ f := newLegFixture(t, "stable", "v3")
+ f.now = time.Now()
+ target := "v1.0.0"
+ if tc == "unknown-upload" || tc == "fixed-upload" || tc == "verified-upload" {
+ target = "upload-abc123"
+ }
+ if tc == "unknown-newer-tag" {
+ target = "v999.0.0"
+ }
+ if tc == "verified" {
+ target = "v2.0.0"
+ }
+ body := []byte("target artifact")
+ f.promote(target, body, 0)
+ s := &readerStore{Store: f.store}
+ putGroup := func() {
+ role, admitted := "serve", true
+ if tc == "booting" || tc == "empty-booting" {
+ role, admitted = "booting", false
+ }
+ if tc == "standby" {
+ role, admitted = "drain", false
+ }
+ v := map[string]any{"v": 1, "box": "g-01234567890123456789", "region": "other-region", "placement": "other-pool", "box_role": role, "admitted": admitted, "drained": false, "capabilities": []string{"names-2"}, "hosts": map[string]any{"held.example": map[string]any{"role": "home"}}}
+ if tc == "empty-booting" {
+ v["hosts"] = map[string]any{}
+ }
+ if tc == "retained-no-dial" {
+ v["generation"] = "2000-01-01T00:00:00Z"
+ v["admitted"] = false
+ }
+ raw, _ := json.Marshal(v)
+ if _, err := s.Put(t.Context(), edgesfile.Key("g-01234567890123456789"), raw, ""); err != nil {
+ t.Fatal(err)
+ }
+ }
+ fixed := strings.HasPrefix(tc, "fixed-") || tc == "retired"
+ arrival := tc == "arrival-during-spread" || tc == "deferred" || tc == "retouch"
+ if !fixed && !arrival {
+ putGroup()
+ }
+ if tc == "retired" {
+ putGroup()
+ }
+ e := readerFold(t, s)
+ if tc == "retired" {
+ if !e.GroupReaderSnapshot().HasGroupNamespace() {
+ t.Fatal("retirement fixture never had a publisher")
+ }
+ if err := s.Delete(t.Context(), edgesfile.Key("g-01234567890123456789")); err != nil {
+ t.Fatal(err)
+ }
+ e.ArmHomeMap() // Task 8 must serialize this full readback with rollback.
+ }
+ snapshot := func() edgesfile.ReaderSnapshot {
+ sn := e.GroupReaderSnapshot()
+ switch tc {
+ case "missing-fold":
+ return edgesfile.ReaderSnapshot{}
+ case "stale-fold":
+ sn.CheckedAt = f.now.Add(-6 * time.Minute)
+ case "incomplete-fold":
+ sn.Complete = false
+ case "known-missing":
+ sn.KnownReaders = []string{"known-live"}
+ }
+ return sn
+ }
+ f.leg.readers = snapshot
+ // The reader must trust a verified digest, not the pointer's version.
+ sum := sha256.Sum256(body)
+ f.leg.namesRelease = namesReleasePin{FirstRelease: "v2.0.0", Digests: map[string][]string{"linux-arm64": {strings.Repeat("0", 64)}}}
+ if tc == "verified" || tc == "verified-upload" {
+ f.leg.namesRelease.Digests["linux-arm64"] = []string{hex.EncodeToString(sum[:])}
+ }
+ fetches := 0
+ fetch := f.leg.fetchTo
+ f.leg.fetchTo = func(c context.Context, key, dst, sha string) error { fetches++; return fetch(c, key, dst, sha) }
+ f.now = time.Now()
+ f.leg.observe(t.Context())
+ if f.leg.pending == nil {
+ t.Fatal("signed target did not arm")
+ }
+ if tc == "cached" {
+ p := systemCachePath(f.dd, target)
+ if err := os.MkdirAll(filepath.Dir(p), 0755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(p, body, 0644); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if tc == "deferred" || tc == "retouch" {
+ f.leg.tick(t.Context(), f.now)
+ if f.request() == nil {
+ t.Fatal("pre-group request missing")
+ }
+ if tc == "deferred" {
+ r := f.request()
+ if err := os.MkdirAll(systemRootDir(f.opt), 0755); err != nil {
+ t.Fatal(err)
+ }
+ if err := writeJSONDurable(filepath.Join(systemRootDir(f.opt), "result.json"), systemResult{Channel: "stable", Version: target, PromotedAt: r.PromotedAt, Outcome: systemOutcomeDeferred, At: f.now.Add(time.Second)}, 0644); err != nil {
+ t.Fatal(err)
+ }
+ }
+ }
+ if arrival {
+ putGroup()
+ e.ArmHomeMap()
+ }
+ if tc == "arrival-during-spread" {
+ f.leg.pending.deadline = f.now.Add(time.Minute)
+ }
+ // Snapshot timestamps follow actual read time; run ticks after that read.
+ at := time.Now().Add(2 * time.Minute)
+ beforeFetch, beforeGet, beforeList := fetches, s.gets, s.lists
+ requestBefore, _ := os.ReadFile(systemRequestPath(f.dd))
+ markerBefore, _ := os.ReadFile(filepath.Join(f.dd, systemRequestMarker))
+ f.leg.tick(t.Context(), at)
+ f.leg.tick(t.Context(), at.Add(10*time.Second))
+ allow := fixed || tc == "verified" || tc == "verified-upload"
+ if allow {
+ if f.request() == nil {
+ t.Fatal("permitted target did not request root")
+ }
+ if _, err := f.marker(); err != nil {
+ t.Fatal(err)
+ }
+ } else {
+ after, _ := os.ReadFile(systemRequestPath(f.dd))
+ marker, _ := os.ReadFile(filepath.Join(f.dd, systemRequestMarker))
+ if fetches != beforeFetch || !bytes.Equal(after, requestBefore) || !bytes.Equal(marker, markerBefore) {
+ t.Fatalf("refusal fetched=%d request=%q marker=%q", fetches-beforeFetch, after, marker)
+ }
+ }
+ if s.gets != beforeGet || s.lists != beforeList {
+ t.Fatal("gate added cloud reads")
+ }
+ })
+ }
+}