carlos / platform Public

region-ha p1b-3a: derive cold placement from cached fold

Project fresh compatible cold-wake candidates from the cached edges fold.
Preserve holder decoding and local safety denials, require mirrored signing
keys for peers, and copy headroom app counts without request-time reads.

Cover projection boundaries and malformed additions; refresh the cumulative
census proposal for independent review.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev fd1bc1561da82388baed91e13376d8d577c3de85 parent 095e25d
8 files changed, +594 −11
  • docs/superpowers/notes/census-proposal-region-ha-p1b3a.md +4 −3
  • docs/superpowers/notes/census-region-ha-p1b3a-claims.md +1 −0
  • internal/boxchoice/policy.go +3 −3
  • internal/edge/homemap.go +12 −1
  • internal/edge/wakeplacement.go +175 −0
  • internal/edge/wakeplacement_test.go +392 −0
  • internal/provision/testdata/plan14-root-reads-chain.tsv +1 −1
  • internal/provision/testdata/plan14-root-reads-region-ha-p1b3a.tsv +6 −3
diff --git a/docs/superpowers/notes/census-proposal-region-ha-p1b3a.md b/docs/superpowers/notes/census-proposal-region-ha-p1b3a.md
index 1ffe80332..ee32978f5 100644
--- a/docs/superpowers/notes/census-proposal-region-ha-p1b3a.md
+++ b/docs/superpowers/notes/census-proposal-region-ha-p1b3a.md
@@ -1,15 +1,16 @@
# Census approval: region-ha-p1b3a
-Ruling `census-ruling-region-ha-p1b3a`. The independent reviewer approves or rejects every change below, 1 with a new disposition; nothing goes to the census owner (Paul, #280, 2026-10-26).
+Ruling `census-ruling-region-ha-p1b3a`. The independent reviewer approves or rejects every change below, 2 with a new disposition; nothing goes to the census owner (Paul, #280, 2026-10-26).
-Envelopes re-pinned: `internal/activator`, `internal/boxchoice`, `internal/host`.
+Envelopes re-pinned: `internal/activator`, `internal/boxchoice`, `internal/edge`, `internal/host`.
Review: a model from the other family than the author reads the branch's diff against main on the amadan.net remote (`origin` or `amadan`, whichever points at amadan.net) and gives a verdict for every unit and every re-pinned envelope above. For a unit, compare the change with its recorded disposition and basis below; for an envelope, read every changed function in the package and what it reaches. Reject if the change lets root open, run, query or follow anything it did not before from a path or input a tenant, an app or a box agent can create, write or name; if it weakens a check, refusal, validation, argument or environment the basis relies on; or if the diff cannot settle either. Otherwise approve. Record each verdict on #280 with the tip. A rejected unit goes back to the author to correct; nothing escalates to the census owner.
New dispositions, which census-propose wrote and the reviewer checks against the unit's reads and the diff:
- new `internal/activator/awakeapps.go:Service.AwakeApps`: reads +registry:App, +whole:Route ×2; written legacy, accepted-legacy, frozen
+- new `internal/edge/wakeplacement.go:homeMap.wakeSnapshot`: reads +registry:App, +registry:Host, +whole:Route; written legacy, accepted-legacy, frozen
-Seal: `5f805400717bad7726bd9d62744b8103a40eb5f5823b0ab7c960a5c0965cb3bc` → `9be819eba3b4a4d2cb38a1ae4feaae4496cc057d1d93f9da6b1e950ce2dfccb8`.
+Seal: `5f805400717bad7726bd9d62744b8103a40eb5f5823b0ab7c960a5c0965cb3bc` → `d7a408934310184a8a042d299cd6456060460a95d5707d03af6dd28d93484cc7`.
Overlay: `internal/provision/testdata/plan14-root-reads-region-ha-p1b3a.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`.
diff --git a/docs/superpowers/notes/census-region-ha-p1b3a-claims.md b/docs/superpowers/notes/census-region-ha-p1b3a-claims.md
index 11720829e..afef3b5dd 100644
--- a/docs/superpowers/notes/census-region-ha-p1b3a-claims.md
+++ b/docs/superpowers/notes/census-region-ha-p1b3a-claims.md
@@ -1 +1,2 @@
internal/activator/awakeapps.go:Service.AwakeApps Count owned awake entries under the service mutex by release.RouteAccount(route)/route.App, validating the resolved account and app. Reads in-memory route values only; no store, registry or filesystem call and no new root authority.
+internal/edge/wakeplacement.go:homeMap.wakeSnapshot Project cold-wake candidates from one immutable cached edges fold using the local route's canonical host, release.RouteAccount and app. Reads only in-memory route fields, cached publication additions and mirrored signing keys; no filesystem, registry, store or root authority added. Reject malformed placement evidence independently of the unchanged holder decoder; preserve explicit local safety denials even when stale.
diff --git a/internal/boxchoice/policy.go b/internal/boxchoice/policy.go
index 7f704b7f1..41e3bacf9 100644
--- a/internal/boxchoice/policy.go
+++ b/internal/boxchoice/policy.go
@@ -44,9 +44,9 @@ func ExcludeRoles(cands []Candidate, roles map[string]string) []Candidate {
return out
}
-// headroomFresh reports whether a candidate's edges file is recent enough
+// HeadroomFresh reports whether a candidate's edges file is recent enough
// at now for its headroom to be trusted.
-func headroomFresh(generation string, now time.Time) bool {
+func HeadroomFresh(generation string, now time.Time) bool {
at, err := time.Parse(time.RFC3339, generation)
if err != nil {
return false
@@ -66,7 +66,7 @@ func Placeable(cands []Candidate, roles map[string]string, now time.Time) []Cand
switch {
case c.MemTotalMiB <= 0 || c.MemFreeMiB*100 < c.MemTotalMiB*MinMemPercent:
case c.DiskTotalMiB <= 0 || c.DiskFreeMiB*100 < c.DiskTotalMiB*MinDiskPercent:
- case !headroomFresh(c.Generation, now):
+ case !HeadroomFresh(c.Generation, now):
default:
out = append(out, c)
}
diff --git a/internal/edge/homemap.go b/internal/edge/homemap.go
index 02c193165..c49b7d676 100644
--- a/internal/edge/homemap.go
+++ b/internal/edge/homemap.go
@@ -154,6 +154,16 @@ type edgesFileView struct {
// (burst_notice.go). A box sends notices only to a file that says so:
// on an older box the notice path would reach a tenant's app.
BurstNotices bool `json:"burst_notices"`
+
+ // Placement additions are decoded separately so an invalid addition
+ // cannot remove a holder target from the existing fold.
+ Generation json.RawMessage `json:"generation"`
+ Capabilities json.RawMessage `json:"capabilities"`
+ HibernationConfigured json.RawMessage `json:"hibernation_configured"`
+ Draining json.RawMessage `json:"draining"`
+ Role json.RawMessage `json:"role"`
+ Drained json.RawMessage `json:"drained"`
+ Headroom json.RawMessage `json:"headroom"`
}
// dialPoint is f's dial fields, as edgesfile reads them.
@@ -171,7 +181,8 @@ func regionHAFromEnv(getenv func(string) string) bool {
// edgesHostView is the per-host object. An object rather than a bare string is
// what makes the role field addable without a wire break — see edgeRoleHome.
type edgesHostView struct {
- Role string `json:"role"`
+ Role string `json:"role"`
+ Replica json.RawMessage `json:"replica,omitempty"`
// Platform is the publisher's class mark (internal/host edgesfile.go):
// a platform-minted row. Absent on files written before the mark
// existed, which reads as "not platform" — fail closed for the one
diff --git a/internal/edge/wakeplacement.go b/internal/edge/wakeplacement.go
new file mode 100644
index 000000000..936a6ebc6
--- /dev/null
+++ b/internal/edge/wakeplacement.go
@@ -0,0 +1,175 @@
+package edge
+
+import (
+ "bytes"
+ "encoding/json"
+ "slices"
+ "time"
+
+ "github.com/carlosframework/platform/internal/boxchoice"
+ "github.com/carlosframework/platform/internal/edgesfile"
+ "github.com/carlosframework/platform/internal/registry"
+ "github.com/carlosframework/platform/internal/release"
+)
+
+// wakePlacementFields is a secondary view of additive placement evidence.
+// It never changes the strict decoder or compatibility policy for holders.
+type wakePlacementFields struct {
+ generation string
+ capabilities []string
+ configured bool
+ localDenied bool
+ headroom boxchoice.Headroom
+ valid bool
+}
+
+// placementField keeps absence distinct from an explicit null or wrong type.
+// Optional fields keep their caller-supplied defaults when absent.
+func placementField[T any](raw json.RawMessage, dst *T) bool {
+ return len(raw) == 0 || (!bytes.Equal(bytes.TrimSpace(raw), []byte("null")) && json.Unmarshal(raw, dst) == nil)
+}
+
+func decodeWakePlacement(f edgesFileView) wakePlacementFields {
+ p := wakePlacementFields{valid: true}
+ role := "serve"
+ var draining, drained bool
+ // Safety fields are read even when other evidence is invalid or stale.
+ roleOK := placementField(f.Role, &role)
+ drainingOK := placementField(f.Draining, &draining)
+ drainedOK := placementField(f.Drained, &drained)
+ p.localDenied = !roleOK || !drainingOK || !drainedOK || role != "serve" || draining || drained
+ p.valid = roleOK && drainingOK && drainedOK
+ p.valid = placementField(f.Generation, &p.generation) && p.valid
+ var capabilities []json.RawMessage
+ p.valid = placementField(f.Capabilities, &capabilities) && p.valid
+ for _, raw := range capabilities {
+ var capability string
+ p.valid = placementField(raw, &capability) && p.valid
+ p.capabilities = append(p.capabilities, capability)
+ }
+ p.valid = placementField(f.HibernationConfigured, &p.configured) && p.valid
+ if len(f.Headroom) == 0 {
+ return p
+ }
+ var h struct {
+ MemFreeMiB json.RawMessage `json:"mem_free_mib"`
+ MemTotalMiB json.RawMessage `json:"mem_total_mib"`
+ DiskFreeMiB json.RawMessage `json:"disk_free_mib"`
+ DiskTotalMiB json.RawMessage `json:"disk_total_mib"`
+ Awake json.RawMessage `json:"awake"`
+ Apps json.RawMessage `json:"apps"`
+ }
+ if !placementField(f.Headroom, &h) {
+ p.valid = false
+ return p
+ }
+ p.valid = placementField(h.MemFreeMiB, &p.headroom.MemFreeMiB) && p.valid
+ p.valid = placementField(h.MemTotalMiB, &p.headroom.MemTotalMiB) && p.valid
+ p.valid = placementField(h.DiskFreeMiB, &p.headroom.DiskFreeMiB) && p.valid
+ p.valid = placementField(h.DiskTotalMiB, &p.headroom.DiskTotalMiB) && p.valid
+ p.valid = placementField(h.Awake, &p.headroom.Awake) && p.valid
+ // Apps is advisory spread only. Bad maps never invalidate headroom.
+ var apps map[string]json.RawMessage
+ if placementField(h.Apps, &apps) {
+ counts := make(map[string]int, len(apps))
+ for app, raw := range apps {
+ var n int
+ if !placementField(raw, &n) {
+ return p
+ }
+ if n > 0 {
+ counts[app] = n
+ }
+ }
+ p.headroom.Apps = counts
+ }
+ return p
+}
+
+func (p wakePlacementFields) compatible(now time.Time) bool {
+ return p.valid && p.configured && slices.Contains(p.capabilities, boxchoice.Capability) && boxchoice.HeadroomFresh(p.generation, now)
+}
+
+func (p wakePlacementFields) candidate(f edgesFileView) boxchoice.Candidate {
+ return boxchoice.Candidate{
+ BoxID: f.Box, Region: f.Region, Generation: p.generation,
+ MemFreeMiB: p.headroom.MemFreeMiB, MemTotalMiB: p.headroom.MemTotalMiB,
+ DiskFreeMiB: p.headroom.DiskFreeMiB, DiskTotalMiB: p.headroom.DiskTotalMiB, Awake: p.headroom.Awake,
+ }
+}
+
+// wakeSnapshot projects one immutable fold for a local route. No membership,
+// registry or signing-key reads are made on the request path.
+func (m *homeMap) wakeSnapshot(rt registry.Route, now time.Time) boxchoice.WakeSnapshot {
+ var out boxchoice.WakeSnapshot
+ if m == nil {
+ return out
+ }
+ out.Enabled = m.privateDial
+ out.Self = m.self
+ snap := m.snapshot()
+ // Sorted keys make duplicate file evidence deterministic, as in foldHomes.
+ keys := make([]string, 0, len(snap.files))
+ for k := range snap.files {
+ keys = append(keys, k)
+ }
+ slices.Sort(keys)
+ var own edgesFileView
+ found := false
+ for _, k := range keys {
+ f := snap.files[k]
+ if m.self != "" && f.Box == m.self {
+ own = f
+ found = true
+ }
+ }
+ if !found {
+ return out
+ }
+ p := decodeWakePlacement(own)
+ out.LocalDenied = p.localDenied
+ out.Region = own.Region
+ if own.Region == "" || own.Placement == "" || own.DataBucket == "" || own.SecretsKeyFP == "" || !p.compatible(now) {
+ return out
+ }
+ out.Usable = true
+ out.Running = make(map[string]boxchoice.Load)
+ reader := edgesfile.Reader{Box: m.self, Self: own.dialPoint(), SelfKnown: true, PrivateDial: m.privateDial}
+ hasKey := len(signingKey(m.meshKeys())) > 0
+ host, account := canonicalizeHopHost(rt.Host), release.RouteAccount(rt)
+ // Collapse references using the same sorted last-file rule as the own file.
+ files := make(map[string]edgesFileView, len(keys))
+ for _, k := range keys {
+ f := snap.files[k]
+ files[f.Box] = f
+ }
+ refs := make([]string, 0, len(files))
+ for ref := range files {
+ refs = append(refs, ref)
+ }
+ slices.Sort(refs)
+ for _, ref := range refs {
+ f := files[ref]
+ if ref == "" || f.Region != own.Region || f.Placement != own.Placement || f.DataBucket != own.DataBucket || f.SecretsKeyFP != own.SecretsKeyFP {
+ continue
+ }
+ fields := decodeWakePlacement(f)
+ if !fields.compatible(now) || fields.localDenied {
+ continue
+ }
+ if ref != m.self {
+ if !hasKey || reader.Dial(f.dialPoint()) == "" {
+ continue
+ }
+ h, ok := f.Hosts[host]
+ var replica bool
+ if !ok || h.Role != edgeRoleHome || h.Alias || h.Wildcard || h.Account != account || h.App != rt.App || !placementField(h.Replica, &replica) || replica {
+ continue
+ }
+ }
+ out.Serving = append(out.Serving, fields.candidate(f))
+ // The decoder creates fresh maps, so returned loads cannot mutate the fold.
+ out.Running[ref] = boxchoice.Load{Hosts: fields.headroom.Awake, Apps: fields.headroom.Apps}
+ }
+ return out
+}
diff --git a/internal/edge/wakeplacement_test.go b/internal/edge/wakeplacement_test.go
new file mode 100644
index 000000000..d1f2bd90a
--- /dev/null
+++ b/internal/edge/wakeplacement_test.go
@@ -0,0 +1,392 @@
+package edge
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "reflect"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/boxchoice"
+ "github.com/carlosframework/platform/internal/registry"
+ "github.com/carlosframework/platform/internal/release"
+)
+
+var wakeNow = time.Date(2026, 11, 1, 12, 0, 0, 0, time.UTC)
+var wakeRoute = registry.Route{Host: "shop.example.com", Account: release.OpsAccount, App: "shop", HA: true}
+
+func wakeFile(ref string) map[string]any {
+ return map[string]any{
+ "v": 1, "box": ref, "box_id": "i-" + ref, "eip": "203.0.113.10",
+ "region": "ie", "placement": "hapair", "data_bucket": "data", "secrets_key_fp": "fp",
+ "generation": wakeNow.Format(time.RFC3339Nano), "capabilities": []string{boxchoice.Capability},
+ "hibernation_configured": true, "serves_shared_pool": false,
+ "hosts": map[string]any{wakeRoute.Host: map[string]any{"role": "home", "account": wakeRoute.Account, "app": wakeRoute.App}},
+ "headroom": map[string]any{"mem_free_mib": 50, "mem_total_mib": 100, "disk_free_mib": 50, "disk_total_mib": 100, "awake": 2, "apps": map[string]any{release.OpsAccount + "/shop": 2}},
+ }
+}
+
+func wakeBody(t *testing.T, f map[string]any) []byte {
+ t.Helper()
+ b, err := json.Marshal(f)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return b
+}
+
+func wakeMap(t *testing.T, files ...map[string]any) *homeMap {
+ t.Helper()
+ m := newHomeMap(nil, "self")
+ m.privateDial = true
+ m.keyCurrent = []byte("cached-key")
+ snap := &homeSnapshot{files: map[string]edgesFileView{}, read: true}
+ for i, f := range files {
+ key := fmt.Sprintf("control/edges/%d.json", i)
+ parsed, err := parseEdgesFile(key, wakeBody(t, f))
+ if err != nil {
+ t.Fatal(err)
+ }
+ snap.files[key] = parsed
+ }
+ snap.hosts, _ = foldHomes(snap.files, m.self, m.privateDial)
+ m.snap = snap
+ return m
+}
+
+func wakeRefs(s boxchoice.WakeSnapshot) []string {
+ refs := []string{}
+ for _, c := range s.Serving {
+ refs = append(refs, c.BoxID)
+ }
+ return refs
+}
+
+func wantWakeRefs(t *testing.T, m *homeMap, want ...string) boxchoice.WakeSnapshot {
+ t.Helper()
+ s := m.wakeSnapshot(wakeRoute, wakeNow)
+ if !s.Enabled || !s.Usable || s.Self != "self" || s.Region != "ie" {
+ t.Fatalf("unusable snapshot: %+v", s)
+ }
+ if got := wakeRefs(s); !reflect.DeepEqual(got, want) {
+ t.Fatalf("refs %v, want %v", got, want)
+ }
+ return s
+}
+
+func TestWakeSnapshotCompatibility(t *testing.T) {
+ for _, tc := range []struct {
+ name, field string
+ value any
+ }{
+ {"store", "data_bucket", "other"}, {"empty-store", "data_bucket", ""}, {"key", "secrets_key_fp", "other"}, {"empty-key", "secrets_key_fp", ""},
+ {"region", "region", "uk"}, {"placement", "placement", "other"}, {"capability", "capabilities", []string{}},
+ {"config", "hibernation_configured", false}, {"dial", "eip", ""}, {"draining", "draining", true}, {"drained", "drained", true}, {"role", "role", "booting"},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ peer := wakeFile("peer")
+ peer[tc.field] = tc.value
+ wantWakeRefs(t, wakeMap(t, wakeFile("self"), peer), "self")
+ })
+ }
+ wantWakeRefs(t, wakeMap(t, wakeFile("self"), wakeFile("peer")), "peer", "self")
+ for _, field := range []string{"data_bucket", "secrets_key_fp", "region", "placement", "generation", "capabilities", "hibernation_configured"} {
+ t.Run("own-missing-"+field, func(t *testing.T) {
+ own := wakeFile("self")
+ delete(own, field)
+ if s := wakeMap(t, own, wakeFile("peer")).wakeSnapshot(wakeRoute, wakeNow); s.Usable {
+ t.Fatalf("missing %s usable: %+v", field, s)
+ }
+ })
+ }
+ m := wakeMap(t, wakeFile("self"))
+ m.privateDial = false
+ if s := m.wakeSnapshot(wakeRoute, wakeNow); s.Enabled {
+ t.Fatal("switch off enabled placement")
+ }
+ if s := wakeMap(t, wakeFile("peer")).wakeSnapshot(wakeRoute, wakeNow); s.Usable {
+ t.Fatal("missing own file usable")
+ }
+ var nilMap *homeMap
+ if s := nilMap.wakeSnapshot(wakeRoute, wakeNow); s.Usable {
+ t.Fatal("nil map usable")
+ }
+}
+
+func TestWakeSnapshotRequiresSigningKey(t *testing.T) {
+ for _, key := range [][]byte{nil, {}, []byte("cached-key")} {
+ m := wakeMap(t, wakeFile("self"), wakeFile("peer"))
+ m.keyCurrent = key
+ want := []string{"self"}
+ if len(key) > 0 {
+ want = []string{"peer", "self"}
+ }
+ s := wantWakeRefs(t, m, want...)
+ if len(key) == 0 {
+ c, ok := boxchoice.ChooseColdWake(wakeRoute.Host, release.OpsAccount+"/shop", "", s, wakeNow)
+ if !ok || c.Ref != "self" {
+ t.Fatalf("no key prevented local HA choice: %+v %v", c, ok)
+ }
+ }
+ }
+ m := wakeMap(t, wakeFile("self"), wakeFile("peer"))
+ m.keyCurrent = nil
+ m.keyNext = []byte("next-key")
+ wantWakeRefs(t, m, "peer", "self")
+}
+
+func TestWakeSnapshotRequiresThePrimaryHost(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ host map[string]any
+ nameOverride string
+ }{
+ {"primary", map[string]any{"role": "home", "account": release.OpsAccount, "app": "shop"}, ""},
+ {"no-primary", nil, ""}, {"alias", map[string]any{"role": "home", "account": release.OpsAccount, "app": "shop", "alias": true}, ""},
+ {"cert", map[string]any{"role": "wildcard", "account": release.OpsAccount, "app": "shop"}, ""},
+ {"wildcard", map[string]any{"role": "home", "account": release.OpsAccount, "app": "shop", "wildcard": true}, ""},
+ {"pattern", map[string]any{"role": "home", "account": release.OpsAccount, "app": "shop"}, "*.example.com"},
+ {"replica", map[string]any{"role": "home", "account": release.OpsAccount, "app": "shop", "replica": true}, ""},
+ {"account", map[string]any{"role": "home", "account": "other", "app": "shop"}, ""},
+ {"app", map[string]any{"role": "home", "account": release.OpsAccount, "app": "other"}, ""},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ peer := wakeFile("peer")
+ hosts := map[string]any{}
+ name := wakeRoute.Host
+ if tc.nameOverride != "" {
+ name = tc.nameOverride
+ }
+ if tc.host != nil {
+ hosts[name] = tc.host
+ }
+ peer["hosts"] = hosts
+ want := []string{"self"}
+ if tc.name == "primary" {
+ want = []string{"peer", "self"}
+ }
+ wantWakeRefs(t, wakeMap(t, wakeFile("self"), peer), want...)
+ })
+ }
+}
+
+func TestWakeSnapshotSelfAdoptsBeforePublication(t *testing.T) {
+ own, peer := wakeFile("self"), wakeFile("peer")
+ own["hosts"] = map[string]any{}
+ peer["hosts"] = map[string]any{}
+ m := wakeMap(t, own, peer)
+ wantWakeRefs(t, m, "self")
+ rt := wakeRoute
+ rt.Host = "SHOP.EXAMPLE.COM.:443"
+ rt.Account = "legacy-account"
+ peer = wakeFile("peer")
+ m = wakeMap(t, own, peer)
+ if s := m.wakeSnapshot(rt, wakeNow); !reflect.DeepEqual(wakeRefs(s), []string{"peer", "self"}) {
+ t.Fatalf("canonical route: %+v", s)
+ }
+}
+
+func TestWakeSnapshotUsesBoxReference(t *testing.T) {
+ peer := wakeFile("peer")
+ peer["headroom"].(map[string]any)["mem_free_mib"] = 90
+ m := wakeMap(t, wakeFile("self"), peer)
+ s := wantWakeRefs(t, m, "peer", "self")
+ c, ok := boxchoice.ChooseColdWake(wakeRoute.Host, release.OpsAccount+"/shop", "peer", s, wakeNow)
+ if !ok || c.Ref != "peer" || s.Running["peer"].Apps[release.OpsAccount+"/shop"] != 2 {
+ t.Fatalf("wrong box reference: %+v %+v", c, s)
+ }
+ if _, ok := m.boxInView(c.Ref, wakeNow); !ok {
+ t.Fatal("choice fails holder view")
+ }
+ if _, ok := s.Running["i-peer"]; ok {
+ t.Fatal("load keyed by cloud id")
+ }
+}
+
+func TestWakeSnapshotFreshness(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ gen any
+ fresh bool
+ }{
+ {"past-boundary", wakeNow.Add(-15 * time.Minute).Format(time.RFC3339Nano), true},
+ {"past-outside", wakeNow.Add(-15*time.Minute - time.Nanosecond).Format(time.RFC3339Nano), false},
+ {"future-boundary", wakeNow.Add(time.Minute).Format(time.RFC3339Nano), true},
+ {"future-outside", wakeNow.Add(time.Minute + time.Nanosecond).Format(time.RFC3339Nano), false},
+ {"bad", "yesterday", false}, {"absent", nil, false},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ own := wakeFile("self")
+ if tc.gen == nil {
+ delete(own, "generation")
+ } else {
+ own["generation"] = tc.gen
+ }
+ if s := wakeMap(t, own).wakeSnapshot(wakeRoute, wakeNow); s.Usable != tc.fresh {
+ t.Fatalf("own usable=%v want %v", s.Usable, tc.fresh)
+ }
+ peer := wakeFile("peer")
+ if tc.gen == nil {
+ delete(peer, "generation")
+ } else {
+ peer["generation"] = tc.gen
+ }
+ want := []string{"self"}
+ if tc.fresh {
+ want = []string{"peer", "self"}
+ }
+ wantWakeRefs(t, wakeMap(t, wakeFile("self"), peer), want...)
+ })
+ }
+ for _, tc := range []struct {
+ field string
+ value any
+ }{{"role", "drain"}, {"role", "platform"}, {"role", 42}, {"role", nil}, {"draining", true}, {"draining", "bad"}, {"drained", true}, {"drained", []string{}}} {
+ t.Run(fmt.Sprintf("denied-%s-%v", tc.field, tc.value), func(t *testing.T) {
+ own := wakeFile("self")
+ own[tc.field] = tc.value
+ own["generation"] = wakeNow.Add(-time.Hour).Format(time.RFC3339)
+ s := wakeMap(t, own, wakeFile("peer")).wakeSnapshot(wakeRoute, wakeNow)
+ if !s.LocalDenied || s.Usable {
+ t.Fatalf("stale safety fields lost: %+v", s)
+ }
+ })
+ }
+ own := wakeFile("self")
+ own["role"] = "platform"
+ s := wantWakeRefs(t, wakeMap(t, own, wakeFile("peer")), "peer")
+ if !s.LocalDenied {
+ t.Fatal("non-serving self not denied")
+ }
+ // A failed refresh carries the original generation, not the refresh time.
+ store := meshTestStore(t)
+ own = wakeFile("self")
+ own["generation"] = wakeNow.Add(-15 * time.Minute).Format(time.RFC3339Nano)
+ putJSON(t, store, "control/edges/self.json", string(wakeBody(t, own)))
+ m := newHomeMap(store, "self")
+ m.privateDial = true
+ refreshHomeMap(t, m)
+ putJSON(t, store, "control/edges/self.json", `{"v":1,"generation":"new",`)
+ refreshHomeMap(t, m)
+ if m.partialPolls != 1 {
+ t.Fatal("malformed file was not carried forward")
+ }
+ if s := m.wakeSnapshot(wakeRoute, wakeNow.Add(time.Nanosecond)); s.Usable {
+ t.Fatal("carry-forward refreshed generation")
+ }
+}
+
+func TestWakeSnapshotMalformedAdditionsPreserveHolder(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ mutate func(map[string]any)
+ }{
+ {"generation", func(f map[string]any) { f["generation"] = 42 }},
+ {"capabilities", func(f map[string]any) { f["capabilities"] = true }},
+ {"null-capability", func(f map[string]any) { f["capabilities"] = []any{nil, boxchoice.Capability} }},
+ {"config", func(f map[string]any) { f["hibernation_configured"] = "yes" }},
+ {"draining", func(f map[string]any) { f["draining"] = "no" }},
+ {"role", func(f map[string]any) { f["role"] = false }},
+ {"drained", func(f map[string]any) { f["drained"] = 42 }},
+ {"headroom", func(f map[string]any) { f["headroom"] = true }},
+ {"mem-free", func(f map[string]any) { f["headroom"].(map[string]any)["mem_free_mib"] = "lots" }},
+ {"mem-total", func(f map[string]any) { f["headroom"].(map[string]any)["mem_total_mib"] = true }},
+ {"disk-free", func(f map[string]any) { f["headroom"].(map[string]any)["disk_free_mib"] = []int{} }},
+ {"disk-total", func(f map[string]any) { f["headroom"].(map[string]any)["disk_total_mib"] = nil }},
+ {"awake", func(f map[string]any) { f["headroom"].(map[string]any)["awake"] = "two" }},
+ {"replica", func(f map[string]any) {
+ f["hosts"].(map[string]any)[wakeRoute.Host].(map[string]any)["replica"] = "false"
+ }},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ peer := wakeFile("peer")
+ tc.mutate(peer)
+ m := wakeMap(t, wakeFile("self"), peer)
+ wantWakeRefs(t, m, "self")
+ if _, ok := m.boxInView("peer", wakeNow); !ok {
+ t.Fatal("malformed addition removed holder")
+ }
+ if addr, _, ok := m.Home(wakeRoute.Host); !ok || addr == "" {
+ t.Fatal("malformed addition removed folded home")
+ }
+ })
+ }
+ for _, apps := range []any{"bad", map[string]any{release.OpsAccount + "/shop": "bad"}, map[string]any{release.OpsAccount + "/shop": nil, release.OpsAccount + "/other": 3}, nil} {
+ peer := wakeFile("peer")
+ peer["headroom"].(map[string]any)["apps"] = apps
+ s := wantWakeRefs(t, wakeMap(t, wakeFile("self"), peer), "peer", "self")
+ if len(s.Running["peer"].Apps) != 0 || len(boxchoice.Placeable(s.Serving, nil, wakeNow)) != 2 {
+ t.Fatalf("bad apps invalidates core: %+v", s)
+ }
+ }
+ // Existing holder identity fields remain strict.
+ for _, field := range []string{"box", "region", "data_bucket", "secrets_key_fp"} {
+ f := wakeFile("peer")
+ f[field] = true
+ if _, err := parseEdgesFile("peer", wakeBody(t, f)); err == nil {
+ t.Fatalf("relaxed holder decoder for %s", field)
+ }
+ }
+}
+
+func TestWakeSnapshotHeadroomAndApps(t *testing.T) {
+ peer := wakeFile("peer")
+ delete(peer, "headroom")
+ m := wakeMap(t, wakeFile("self"), peer)
+ s := wantWakeRefs(t, m, "peer", "self")
+ if c := boxchoice.Placeable(s.Serving, nil, wakeNow); len(c) != 1 || c[0].BoxID != "self" {
+ t.Fatalf("missing headroom eligible: %+v", c)
+ }
+ peer = wakeFile("peer")
+ peer["headroom"].(map[string]any)["apps"] = map[string]any{release.OpsAccount + "/shop": -2, release.OpsAccount + "/other": 3}
+ m = wakeMap(t, wakeFile("self"), peer)
+ s = wantWakeRefs(t, m, "peer", "self")
+ if s.Running["peer"].Apps[release.OpsAccount+"/shop"] != 0 || s.Running["peer"].Apps[release.OpsAccount+"/other"] != 3 {
+ t.Fatalf("negative spread: %+v", s.Running)
+ }
+ s.Running["peer"].Apps[release.OpsAccount+"/other"] = 99
+ delete(s.Running, "self")
+ s.Serving[0].MemFreeMiB = 999
+ next := m.wakeSnapshot(wakeRoute, wakeNow)
+ if next.Running["peer"].Apps[release.OpsAccount+"/other"] != 3 || next.Serving[0].MemFreeMiB != 50 || len(next.Running) != 2 {
+ t.Fatal("projection mutated immutable fold")
+ }
+}
+
+type wakeNoIOStore struct {
+ release.Store
+ calls int
+}
+
+func (s *wakeNoIOStore) Get(context.Context, string) ([]byte, string, error) {
+ s.calls++
+ return nil, "", fmt.Errorf("unexpected GET")
+}
+func (s *wakeNoIOStore) List(context.Context, string) ([]string, error) {
+ s.calls++
+ return nil, fmt.Errorf("unexpected LIST")
+}
+func (s *wakeNoIOStore) ListDirs(context.Context, string) ([]string, error) {
+ s.calls++
+ return nil, fmt.Errorf("unexpected ListDirs")
+}
+func (s *wakeNoIOStore) Put(context.Context, string, []byte, string) (string, error) {
+ s.calls++
+ return "", fmt.Errorf("unexpected PUT")
+}
+func (s *wakeNoIOStore) Delete(context.Context, string) error {
+ s.calls++
+ return fmt.Errorf("unexpected DELETE")
+}
+func TestWakeSnapshotNoIO(t *testing.T) {
+ m := wakeMap(t, wakeFile("self"), wakeFile("peer"))
+ store := &wakeNoIOStore{}
+ m.s = store
+ for i := 0; i < 100; i++ {
+ wantWakeRefs(t, m, "peer", "self")
+ }
+ if store.calls != 0 {
+ t.Fatalf("projection made %d store calls", store.calls)
+ }
+}
diff --git a/internal/provision/testdata/plan14-root-reads-chain.tsv b/internal/provision/testdata/plan14-root-reads-chain.tsv
index 453a14607..67cdf29b3 100644
--- a/internal/provision/testdata/plan14-root-reads-chain.tsv
+++ b/internal/provision/testdata/plan14-root-reads-chain.tsv
@@ -56,4 +56,4 @@ plan14-root-reads-fix-set-aside-exdev.tsv f9d3016cc6803338f9db19311f3f598e20c37c
plan14-root-reads-durability-3a-escrow.tsv 03a92257beb9b8aac421559e247d191bd69f28a0b26243397a1344a90d59fc2a
plan14-root-reads-rootfs-default-home.tsv 7a0a3da3d6fe7e3c77abb22676db000af2a276c3d13ccae0f038190f51287ed5
plan14-root-reads-probe-burst-limit.tsv 5f805400717bad7726bd9d62744b8103a40eb5f5823b0ab7c960a5c0965cb3bc
-plan14-root-reads-region-ha-p1b3a.tsv 9be819eba3b4a4d2cb38a1ae4feaae4496cc057d1d93f9da6b1e950ce2dfccb8
+plan14-root-reads-region-ha-p1b3a.tsv d7a408934310184a8a042d299cd6456060460a95d5707d03af6dd28d93484cc7
diff --git a/internal/provision/testdata/plan14-root-reads-region-ha-p1b3a.tsv b/internal/provision/testdata/plan14-root-reads-region-ha-p1b3a.tsv
index 79e764d83..6e2f3e80f 100644
--- a/internal/provision/testdata/plan14-root-reads-region-ha-p1b3a.tsv
+++ b/internal/provision/testdata/plan14-root-reads-region-ha-p1b3a.tsv
@@ -1,8 +1,11 @@
# Census overlay region-ha-p1b3a, written by census-propose (#369). census-ruling-region-ha-p1b3a, approved on #280 before the merge; the approval card is docs/superpowers/notes/census-proposal-region-ha-p1b3a.md.
-# 0 body, 0 sites, 3 envelope: each changed unit re-frozen at its existing disposition with its claim appended.
-# 1 new dispositions: 0 reads re-frozen at their disposition with the claim, 1 new units frozen accepted-legacy, 0 quiet units retired while they read nothing, 0 other.
+# 0 body, 0 sites, 4 envelope: each changed unit re-frozen at its existing disposition with its claim appended.
+# 2 new dispositions: 0 reads re-frozen at their disposition with the claim, 2 new units frozen accepted-legacy, 0 quiet units retired while they read nothing, 0 other.
@legacy 2ffbb58e2568a1ea38d893670ab9498c6581af1aeba74e5a4d78cc5327e531cd internal/activator/awakeapps.go Service.AwakeApps legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p1b3a;basis=Count owned awake entries under the service mutex by release.RouteAccount(route)/route.App, validating the resolved account and app. Reads in-memory route values only; no store, registry or filesystem call and no new root authority. registry:App@242,whole:Route@234,whole:Route@244 1eb4a8a36fdcb246f031482676c6af586cb1ecbeabc07271c9d3021ecf355a60
+@legacy bcd9a0aa6e0e449a3900fba77c971ed0f5b06020c3d1d3af34660571f94539a5 internal/edge/wakeplacement.go homeMap.wakeSnapshot legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p1b3a;basis=Project cold-wake candidates from one immutable cached edges fold using the local route's canonical host, release.RouteAccount and app. Reads only in-memory route fields, cached publication additions and mirrored signing keys; no filesystem, registry, store or root authority added. Reject malformed placement evidence independently of the unchanged holder decoder; preserve explicit local safety denials even when stale. registry:App@1984,registry:Host@1089,whole:Route@1120 4d138a61f816bdd353cbe52d0b3620040b6bb1b2ab04d9c13910460b92b819e3
internal/activator/awakeapps.go Service.AwakeApps legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p1b3a;basis=Count owned awake entries under the service mutex by release.RouteAccount(route)/route.App, validating the resolved account and app. Reads in-memory route values only; no store, registry or filesystem call and no new root authority. registry:App@242,whole:Route@234,whole:Route@244 1eb4a8a36fdcb246f031482676c6af586cb1ecbeabc07271c9d3021ecf355a60
+internal/edge/wakeplacement.go homeMap.wakeSnapshot legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p1b3a;basis=Project cold-wake candidates from one immutable cached edges fold using the local route's canonical host, release.RouteAccount and app. Reads only in-memory route fields, cached publication additions and mirrored signing keys; no filesystem, registry, store or root authority added. Reject malformed placement evidence independently of the unchanged holder decoder; preserve explicit local safety denials even when stale. registry:App@1984,registry:Host@1089,whole:Route@1120 4d138a61f816bdd353cbe52d0b3620040b6bb1b2ab04d9c13910460b92b819e3
@coverage internal/activator b9b984a8634f6783c82923f8e4736ef41aa8087dc2e748fc6e30f8645eb0ce7f
-@coverage internal/boxchoice 893e5d5af6d33ae731a34ba70c343836f5ae9f49f4da891a47a24d6a257bb7e1
+@coverage internal/boxchoice 2461971eb41338ab53f0c7c77c0e01b1e0b854f657a1cecddfbaf6c142f0feed
+@coverage internal/edge 13a04521bd87e65f83c1cb041cc72fc997082f84881a94c8aa74fe6752b46180
@coverage internal/host 827414424edca7b51415e327c5ce0c9d95a30a4bbe7f0eb418fdc03ddc77538b