carlos / platform Public

edge: re-check open upgrades on home map and mesh key changes (#186)

Whole-branch review R1 P2-3 (Paul, rule 2: connect the triggers). The
upgrade re-check reads the home map's name authority and whether a mesh
key is mirrored, but sweepUpgrades ran only from Reload, so a held case 3
upgrade outlived its front being re-owned until an unrelated reload.

refreshHosts now wakes the sweep when the snapshot's ownership inputs
changed (the fold, the read flag, this box's admission posture), and
refreshKeys when the key pair changed, through an upgradeWake hook that
newHomeMap sets to the edge's sweepUpgrades; ArmHomeMap sweeps after
installing its map. The wake runs with refreshMu held and the map's mu
and keyMu released: refreshMu -> open.mu -> homeMap.mu/keyMu, beside
Reload's reloadMu -> open.mu -> ...; documented in upgradetriggers.go.

TestUpgradeInputsHaveSweepTriggers walks upgradeSelection's call graph
with types, collects every Edge and homeMap field it reads, and requires
a row for each: inputs name their writers and the trigger each calls.
Witnesses change only remote state through the production-wired map's
refresh: a re-owned front, and a newly mirrored mesh key, each cancel a
held upgrade with no Reload or sweepUpgrades call.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev ea5800d52e477d9053fe89e4fd072b77fcacdc09 parent 6d692fe
5 files changed, +494 −3
  • internal/edge/homemap.go +17 −2
  • internal/edge/reload_guard_test.go +9 −1
  • internal/edge/upgrade_triggers_guard_test.go +264 −0
  • internal/edge/upgrade_triggers_test.go +136 −0
  • internal/edge/upgradetriggers.go +68 −0
diff --git a/internal/edge/homemap.go b/internal/edge/homemap.go
index 639abb937..faa6375b9 100644
--- a/internal/edge/homemap.go
+++ b/internal/edge/homemap.go
@@ -358,6 +358,11 @@ type homeMap struct {
// because their filters are opposites: hostsWake ignores exactly the
// unclassed rows a custom domain arrives as.
servedWake func()
+ // upgradeWake re-checks the edge's open upgrades (Edge.sweepUpgrades,
+ // set by newHomeMap before the first refresh and never after): run when
+ // a refresh changed an input of their ownership re-check (the
+ // snapshot's, or the mesh keys; upgradetriggers.go).
+ upgradeWake func()
// partialPolls counts polls that could not read (or parse) every object,
// for the first-and-every-tenth log cadence.
partialPolls int
@@ -452,6 +457,7 @@ func (e *Edge) newHomeMap() *homeMap {
m.departureTick = e.departureTick
m.peerDrained = e.runPeerDrained
m.peerUndrained = e.runPeerUndrained
+ m.upgradeWake = e.sweepUpgrades
return m
}
@@ -473,6 +479,9 @@ func (e *Edge) ArmHomeMap() (run func(stop <-chan struct{})) {
}
cancel()
e.homes.Store(hm)
+ // The installed map is an input of every open upgrade's re-check
+ // (upgradetriggers.go).
+ e.sweepUpgrades()
return hm.run
}
@@ -681,6 +690,9 @@ func (m *homeMap) refreshHosts(ctx context.Context) error {
// parse is retried on the next poll, as it always was.
m.lastHosts, m.hostsAge = m.clock(), jitteredBackstop()
m.actedGen, m.actedOK = gen, genOK && failed == 0
+ if ownershipInputsChanged(prev, snap, m.self) {
+ m.wakeUpgrades()
+ }
if wake != nil && !samePlatformSet(prev.hosts, snap.hosts) {
// The deployment's platform name set moved: a wildcard parent may
// have appeared for an account homed elsewhere (#300). Off this
@@ -1271,8 +1283,7 @@ func (m *homeMap) resolveName(host string, local []edgesfile.NameClaim, exact bo
if m != nil && m.self != "" {
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 {
+ if snap.ownAdmissionAware(m.self) {
local = slices.Clone(local)
for i := range local {
local[i].AdmissionAware = true
@@ -1425,8 +1436,12 @@ func (m *homeMap) refreshKeys(ctx context.Context) error {
return err
}
m.keyMu.Lock()
+ changed := meshKeysChanged(m.keyCurrent, m.keyNext, current, next)
m.keyCurrent, m.keyNext = current, next
m.keyMu.Unlock()
+ if changed {
+ m.wakeUpgrades()
+ }
return nil
}
diff --git a/internal/edge/reload_guard_test.go b/internal/edge/reload_guard_test.go
index dccc0e855..2d4927acd 100644
--- a/internal/edge/reload_guard_test.go
+++ b/internal/edge/reload_guard_test.go
@@ -155,7 +155,15 @@ func TestReloadIsTheOnlyPublisher(t *testing.T) {
}
only("e.upstreams.Store", stores, 1)
only("SetDynamicAuth or SetLinkAuth", dynAuth, 0)
- only("sweepUpgrades", sweeps, 1)
+ // The sweep's other triggers (ArmHomeMap's, and the home map's wake
+ // through the hook newHomeMap sets) are TestUpgradeInputsHaveSweepTriggers'.
+ var reloadSweeps []site
+ for _, s := range sweeps {
+ if s.fn != "(*Edge).ArmHomeMap" {
+ reloadSweeps = append(reloadSweeps, s)
+ }
+ }
+ only("sweepUpgrades", reloadSweeps, 1)
only("reloadMu", reloadMu, 0)
if t.Failed() {
return
diff --git a/internal/edge/upgrade_triggers_guard_test.go b/internal/edge/upgrade_triggers_guard_test.go
new file mode 100644
index 000000000..a06bc2764
--- /dev/null
+++ b/internal/edge/upgrade_triggers_guard_test.go
@@ -0,0 +1,264 @@
+package edge
+
+// TestUpgradeInputsHaveSweepTriggers (whole-branch review R1 P2-3; Paul,
+// rule 2, 2026-11-21): every input an open upgrade's re-check reads has a
+// trigger that re-runs it (upgradetriggers.go). A typed source check over
+// this package's non-test files: it walks the static call graph from
+// upgradeSelection (selectUpstream, nameOwnerVerdict and everything they
+// call here), collects every field of Edge and homeMap read on the way,
+// and fails when one has no row below. For an input row, every function
+// that writes the field must be one of the row's writers, and each writer
+// must call its trigger. A new input, or a new writer of an existing one,
+// fails here by name until it is connected.
+
+import (
+ "go/ast"
+ "go/types"
+ "path/filepath"
+ "slices"
+ "strings"
+ "testing"
+
+ "golang.org/x/tools/go/packages"
+)
+
+// upgradeInput is one field the re-check reads. writers maps each function
+// allowed to write it (objName: "Edge.Reload") to the trigger it must call
+// ("Edge.sweepUpgrades", "homeMap.wakeUpgrades"), or "" with why that write
+// needs none. fixed, instead, says why the field is no input at all; a
+// fixed row with writers (empty: only the struct literal that builds it)
+// still has its writes checked, a fixed row without (a lock, the log's
+// counters) does not.
+type upgradeInput struct {
+ writers map[string]string
+ fixed string
+}
+
+var upgradeInputs = map[string]upgradeInput{
+ // The inputs.
+ "Edge.upstreams": {writers: map[string]string{"Edge.Reload": "Edge.sweepUpgrades"}},
+ "Edge.homes": {writers: map[string]string{"Edge.ArmHomeMap": "Edge.sweepUpgrades"}},
+ "homeMap.snap": {writers: map[string]string{
+ "homeMap.refreshHosts": "homeMap.wakeUpgrades",
+ "homeMap.refresh": "", // copies the published snapshot, changing only the reader gate's fields (readerComplete, readerCheckedAt)
+ "homeMap.noteGroupPublisher": "", // copies it, changing only groupObserved and readerComplete
+ }},
+ "homeMap.keyCurrent": {writers: map[string]string{"homeMap.refreshKeys": "homeMap.wakeUpgrades"}},
+ "homeMap.keyNext": {writers: map[string]string{"homeMap.refreshKeys": "homeMap.wakeUpgrades"}},
+ // Not inputs.
+ "Edge.box": {fixed: "this box's label, set when the edge is built", writers: map[string]string{"WithBoxLabel": ""}},
+ "Edge.demo": {fixed: "the demo configuration, set when the edge is built", writers: map[string]string{}},
+ "Edge.logMu": {fixed: "the throttled log's lock (pathSkip)"},
+ "Edge.logN": {fixed: "the throttled log's counters (pathSkip)"},
+ "homeMap.self": {fixed: "this box's label, set when the map is built", writers: map[string]string{}},
+ "homeMap.mu": {fixed: "the snapshot's lock"},
+ "homeMap.keyMu": {fixed: "the mesh keys' lock"},
+}
+
+func TestUpgradeInputsHaveSweepTriggers(t *testing.T) {
+ dir, err := filepath.Abs(".")
+ if err != nil {
+ t.Fatal(err)
+ }
+ pkgs, err := packages.Load(&packages.Config{Dir: dir,
+ Mode: packages.NeedName | packages.NeedFiles | packages.NeedCompiledGoFiles | packages.NeedSyntax | packages.NeedTypes | packages.NeedTypesInfo}, ".")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(pkgs) != 1 || len(pkgs[0].Errors) > 0 {
+ t.Fatalf("load: %d packages, errors %v", len(pkgs), pkgs[0].Errors)
+ }
+ pkg := pkgs[0]
+ info := pkg.TypesInfo
+ decls := map[types.Object]*ast.FuncDecl{}
+ for _, f := range pkg.Syntax {
+ for _, d := range f.Decls {
+ if fd, ok := d.(*ast.FuncDecl); ok && fd.Body != nil {
+ decls[info.Defs[fd.Name]] = fd
+ }
+ }
+ }
+ // fieldOf names the Edge or homeMap field sel selects, or "".
+ fieldOf := func(sel *ast.SelectorExpr) string {
+ s, ok := info.Selections[sel]
+ if !ok || s.Kind() != types.FieldVal {
+ return ""
+ }
+ recv := s.Recv()
+ if p, ok := recv.(*types.Pointer); ok {
+ recv = p.Elem()
+ }
+ n, ok := recv.(*types.Named)
+ if !ok || n.Obj().Pkg() != pkg.Types || (n.Obj().Name() != "Edge" && n.Obj().Name() != "homeMap") {
+ return ""
+ }
+ return n.Obj().Name() + "." + sel.Sel.Name
+ }
+
+ // The re-check's reads.
+ root := pkg.Types.Scope().Lookup("Edge").Type().(*types.Named)
+ var start types.Object
+ for i := 0; i < root.NumMethods(); i++ {
+ if root.Method(i).Name() == "upgradeSelection" {
+ start = root.Method(i)
+ }
+ }
+ if start == nil || decls[start] == nil {
+ t.Fatal("no (*Edge).upgradeSelection to walk from")
+ }
+ reads := map[string]string{} // field -> first function seen reading it
+ seen := map[types.Object]bool{}
+ var walk func(obj types.Object)
+ walk = func(obj types.Object) {
+ fd := decls[obj]
+ if fd == nil || seen[obj] {
+ return
+ }
+ seen[obj] = true
+ ast.Inspect(fd.Body, func(n ast.Node) bool {
+ switch v := n.(type) {
+ case *ast.CallExpr:
+ if c := calleeObj(info, v); c != nil {
+ walk(c)
+ }
+ case *ast.SelectorExpr:
+ if f := fieldOf(v); f != "" && reads[f] == "" {
+ reads[f] = objName(obj)
+ }
+ }
+ return true
+ })
+ }
+ walk(start)
+ walked := map[string]bool{}
+ for o := range seen {
+ walked[objName(o)] = true
+ }
+ for _, must := range []string{"Edge.nameOwnerVerdict", "Edge.selectUpstream", "homeMap.exactPathRoute", "homeMap.resolveName", "homeMap.meshKeys"} {
+ if !walked[must] {
+ t.Errorf("the walk from upgradeSelection never reached %s: the scan has nothing to anchor on", must)
+ }
+ }
+ for f, by := range reads {
+ if _, ok := upgradeInputs[f]; !ok {
+ t.Errorf("the upgrade re-check reads %s (in %s), which has no row in upgradeInputs: connect a sweep trigger to its writers, or say why it is no input", f, by)
+ }
+ }
+
+ // Every write of an input, and every trigger call.
+ writes := map[string]map[string]bool{} // field -> writer -> true
+ calls := map[string]map[string]bool{} // function -> callee -> true
+ noteWrite := func(x ast.Expr, fn string) {
+ if sel, ok := ast.Unparen(x).(*ast.SelectorExpr); ok {
+ if f := fieldOf(sel); f != "" {
+ if writes[f] == nil {
+ writes[f] = map[string]bool{}
+ }
+ writes[f][fn] = true
+ }
+ }
+ }
+ for obj, fd := range decls {
+ fn := objName(obj)
+ ast.Inspect(fd.Body, func(n ast.Node) bool {
+ switch v := n.(type) {
+ case *ast.AssignStmt:
+ for _, l := range v.Lhs {
+ noteWrite(l, fn)
+ }
+ case *ast.UnaryExpr:
+ // &e.field handed on can be written through.
+ noteWrite(v.X, fn)
+ case *ast.CallExpr:
+ c := calleeObj(info, v)
+ if c == nil {
+ return true
+ }
+ if calls[fn] == nil {
+ calls[fn] = map[string]bool{}
+ }
+ calls[fn][objName(c)] = true
+ // e.homes.Store(hm): a write through an atomic field.
+ if se, ok := ast.Unparen(v.Fun).(*ast.SelectorExpr); ok && slices.Contains([]string{"Store", "Swap", "CompareAndSwap"}, se.Sel.Name) {
+ noteWrite(se.X, fn)
+ }
+ }
+ return true
+ })
+ }
+ for f, in := range upgradeInputs {
+ if in.writers == nil {
+ continue
+ }
+ if in.fixed == "" && len(writes[f]) == 0 {
+ t.Errorf("%s: no writer found; the scan has nothing to anchor on", f)
+ }
+ for w := range writes[f] {
+ trig, ok := in.writers[w]
+ if !ok {
+ t.Errorf("%s is written in %s, which is not one of its writers: run its sweep trigger there and add it to upgradeInputs", f, w)
+ continue
+ }
+ if trig != "" && !calls[w][trig] {
+ t.Errorf("%s is written in %s, which does not call its trigger %s", f, w, trig)
+ }
+ }
+ }
+
+ // The home map's trigger reaches the sweep: wakeUpgrades calls the
+ // upgradeWake hook, which only newHomeMap (the edge's own map) sets,
+ // to the edge's sweepUpgrades.
+ if !strings.Contains(callsOf(t, decls, "homeMap.wakeUpgrades"), "upgradeWake") {
+ t.Error("homeMap.wakeUpgrades does not call the upgradeWake hook")
+ }
+ for w := range writes["homeMap.upgradeWake"] {
+ if w != "Edge.newHomeMap" {
+ t.Errorf("homeMap.upgradeWake is set in %s; only Edge.newHomeMap may set it", w)
+ }
+ }
+ var wired bool
+ for obj, fd := range decls {
+ if objName(obj) != "Edge.newHomeMap" {
+ continue
+ }
+ ast.Inspect(fd.Body, func(n ast.Node) bool {
+ as, ok := n.(*ast.AssignStmt)
+ if !ok || len(as.Lhs) != 1 || len(as.Rhs) != 1 {
+ return true
+ }
+ l, ok := as.Lhs[0].(*ast.SelectorExpr)
+ r, rok := as.Rhs[0].(*ast.SelectorExpr)
+ if ok && rok && fieldOf(l) == "homeMap.upgradeWake" {
+ if s, ok := info.Selections[r]; ok && s.Kind() == types.MethodVal && objName(s.Obj()) == "Edge.sweepUpgrades" {
+ wired = true
+ }
+ }
+ return true
+ })
+ }
+ if !wired {
+ t.Error("Edge.newHomeMap does not set the map's upgradeWake to the edge's sweepUpgrades")
+ }
+}
+
+// callsOf is the source text of the named function's body, for a crude
+// containment check.
+func callsOf(t *testing.T, decls map[types.Object]*ast.FuncDecl, name string) string {
+ t.Helper()
+ var out []string
+ for obj, fd := range decls {
+ if objName(obj) != name {
+ continue
+ }
+ ast.Inspect(fd.Body, func(n ast.Node) bool {
+ if se, ok := n.(*ast.SelectorExpr); ok {
+ out = append(out, se.Sel.Name)
+ }
+ return true
+ })
+ }
+ if out == nil {
+ t.Errorf("no %s in the package", name)
+ }
+ return strings.Join(out, " ")
+}
diff --git a/internal/edge/upgrade_triggers_test.go b/internal/edge/upgrade_triggers_test.go
new file mode 100644
index 000000000..91f379a5c
--- /dev/null
+++ b/internal/edge/upgrade_triggers_test.go
@@ -0,0 +1,136 @@
+package edge
+
+// Whole-branch review R1 P2-3 (Paul, rule 2, 2026-11-21: connect the
+// triggers): an open upgrade is re-checked (sweepUpgrades) whenever an
+// input its re-check reads changes, not only on a registry Reload. These
+// witnesses change only remote state, through the home map's own refresh
+// on a production-wired map (ArmHomeMap), and never call Reload or
+// sweepUpgrades after the reservation.
+
+import (
+ "context"
+ "fmt"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/registry"
+)
+
+const (
+ trigFront = "hub.tunnel.example"
+ trigTarget = "t.example.com"
+)
+
+var trigTenancy = tenancy{ArmTunnel, fwdOther, "blog", "", "t1", ""}
+
+// triggerScene is a hub ("annie") serving trigTarget over a tunnel, with
+// trigFront's remote map (acme -> trigTarget) and a production-wired home
+// map (ArmHomeMap over the deployment store) in which betty publishes
+// trigFront as a front route of the target's account. keyed mints a mesh
+// key first. catchAll also gives the hub *.tunnel.example -> trigTarget.
+func triggerScene(t *testing.T, keyed, catchAll bool) (hub *Edge, tc *tunnelConn) {
+ t.Helper()
+ _, hub, _ = forwardHubAndBox(t, []registry.Route{
+ {Host: trigTarget, Kind: "instance", Status: "ready", Tunnel: "t1", Account: fwdOther, App: "blog"},
+ }, nil, namedHandler("box-1"))
+ remotePathRow(t, hub.reg, trigFront, acrossPrefix, trigTarget, fwdOther, "hub")
+ if catchAll {
+ if err := hub.reg.UpsertAlias(registry.RouteAlias{Alias: "*.tunnel.example", Host: trigTarget, Account: fwdOther, App: "blog"}); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if err := hub.Reload(); err != nil {
+ t.Fatal(err)
+ }
+ hub.staticStore, hub.box = meshTestStore(t), "annie"
+ if keyed {
+ if err := MintMeshKey(t.Context(), hub.staticStore); err != nil {
+ t.Fatal(err)
+ }
+ }
+ trigPublish(t, hub, frontRow(fwdOther, "hub"))
+ if hub.ArmHomeMap() == nil {
+ t.Fatal("no home map armed")
+ }
+ if tc = hub.tunnels.channel("home/box-1"); tc == nil {
+ t.Fatal("home/box-1 has no channel connection")
+ }
+ return hub, tc
+}
+
+// trigPublish writes betty's edges file naming trigFront with entry.
+func trigPublish(t *testing.T, hub *Edge, entry string) {
+ t.Helper()
+ putJSON(t, hub.staticStore, "control/edges/betty.json",
+ fmt.Sprintf(`{"v":1,"box":"betty","eip":"2.2.2.2","hosts":{%q:%s}}`, trigFront, entry))
+}
+
+// wantReleased waits for r's stream context to end (a sweep's release
+// cancels it first), bounded so a missing trigger fails rather than hangs.
+func wantReleased(t *testing.T, ctx context.Context, r *upgradeReservation, what string) {
+ t.Helper()
+ select {
+ case <-ctx.Done():
+ case <-time.After(5 * time.Second):
+ t.Fatalf("%s: the held upgrade was not released", what)
+ }
+ if by := r.firstReleaser(); by != relSweep {
+ t.Fatalf("%s: released by %v, want the sweep", what, by)
+ }
+}
+
+// A case 3 upgrade admitted for trigFront's prefix in the target's account
+// is cancelled once a home-map refresh shows trigFront owned by another
+// account: the target box's registry is unchanged and nothing reloads.
+func TestUpgradeSweptByHomeMapRefresh(t *testing.T) {
+ hub, tc := triggerScene(t, true, false)
+ r, ctx, err := hub.reserveUpgrade(context.Background(), upgradeAdmission{Host: trigFront, Path: "/acme/cable", Tenancy: trigTenancy}, tc, 10)
+ if err != nil {
+ t.Fatalf("reserve for a case 3 target: %v, want admitted", err)
+ }
+ defer r.release(relBody) // also waits for the sweep's release to finish
+ // A refresh that changes nothing keeps it.
+ if err := hub.homes.Load().Refresh(context.Background()); err != nil {
+ t.Fatal(err)
+ }
+ if n := heldFor(hub, trigFront); n != 1 || ctx.Err() != nil {
+ t.Fatalf("after an unchanged refresh: %d held (ctx %v), want 1", n, ctx.Err())
+ }
+ trigPublish(t, hub, frontRow(fwdOwner, "other"))
+ if err := hub.homes.Load().Refresh(context.Background()); err != nil {
+ t.Fatal(err)
+ }
+ wantReleased(t, ctx, r, "after the front was re-owned")
+ if n := heldFor(hub, trigFront); n != 0 {
+ t.Fatalf("after the front was re-owned: %d held, want 0", n)
+ }
+}
+
+// The legacy no-key fallback serves a name another box owns here, so an
+// upgrade on it through a local catch-all is kept while no mesh key is
+// mirrored. Once a key is minted, the next refresh (the hosts unchanged)
+// mirrors it and the upgrade is cancelled: an ordinary request would now be
+// backhauled to the name's owner.
+func TestUpgradeSweptByMeshKeyChange(t *testing.T) {
+ hub, tc := triggerScene(t, false, true)
+ trigPublish(t, hub, frontRow(fwdOwner, "other"))
+ m := hub.homes.Load()
+ if err := m.Refresh(context.Background()); err != nil {
+ t.Fatal(err)
+ }
+ r, ctx, err := hub.reserveUpgrade(context.Background(), upgradeAdmission{Host: trigFront, Path: "/acme/cable", Tenancy: trigTenancy}, tc, 10)
+ if err != nil {
+ t.Fatalf("reserve under the no-key fallback: %v, want admitted", err)
+ }
+ defer r.release(relBody)
+ if err := MintMeshKey(t.Context(), hub.staticStore); err != nil {
+ t.Fatal(err)
+ }
+ if err := m.Refresh(context.Background()); err != nil {
+ t.Fatal(err)
+ }
+ if len(signingKey(m.meshKeys())) == 0 {
+ t.Fatal("fixture: the refresh mirrored no key")
+ }
+ wantReleased(t, ctx, r, "after a mesh key was mirrored")
+}
diff --git a/internal/edge/upgradetriggers.go b/internal/edge/upgradetriggers.go
new file mode 100644
index 000000000..86f72e000
--- /dev/null
+++ b/internal/edge/upgradetriggers.go
@@ -0,0 +1,68 @@
+package edge
+
+// Re-checking open upgrades when what they were admitted under moves (#186
+// whole-branch review R1 P2-3; Paul, rule 2, 2026-11-21: connect the
+// triggers). An admitted upgrade is kept only while upgradeSelection still
+// answers it ownerLocal with its tenancy, and that answer reads three
+// inputs, each with its own trigger for sweepUpgrades
+// (TestUpgradeInputsHaveSweepTriggers pins the table):
+//
+// - the routing table (Edge.upstreams), published only by Reload, which
+// sweeps right after its swap;
+// - the home map's snapshot (homeMap.snap: the fold, whether it was read,
+// this box's own admission posture), published by refreshHosts, which
+// wakes the sweep when one of those changed (ownershipInputsChanged);
+// - the mirrored mesh keys (homeMap.keyCurrent, keyNext), replaced by
+// refreshKeys, which wakes the sweep when the pair changed.
+//
+// The home map itself (Edge.homes) is installed once, by ArmHomeMap before
+// serving, which sweeps after installing it.
+//
+// Lock order. The home map's wake runs under homeMap.refreshMu (refreshHosts
+// and refreshKeys run under it), after homeMap.mu and homeMap.keyMu are
+// released; sweepUpgrades then takes Edge.open.mu, and under it the
+// re-check reads the snapshot and the keys (homeMap.mu and keyMu, read
+// locks). So: refreshMu -> open.mu -> homeMap.mu / keyMu. Reload's sweep is
+// reloadMu -> open.mu -> homeMap.mu / keyMu. Nothing holding open.mu,
+// homeMap.mu or keyMu takes refreshMu or reloadMu (the sweep never
+// refreshes or reloads, and releases streams on their own goroutines), and
+// neither path takes the other's outer lock, so there is no cycle.
+
+import (
+ "bytes"
+ "reflect"
+
+ "github.com/carlosframework/platform/internal/edgesfile"
+)
+
+// ownAdmissionAware reports whether this box's own edges file, as s read
+// it, carries any admission state (box role, admitted, drained). resolveName
+// marks this box's local claims admission-aware by it.
+func (s *homeSnapshot) ownAdmissionAware(self string) bool {
+ own := s.files[edgesfile.Key(self)]
+ return len(own.BoxRole) > 0 || len(own.Admitted) > 0 || len(own.Drained) > 0
+}
+
+// ownershipInputsChanged reports whether next differs from prev in anything
+// the ownership verdict and the path selection read from a snapshot
+// (resolveName, exactPathRoute): the fold, whether a read landed, and this
+// box's own admission posture. A difference elsewhere in the fold (an asset
+// view, an address) also counts: a needless sweep only re-checks.
+func ownershipInputsChanged(prev, next *homeSnapshot, self string) bool {
+ return prev.read != next.read || prev.ownAdmissionAware(self) != next.ownAdmissionAware(self) ||
+ !reflect.DeepEqual(prev.hosts, next.hosts)
+}
+
+// meshKeysChanged reports whether a key pair moved.
+func meshKeysChanged(current, next, newCurrent, newNext []byte) bool {
+ return !bytes.Equal(current, newCurrent) || !bytes.Equal(next, newNext)
+}
+
+// wakeUpgrades runs the map's upgrade wake (Edge.sweepUpgrades on the
+// edge's own map, newHomeMap; nil elsewhere). Called with refreshMu held and
+// mu and keyMu released (see the lock order above).
+func (m *homeMap) wakeUpgrades() {
+ if m.upgradeWake != nil {
+ m.upgradeWake()
+ }
+}