carlos / platform Public

edgesfile: one home election for the edge and assets status; unknown state (asset cache plan 3 Task 12, #396)

The status door elected a host's home with its own copy of the edge's
rules and ignored dial eligibility, so a higher-stamped box no edge can
dial could be reported as the home. The rule (HomeBeats) and the dial
address (DialAddress) now live in internal/edgesfile; the edge's
dialBeats and dialAddress call them unchanged, and the door elects
through edgesfile.ElectHomes (bucket-key order, only boxes some edge
can dial).

When the edges files cannot all be read the door now says
published_unknown, and the CLI prints EAC-26 "unknown" in FOLDERS and
the published columns, distinct from "-" (publishes nothing). EAC-16
revised in docs/site/cli.md and the copy record, per Paul's plan 3
approval; the gate pins the record against that approval.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev 0fb0425e13160d366a4163b49ba05932ec1cd19e parent 49a8386
14 files changed, +746 −126
  • apimode.go +4 −0
  • approved_asset_cache_copy_test.go +57 −5
  • assets_cli.go +16 −5
  • assets_cli_test.go +40 −0
  • docs/site/cli.md +1 −1
  • docs/superpowers/plans/2026-10-24-edge-asset-cache-copy.md +7 −1
  • internal/console/apiassets.go +57 −68
  • internal/console/apiassets_test.go +140 −6
  • internal/edge/homemap.go +28 −39
  • internal/edge/homemap_status_election_test.go +155 −0
  • internal/edgesfile/edgesfile.go +3 −1
  • internal/edgesfile/homeelect.go +160 −0
  • internal/edgesfile/homeelect_test.go +68 −0
  • internal/edgesfile/snapshot.go +10 −0
diff --git a/apimode.go b/apimode.go
index 138ecd6bb..e93287818 100644
--- a/apimode.go
+++ b/apimode.go
@@ -5187,6 +5187,10 @@ type apiAssetsStatus struct {
Gen string `json:"gen"`
PublishedGen string `json:"published_gen"`
PublishedAt string `json:"published_at"`
+ // PublishedUnknown: the console could not read the edges files, so
+ // the published columns are unknown, not empty. Absent from a
+ // console that predates it.
+ PublishedUnknown bool `json:"published_unknown"`
} `json:"instances"`
Truncated bool `json:"truncated"`
}
diff --git a/approved_asset_cache_copy_test.go b/approved_asset_cache_copy_test.go
index bce964d9d..e4b003551 100644
--- a/approved_asset_cache_copy_test.go
+++ b/approved_asset_cache_copy_test.go
@@ -2,6 +2,7 @@
package main
import (
+ "encoding/json"
"os"
"path/filepath"
"regexp"
@@ -26,17 +27,22 @@ const assetCacheCopyRecordPath = "docs/superpowers/plans/2026-10-24-edge-asset-c
var assetCacheCopyIDPattern = regexp.MustCompile(`^EAC-[0-9]+$`)
-// assetCacheCopyIDs is the record's inventory, pinned: EAC-1 to EAC-22, and
-// EAC-25 (the status list cut short, added in task 10's review). Plan 3 Task 0
-// adds EAC-23 and EAC-24 (its two docs rows).
+// assetCacheCopyIDs is the record's inventory, pinned: EAC-1 to EAC-22,
+// EAC-25 (the status list cut short, added in task 10's review) and EAC-26
+// (the status table's unknown, plan 3 Task 12). Plan 3 Task 10 adds EAC-23
+// and EAC-24 (its two docs rows).
var assetCacheCopyIDs = func() []string {
- ids := make([]string, 0, 23)
+ ids := make([]string, 0, 24)
for i := 1; i <= 22; i++ {
ids = append(ids, "EAC-"+strconv.Itoa(i))
}
- return append(ids, "EAC-25")
+ return append(ids, "EAC-25", "EAC-26")
}()
+// assetCachePlan3ApprovalPath is Paul's plan 3 copy review (2026-10-25): the
+// texts of EAC-23, EAC-24, EAC-26 and the revised EAC-16.
+const assetCachePlan3ApprovalPath = "docs/superpowers/plans/2026-10-24-edge-asset-cache-copy-approved-plan3.json"
+
// assetCacheCopyBuilt is every row whose text the code or docs carry. The task
// that writes a row's text adds its entry here in the same commit, once Paul
// has approved the row. An entry is "EAC-n", checked in the row's first file,
@@ -53,6 +59,7 @@ var assetCacheCopyBuilt = []string{
"EAC-10", "EAC-11", "EAC-12", "EAC-13", "EAC-14",
"EAC-16", "EAC-17", "EAC-18", "EAC-19",
"EAC-25",
+ "EAC-26",
}
// assetCacheBuiltRows turns built entries into the rows to check: one per
@@ -124,6 +131,51 @@ func TestAssetCacheCopyBuiltRowsAreApprovedAndPresent(t *testing.T) {
reportAll(t, checkAssetCacheBuilt(mustParseAssetCacheCopyRecord(t), assetCacheCopyBuilt, "."))
}
+// TestAssetCacheCopyRecordsThePlan3Approval: every id Paul approved in the
+// plan 3 review that the record already carries has the approved text,
+// verbatim, so the revised EAC-16 cannot drift back to the plan 1 wording
+// (and, through TestAssetCacheCopyBuiltRowsAreApprovedAndPresent, neither
+// can docs/site/cli.md). An approved id the record does not carry yet
+// (EAC-23 and EAC-24 until Task 10) is not checked here; the inventory pins
+// when it arrives.
+func TestAssetCacheCopyRecordsThePlan3Approval(t *testing.T) {
+ raw, err := os.ReadFile(assetCachePlan3ApprovalPath)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var approval struct {
+ Action string `json:"action"`
+ Strings []struct {
+ ID string `json:"id"`
+ Text string `json:"text"`
+ } `json:"strings"`
+ }
+ if err := json.Unmarshal(raw, &approval); err != nil {
+ t.Fatal(err)
+ }
+ if approval.Action != "approve" {
+ t.Fatalf("%s: action %q, want approve", assetCachePlan3ApprovalPath, approval.Action)
+ }
+ byID := map[string]string{}
+ for _, r := range mustParseAssetCacheCopyRecord(t) {
+ byID[r.ID] = strings.ReplaceAll(r.Text, `\n`, "\n")
+ }
+ for _, id := range []string{"EAC-16", "EAC-26"} {
+ if _, ok := byID[id]; !ok {
+ t.Errorf("the record has no %s row", id)
+ }
+ }
+ for _, s := range approval.Strings {
+ got, ok := byID[s.ID]
+ if !ok {
+ continue
+ }
+ if got != s.Text {
+ t.Errorf("%s: the record says %q, Paul approved %q", s.ID, got, s.Text)
+ }
+ }
+}
+
// The gate itself: an "@path" entry is checked in that file, and the record's
// \n and \t are real characters when matched against a Go literal.
func TestAssetCacheCopyGateChecksTheNamedFile(t *testing.T) {
diff --git a/assets_cli.go b/assets_cli.go
index 63e049317..b59982dcd 100644
--- a/assets_cli.go
+++ b/assets_cli.go
@@ -141,10 +141,17 @@ func runAssetsStatus(args []string) {
printAssetsStatus(stdout, app2, st)
}
+// assetsStatusUnknown is the approved copy row EAC-26: what the folders and
+// published columns say when the console could not read what the home
+// publishes. It is not "-", which says the home publishes nothing.
+const assetsStatusUnknown = "unknown"
+
// printAssetsStatus prints the heads, a row per instance, a blank line and the
-// bound sentence (EAC-14). An empty cell reads "-". When the door says it
-// stopped listing, EAC-25 takes the bound sentence's place: matching
-// generations in a partial list say nothing about the whole app.
+// bound sentence (EAC-14). An empty cell reads "-". When the door could not
+// read the edges files, the folders and published columns read EAC-26
+// instead. When the door says it stopped listing, EAC-25 takes the bound
+// sentence's place: matching generations in a partial list say nothing about
+// the whole app.
func printAssetsStatus(w io.Writer, app string, st apiAssetsStatus) {
heads, bound, _ := strings.Cut(assetsStatusText, "\n\n")
dash := func(s string) string {
@@ -156,8 +163,12 @@ func printAssetsStatus(w io.Writer, app string, st apiAssetsStatus) {
t := newTable(w)
fmt.Fprintln(t, heads)
for _, in := range st.Instances {
- fmt.Fprintf(t, "%s\t%s\t%s\t%s\t%s\t%s\n", in.Host, dash(strings.Join(in.Paths, ",")), dash(in.Assets),
- dash(in.Gen), dash(in.PublishedGen), dash(in.PublishedAt))
+ folders, pubGen, pubAt := dash(strings.Join(in.Paths, ",")), dash(in.PublishedGen), dash(in.PublishedAt)
+ if in.PublishedUnknown {
+ folders, pubGen, pubAt = assetsStatusUnknown, assetsStatusUnknown, assetsStatusUnknown
+ }
+ fmt.Fprintf(t, "%s\t%s\t%s\t%s\t%s\t%s\n", in.Host, folders, dash(in.Assets),
+ dash(in.Gen), pubGen, pubAt)
}
t.Flush()
fmt.Fprintln(w)
diff --git a/assets_cli_test.go b/assets_cli_test.go
index 6e14accf3..8f27ea09d 100644
--- a/assets_cli_test.go
+++ b/assets_cli_test.go
@@ -7,6 +7,7 @@ import (
"io"
"net/http"
"net/http/httptest"
+ "slices"
"strings"
"testing"
)
@@ -283,3 +284,42 @@ func TestAssetsStatusTruncatedSaysSo(t *testing.T) {
}
}
}
+
+// TestAssetsStatusPrintsUnknownApartFromNothing: an instance the door marks
+// published_unknown (it could not read the edges files) shows EAC-26 in the
+// FOLDERS, PUBLISHED GENERATION and PUBLISHED AT columns, while its own
+// columns (ASSETS, GENERATION) still come from the record; an instance whose
+// home publishes nothing still shows "-". The bound sentence is unchanged.
+//
+// Not acceptance: the console is a stand-in that returns canned JSON; the real
+// door's unknown state is tested in internal/console
+// (TestStatusShowsUnknownWhenTheEdgesFileCannotBeRead).
+func TestAssetsStatusPrintsUnknownApartFromNothing(t *testing.T) {
+ const reply = `{"instances":[` +
+ `{"host":"a.shop.example.com","paths":[],"assets":"on","gen":"0123456789abcdef","published_unknown":true},` +
+ `{"host":"b.shop.example.com","paths":[],"assets":"off","gen":"fedcba9876543210"}` +
+ `],"truncated":false}`
+ sess, _ := assetsDoor(t, http.StatusOK, reply)
+ st, err := sess.assetsStatus(context.Background(), apiAcct{Seg: "abc"}, "shop")
+ if err != nil {
+ t.Fatalf("assetsStatus: %v", err)
+ }
+ var b bytes.Buffer
+ printAssetsStatus(&b, "shop", st)
+ out := b.String()
+ rows := map[string][]string{}
+ for _, line := range strings.Split(out, "\n") {
+ if f := strings.Fields(line); len(f) > 0 && strings.HasSuffix(f[0], ".shop.example.com") {
+ rows[f[0]] = f[1:]
+ }
+ }
+ if got, want := rows["a.shop.example.com"], []string{"unknown", "on", "0123456789abcdef", "unknown", "unknown"}; !slices.Equal(got, want) {
+ t.Errorf("a.shop.example.com row = %q, want %q\n%s", got, want, out)
+ }
+ if got, want := rows["b.shop.example.com"], []string{"-", "off", "fedcba9876543210", "-", "-"}; !slices.Equal(got, want) {
+ t.Errorf("b.shop.example.com row = %q, want %q\n%s", got, want, out)
+ }
+ if !strings.HasSuffix(out, "a server that cannot stops serving the app's saved asset files within an hour.\n") {
+ t.Errorf("status output does not end with the bound sentence:\n%s", out)
+ }
+}
diff --git a/docs/site/cli.md b/docs/site/cli.md
index 8195ae215..ec156a6cb 100644
--- a/docs/site/cli.md
+++ b/docs/site/cli.md
@@ -1258,7 +1258,7 @@ the app's own instance credential can read the flags but never set them.
### carlos assets
-Throws away or inspects the copies that servers keep of an app's asset files. `carlos assets purge --app shop` makes every instance of the app forget what it has saved, so the next request for each file goes to the app. If it stops part way it names the instances that did not change, and running it again finishes the job. `carlos assets status --app shop` lists each instance with the folders its release declares, whether asset copying is on, and the generation the purge has reached. Copies are only kept for folders the release declares with `--assets`.
+Throws away or inspects the copies that servers keep of an app's asset files. `carlos assets purge --app shop` makes every instance of the app forget what it has saved, so the next request for each file goes to the app. If it stops part way it names the instances that did not change, and running it again finishes the job. `carlos assets status --app shop` lists each instance with the folders its home server is publishing, whether asset copying is on, and the generation the purge has reached. Copies are only kept for folders the release declares with `--assets`.
A purge reaches every server that can read the platform's storage within a minute. A server that cannot stops serving the app's saved asset files within an hour.
diff --git a/docs/superpowers/plans/2026-10-24-edge-asset-cache-copy.md b/docs/superpowers/plans/2026-10-24-edge-asset-cache-copy.md
index 7e24e4259..b43ca7c6f 100644
--- a/docs/superpowers/plans/2026-10-24-edge-asset-cache-copy.md
+++ b/docs/superpowers/plans/2026-10-24-edge-asset-cache-copy.md
@@ -30,6 +30,11 @@ The rules:
case. Docs prose keeps the CLI page's sentence case.
- Ids are not renumbered. EAC-23 and EAC-24 are plan 3's docs rows and stay
free here.
+- Plan 3 Task 12 (discussion #396) added EAC-26, the status table's word
+ for published columns the console could not read, and revised EAC-16 to
+ say status lists the folders the home server is publishing. Paul
+ approved both on 2026-10-25
+ (`2026-10-24-edge-asset-cache-copy-approved-plan3.json`).
Placeholders: `<path>` an asset path as the person typed it; `<version>` a
release version; `<host>` an instance's hostname; `<hosts>` a comma-separated
@@ -72,6 +77,7 @@ none a prefix of another.
| EAC-13 | assets_cli.go | the purge of <app> changed <done> of <total> instances and left these unchanged: <hosts>. run carlos assets purge --app <app> again to finish it. | approved |
| EAC-14 | assets_cli.go | HOST\tFOLDERS\tASSETS\tGENERATION\tPUBLISHED GENERATION\tPUBLISHED AT\n\na purge is done once the published generation matches the generation. servers that can reach the platform pick up a new generation within a minute. a server that cannot stops serving the app's saved asset files within an hour. | approved |
| EAC-25 | assets_cli.go | the list stops at <n> instances, so it may not show every instance of <app>. a purge is only known to be done once every instance is listed. | approved |
+| EAC-26 | assets_cli.go | unknown | approved |
## Console (plan 1, task 5)
@@ -83,7 +89,7 @@ none a prefix of another.
| id | file | text | status |
|---|---|---|---|
-| EAC-16 | docs/site/cli.md | Throws away or inspects the copies that servers keep of an app's asset files. `carlos assets purge --app shop` makes every instance of the app forget what it has saved, so the next request for each file goes to the app. If it stops part way it names the instances that did not change, and running it again finishes the job. `carlos assets status --app shop` lists each instance with the folders its release declares, whether asset copying is on, and the generation the purge has reached. Copies are only kept for folders the release declares with `--assets`.\n\nA purge reaches every server that can read the platform's storage within a minute. A server that cannot stops serving the app's saved asset files within an hour. | approved |
+| EAC-16 | docs/site/cli.md | Throws away or inspects the copies that servers keep of an app's asset files. `carlos assets purge --app shop` makes every instance of the app forget what it has saved, so the next request for each file goes to the app. If it stops part way it names the instances that did not change, and running it again finishes the job. `carlos assets status --app shop` lists each instance with the folders its home server is publishing, whether asset copying is on, and the generation the purge has reached. Copies are only kept for folders the release declares with `--assets`.\n\nA purge reaches every server that can read the platform's storage within a minute. A server that cannot stops serving the app's saved asset files within an hour. | approved |
| EAC-17 | docs/site/cli.md | Turns asset copying on or off for one instance. `off` means requests for its asset files always reach the app, which helps while you are debugging. `on` goes back to following the folders its release declares. An instance follows its release until you set it. | approved |
| EAC-18 | docs/site/cli.md | `--assets` names a folder your build writes its files to, for example `/assets/`. Repeat it for up to 8 folders. Each must start and end with `/`, be at most 128 bytes, and contain none of `%`, `?`, `#`, `*` or `..`. `/` alone is refused, because it would keep copies of every page. No folder may sit inside another. A static site cannot use it, because a static site is already served from every region. The folders belong to the release, so a rollback to an older build uses the folders that build declared. | approved |
| EAC-19 | docs/site/cli.md | `carlos deploy` takes the same repeatable `--assets` flag and passes it to the ship. Save the list as `"assets": ["/assets/"]` in `.carlos/config` and a bare `carlos deploy` declares it on every release. A flag on the command line replaces the saved list for that run, and `--no-assets` ships with none. A release that declares no folders gets no copies, so deploying a build without them turns copying off for that build. `--assets` and `--no-assets` cannot be given together. | approved |
diff --git a/internal/console/apiassets.go b/internal/console/apiassets.go
index 1efdfda80..5d89d7c7b 100644
--- a/internal/console/apiassets.go
+++ b/internal/console/apiassets.go
@@ -2,12 +2,10 @@ package console
import (
"context"
- "encoding/json"
"errors"
"log"
"net/http"
"os"
- "slices"
"strings"
"time"
@@ -136,26 +134,39 @@ func listOrNone(hosts []string) string {
}
// assetStatusView is one instance in the status reply (design §6): the
-// folders its channel's build declares, the opt-out, the generation in the
-// record, and the generation and at its home published in its edges file.
-// A purge is complete at the home when PublishedGen matches Gen.
+// folders its home publishes, the opt-out, the generation in the record,
+// and the generation and at its home published in its edges file. A purge
+// is complete at the home when PublishedGen matches Gen.
+//
+// PublishedUnknown says the published columns could not be read at all (the
+// edges files could not be listed, or one of them could not be read), which
+// the CLI prints as EAC-26 in place of the folders and published columns.
+// It is not "publishes nothing": that is a readable winner with no block,
+// and leaves PublishedUnknown false and the columns empty. A console that
+// predates the field leaves it out, and a CLI that predates it prints the
+// empty columns it always printed.
type assetStatusView struct {
- Host string `json:"host"`
- Paths []string `json:"paths"`
- Assets string `json:"assets"`
- Gen string `json:"gen"`
- PublishedGen string `json:"published_gen,omitempty"`
- PublishedAt string `json:"published_at,omitempty"`
+ Host string `json:"host"`
+ Paths []string `json:"paths"`
+ Assets string `json:"assets"`
+ Gen string `json:"gen"`
+ PublishedGen string `json:"published_gen,omitempty"`
+ PublishedAt string `json:"published_at,omitempty"`
+ PublishedUnknown bool `json:"published_unknown,omitempty"`
}
// handleAPIAssetsStatus answers per instance what `carlos assets status`
// prints. Reads only: the records (the instance list's capped read) and the
-// edges files through readEdgesFiles. Every published column comes from one
-// place, the assets block of the host's WINNING home entry, chosen the way
-// an edge's home map chooses it (homeAssets): the folders, generation and at
-// an edge would use, or none when that entry publishes no block. The channel
-// head's declaration is not consulted: it says what a release asks for, not
-// what the home is serving (design §6).
+// edges files through readEdgesSnapshot. Every published column comes from
+// one place, the assets block of the host's WINNING home entry, elected the
+// way an edge's home map elects it (homeAssets, edgesfile.ElectHomes): the
+// folders, generation and at an edge would use, or none when that entry
+// publishes no block. The channel head's declaration is not consulted: it
+// says what a release asks for, not what the home is serving (design §6).
+//
+// When the edges files cannot all be read, nobody can say which entry wins
+// for any host: an unread file may hold a higher stamp. Every instance's
+// published columns are then unknown (PublishedUnknown), never "none".
//
// truncated is set when the listing stopped at the cap and also when it
// skipped a record it could not read: either way an instance is missing
@@ -177,10 +188,10 @@ func (s *Server) handleAPIAssetsStatus(w http.ResponseWriter, r *http.Request) {
log.Printf("console: api assets status %s/%s: %d record(s) unreadable %v", acct.Sqid, app, len(skipped), skipped)
truncated = true
}
- published := homeAssets(readEdgesFiles(ctx, s.cfg.Releases))
+ published, known := s.homeAssets(ctx, acct.Sqid, app)
out := make([]assetStatusView, 0, len(recs))
for _, rec := range recs {
- v := assetStatusView{Host: rec.Host, Paths: []string{}, Assets: "on", Gen: rec.AssetGen}
+ v := assetStatusView{Host: rec.Host, Paths: []string{}, Assets: "on", Gen: rec.AssetGen, PublishedUnknown: !known}
if !rec.AssetsOn() {
v.Assets = "off"
}
@@ -196,58 +207,36 @@ func (s *Server) handleAPIAssetsStatus(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, map[string]any{"instances": out, "truncated": truncated})
}
-// homeAssetsEntry is one host entry as the status door elects it: the
-// reader's Host plus the installation stamp the edge's home map orders
-// claims by (internal/edge homemap.go's edgesFileView.Stamp).
-type homeAssetsEntry struct {
- edgesfile.Host
- Stamp int64 `json:"stamp"`
-}
-
-// homeAssets folds the edges files into host -> the assets block of the
-// entry an edge dials for it, nil when that entry publishes none. The
-// election is the edge's own (internal/edge homemap.go foldHomes and
-// dialBeats), rule for rule: only a home-role entry is a candidate; files
-// are taken in object-key order; a later entry takes the host when it is a
-// route and the holder an alias, or, being of the same kind, when its stamp
-// is higher; otherwise the first keeps it. The winner's block is taken
-// whole, its absence included, so a losing box's newer block is never
-// reported as the home's. Left out on purpose are the parts of the fold
-// that depend on which edge is reading (its own box, and whether it has an
-// address to dial). A host entry that does not decode is skipped, as
-// readEdgesFiles skips a file.
-func homeAssets(files []edgesFilePlacementView) map[string]*edgesfile.HostAssets {
- sorted := slices.Clone(files)
- slices.SortStableFunc(sorted, func(a, b edgesFilePlacementView) int {
- return strings.Compare(edgesfile.Key(a.Box), edgesfile.Key(b.Box))
- })
- won := map[string]homeAssetsEntry{}
- for _, f := range sorted {
- for host, raw := range f.Hosts {
- var in homeAssetsEntry
- if host == "" || json.Unmarshal(raw, &in) != nil || in.Role != edgesfile.RoleHome {
- continue
- }
- prev, held := won[host]
- if held && !homeAssetsBeats(in, prev) {
- continue
- }
- won[host] = in
- }
+// homeAssets reads the edges files and answers host -> the assets block of
+// the entry an edge dials for it, nil when that entry publishes none. The
+// election is edgesfile.ElectHomes, which shares its rule (HomeBeats) and
+// its dial eligibility (DialAddress) with the edge's home map, so a box no
+// edge can dial never wins, however high its stamp (#396). The winner's
+// block is taken whole, its absence included, so a losing box's newer
+// block is never reported as the home's.
+//
+// known is false when the answer cannot be trusted at all: no store, a
+// listing that failed, or a file under the prefix that could not be read
+// or parsed (the snapshot is not Complete). An edge carries an unreadable
+// file's previous parse forward; the console has none to carry, and the
+// unread file may hold the winning entry for any host.
+func (s *Server) homeAssets(ctx context.Context, acct, app string) (map[string]*edgesfile.HostAssets, bool) {
+ if s.cfg.Releases == nil {
+ return nil, false
+ }
+ snap, err := readEdgesSnapshot(ctx, s.cfg.Releases)
+ if err != nil {
+ log.Printf("console: api assets status %s/%s: could not list %s: %v", acct, app, edgesfile.Prefix, err)
+ return nil, false
}
+ if !snap.Complete {
+ log.Printf("console: api assets status %s/%s: an edges file under %s could not be read, so every published column is unknown", acct, app, edgesfile.Prefix)
+ return nil, false
+ }
+ won := edgesfile.ElectHomes(snap.Files)
out := make(map[string]*edgesfile.HostAssets, len(won))
for host, e := range won {
out[host] = e.Assets
}
- return out
-}
-
-// homeAssetsBeats is the edge's dialBeats over two home-role entries: a
-// route beats an alias, then the higher installation stamp wins (a stamped
-// entry beats an unstamped one).
-func homeAssetsBeats(in, prev homeAssetsEntry) bool {
- if prev.Alias != in.Alias {
- return prev.Alias && !in.Alias
- }
- return in.Stamp > prev.Stamp
+ return out, true
}
diff --git a/internal/console/apiassets_test.go b/internal/console/apiassets_test.go
index 03c56e2cd..27ef42a97 100644
--- a/internal/console/apiassets_test.go
+++ b/internal/console/apiassets_test.go
@@ -12,6 +12,7 @@ import (
"testing"
"time"
+ "github.com/carlosframework/platform/internal/edgesfile"
"github.com/carlosframework/platform/internal/provision"
"github.com/carlosframework/platform/internal/release"
)
@@ -591,12 +592,13 @@ func TestAssetsStatusJoinsPublishedGeneration(t *testing.T) {
// assetStatusReply is the status door's answer, decoded.
type assetStatusReply struct {
Instances []struct {
- Host string `json:"host"`
- Paths []string `json:"paths"`
- Assets string `json:"assets"`
- Gen string `json:"gen"`
- PublishedGen string `json:"published_gen"`
- PublishedAt string `json:"published_at"`
+ Host string `json:"host"`
+ Paths []string `json:"paths"`
+ Assets string `json:"assets"`
+ Gen string `json:"gen"`
+ PublishedGen string `json:"published_gen"`
+ PublishedAt string `json:"published_at"`
+ PublishedUnknown bool `json:"published_unknown"`
} `json:"instances"`
Truncated bool `json:"truncated"`
}
@@ -681,6 +683,138 @@ func TestAssetsStatusReportsTheWinningHomesBlock(t *testing.T) {
}
}
+// TestAssetsStatusSkipsAHomeNoEdgeCanDial: a box that publishes the host
+// at a higher stamp but has neither a public nor a usable private address
+// is no dial target, so the edges use the lower-stamped reachable
+// publisher, and status reports that publisher's block (#396). The
+// election is the edge's own (edgesfile.ElectHomes; internal/edge
+// TestStatusElectsTheSameHomeAsTheEdge holds the two together). Not
+// acceptance: the edges files are built by hand.
+func TestAssetsStatusSkipsAHomeNoEdgeCanDial(t *testing.T) {
+ const host = "shop.example.com"
+ at := time.Date(2026, 10, 25, 9, 0, 0, 0, time.UTC)
+ fx, token := assetsFixture(t, "code-assets-status-undialable")
+ putAssetRecord(t, fx, host, "aaaaaaaaaaaaaaaa")
+ putStatusEdges(t, fx, "box-a", map[string]any{host: map[string]any{
+ "role": "home", "stamp": 1, "assets": statusBlock([]string{"/assets/"}, "aaaaaaaaaaaaaaaa", at)}})
+ raw, err := json.Marshal(map[string]any{"v": 1, "box": "box-b", "eip": "", "region": "ie", "hosts": map[string]any{host: map[string]any{
+ "role": "home", "stamp": 9, "assets": statusBlock([]string{"/new/"}, "bbbbbbbbbbbbbbbb", at.Add(time.Hour))}}})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := fx.rel.Put(context.Background(), "control/edges/box-b.json", raw, ""); err != nil {
+ t.Fatal(err)
+ }
+ reply := getAssetStatus(t, fx, token)
+ if len(reply.Instances) != 1 {
+ t.Fatalf("status = %+v, want one instance", reply)
+ }
+ in := reply.Instances[0]
+ if in.PublishedUnknown || in.PublishedGen != "aaaaaaaaaaaaaaaa" || in.PublishedAt != at.Format(time.RFC3339) ||
+ !samePathList(in.Paths, []string{"/assets/"}) {
+ t.Fatalf("%s = %+v, want box-a's block: box-b has nothing an edge can dial", host, in)
+ }
+}
+
+// assetEdgesFailStore fails the edges files' read: the listing of the
+// prefix when key is "", otherwise every Get of key.
+type assetEdgesFailStore struct {
+ release.Store
+ key string
+}
+
+func (f assetEdgesFailStore) List(ctx context.Context, prefix string) ([]string, error) {
+ if f.key == "" && prefix == edgesfile.Prefix {
+ return nil, errors.New("assetEdgesFailStore: listing unavailable")
+ }
+ return f.Store.List(ctx, prefix)
+}
+
+func (f assetEdgesFailStore) Get(ctx context.Context, key string) ([]byte, string, error) {
+ if f.key != "" && key == f.key {
+ return nil, "", errors.New("assetEdgesFailStore: bucket unavailable")
+ }
+ return f.Store.Get(ctx, key)
+}
+
+// TestStatusShowsUnknownWhenTheEdgesFileCannotBeRead: when the door cannot
+// read every edges file, it cannot say which entry wins for any host (an
+// unread file may hold the winner), so every instance's published columns
+// are unknown (published_unknown, which the CLI prints as EAC-26), never
+// "publishes nothing". Each failure separately: an edges file whose GET
+// fails, a malformed one, and a listing that fails. The control read shows
+// the other state: a host whose winning entry publishes no block is known
+// and empty ("-" in the CLI), not unknown. The records are still read and
+// shown. Not acceptance: the edges files are built by hand.
+func TestStatusShowsUnknownWhenTheEdgesFileCannotBeRead(t *testing.T) {
+ at := time.Date(2026, 10, 25, 9, 0, 0, 0, time.UTC)
+ const broken = "control/edges/box-b.json"
+ cases := []struct {
+ name string
+ inject func(t *testing.T, fx *consoleFixture)
+ }{
+ {"an edges file whose GET fails", func(t *testing.T, fx *consoleFixture) {
+ putStatusEdges(t, fx, "box-b", map[string]any{})
+ fx.srv.cfg.Releases = assetEdgesFailStore{Store: fx.rel, key: broken}
+ }},
+ {"a malformed edges file", func(t *testing.T, fx *consoleFixture) {
+ if _, err := fx.rel.Put(context.Background(), broken, []byte(`{"v":1,"box":`), ""); err != nil {
+ t.Fatal(err)
+ }
+ }},
+ {"a listing that fails", func(t *testing.T, fx *consoleFixture) {
+ fx.srv.cfg.Releases = assetEdgesFailStore{Store: fx.rel}
+ }},
+ }
+ for i, c := range cases {
+ t.Run(c.name, func(t *testing.T) {
+ fx, token := assetsFixture(t, fmt.Sprintf("code-assets-status-unknown-%d", i))
+ putAssetRecord(t, fx, "shop.example.com", "0123456789abcdef")
+ putAssetRecord(t, fx, "shop-2.example.com", "fedcba9876543210")
+ putStatusEdges(t, fx, "box-a", map[string]any{
+ "shop.example.com": map[string]any{"role": "home", "assets": statusBlock([]string{"/assets/"}, "0123456789abcdef", at)},
+ "shop-2.example.com": map[string]any{"role": "home"},
+ })
+ byHost := func(reply assetStatusReply) map[string]int {
+ m := map[string]int{}
+ for i, in := range reply.Instances {
+ m[in.Host] = i
+ }
+ return m
+ }
+
+ control := getAssetStatus(t, fx, token)
+ idx := byHost(control)
+ one, two := control.Instances[idx["shop.example.com"]], control.Instances[idx["shop-2.example.com"]]
+ if len(control.Instances) != 2 || one.PublishedUnknown || one.PublishedGen != "0123456789abcdef" ||
+ !samePathList(one.Paths, []string{"/assets/"}) {
+ t.Fatalf("control: shop.example.com = %+v, want its published block", one)
+ }
+ if two.PublishedUnknown || two.PublishedGen != "" || two.PublishedAt != "" || len(two.Paths) != 0 {
+ t.Fatalf("control: shop-2.example.com = %+v, want known and publishing nothing", two)
+ }
+
+ c.inject(t, fx)
+ reply := getAssetStatus(t, fx, token)
+ if len(reply.Instances) != 2 {
+ t.Fatalf("status = %+v, want both instances listed", reply)
+ }
+ for _, in := range reply.Instances {
+ if !in.PublishedUnknown || in.PublishedGen != "" || in.PublishedAt != "" || len(in.Paths) != 0 {
+ t.Errorf("%s = %+v, want unknown published columns and nothing reported as published", in.Host, in)
+ }
+ }
+ idx = byHost(reply)
+ if g := reply.Instances[idx["shop.example.com"]].Gen; g != "0123456789abcdef" {
+ t.Errorf("shop.example.com record gen = %q, want the record's", g)
+ }
+ if g := reply.Instances[idx["shop-2.example.com"]].Gen; g != "fedcba9876543210" {
+ t.Errorf("shop-2.example.com record gen = %q, want the record's", g)
+ }
+ })
+ }
+}
+
// assetGetFailStore fails every Get of one key: a record the listing names
// but the store will not return.
type assetGetFailStore struct {
diff --git a/internal/edge/homemap.go b/internal/edge/homemap.go
index 32a044764..62dd74315 100644
--- a/internal/edge/homemap.go
+++ b/internal/edge/homemap.go
@@ -145,25 +145,20 @@ type edgesFileView struct {
Placement string `json:"placement"`
}
-// dialAddress is where this edge dials f's box (region HA spec 2 §6). With
-// privateDial (this edge's own region HA switch) on, a box that publishes
-// the same AWS region and placement as this one is dialled at its private
-// address, so the dial stays inside the region's network, but only when
-// that address passes edgesfile.PrivateAddress against the network this
-// box's own file publishes (census ruling region-ha-2a). The home's
-// placement code is "", so two home boxes share a placement as two boxes
-// of one named region do; a home box and a named one never do (Astra 2a
-// final review, P2). Every other box, and every box with privateDial off,
-// is dialled at its public address, as before. self is this box's own
-// file, which selfKnown says was found. "" is nothing to dial.
+// dialAddress is where this edge dials f's box: edgesfile.DialAddress, the
+// rule the console's status door also elects a home by (#396). With
+// privateDial (this edge's own region HA switch) on, a box in this box's
+// own region and placement is dialled at its private address when it
+// passes this box's network; every other box at its public address. self
+// is this box's own file, which selfKnown says was found. "" is nothing to
+// dial.
func dialAddress(f, self edgesFileView, selfKnown, privateDial bool) string {
- if privateDial && selfKnown && f.Region != "" &&
- f.Region == self.Region && f.Placement == self.Placement {
- if addr, _ := edgesfile.PrivateAddress(f.PrivateIP, []string{self.PrivateCIDR}); addr != "" {
- return addr
- }
- }
- return f.EIP
+ return edgesfile.DialAddress(f.dialPoint(), self.dialPoint(), selfKnown, privateDial)
+}
+
+// dialPoint is f's dial fields, as edgesfile reads them.
+func (f edgesFileView) dialPoint() edgesfile.DialPoint {
+ return edgesfile.DialPoint{EIP: f.EIP, PrivateIP: f.PrivateIP, PrivateCIDR: f.PrivateCIDR, Region: f.Region, Placement: f.Placement}
}
// regionHAFromEnv is CARLOS_REGION_HA as strconv.ParseBool reads it, the
@@ -774,6 +769,10 @@ func (m *homeMap) logPartialPoll(failed, tried int, err error) {
// split-and-wrong: the whole fleet aiming at one box is a condition that heals
// on the next publish, where half the fleet aiming at each is a condition that
// looks fine from any single box.
+//
+// The console's status door elects through edgesfile.ElectHomes, which
+// takes the same order, the same dial rule and the same HomeBeats, so it
+// names the home this fold dials (#396).
func foldHomes(files map[string]edgesFileView, self string, privateDial bool) (map[string]homeEntry, []string) {
keys := make([]string, 0, len(files))
for k := range files {
@@ -892,28 +891,18 @@ func tiedStamps(files map[string]edgesFileView) []string {
}
// dialBeats reports whether a later file's entry takes the dial from the
-// one already folded. In order:
-//
-// - only a dial target can take it, and any dial target beats none;
-// - a ROUTE beats an ALIAS whatever else is true (#287);
-// - between two of the same kind, the newer installation wins: a stamped
-// entry beats an unstamped one, and a higher stamp beats a lower one
-// (region HA spec 1 HA4). A dead box's file lingers; its successor's
-// stamp is always higher, so the stale one loses without any liveness
-// rule;
-// - otherwise the earlier file keeps it, which is the first box in
-// sorted order, as before.
+// one already folded: edgesfile.HomeBeats, the election the console's
+// status door makes too (#396). Only a dial target can take it and any
+// dial target beats none; a ROUTE beats an ALIAS (#287); then the higher
+// installation stamp (region HA spec 1 HA4); otherwise the earlier file,
+// the first box in sorted order, keeps it.
func dialBeats(in, prev homeEntry) bool {
- if !in.dial {
- return false
- }
- if !prev.dial {
- return true
- }
- if prev.alias != in.alias {
- return prev.alias && !in.alias
- }
- return in.stamp > prev.stamp
+ return edgesfile.HomeBeats(in.claim(), prev.claim())
+}
+
+// claim is e as the home election orders it.
+func (e homeEntry) claim() edgesfile.HomeClaim {
+ return edgesfile.HomeClaim{Dial: e.dial, Alias: e.alias, Stamp: e.stamp}
}
func (m *homeMap) snapshot() *homeSnapshot {
diff --git a/internal/edge/homemap_status_election_test.go b/internal/edge/homemap_status_election_test.go
new file mode 100644
index 000000000..5a18b87a7
--- /dev/null
+++ b/internal/edge/homemap_status_election_test.go
@@ -0,0 +1,155 @@
+package edge
+
+import (
+ "context"
+ "fmt"
+ "slices"
+ "testing"
+
+ "github.com/carlosframework/platform/internal/edgesfile"
+)
+
+// TestStatusElectsTheSameHomeAsTheEdge: the console's status door elects a
+// host's home through edgesfile.ElectHomes, over the files edgesfile's
+// ReadSnapshot reads (#396). For every row, one store holds the edges
+// files, a real homeMap refreshes from it and folds them (foldHomes), and
+// ElectHomes elects from a ReadSnapshot of the same store: both must name
+// the same winning box and the same assets block, or both no winner.
+//
+// The reader is a box that homes nothing, so the fold's own-box exclusion
+// plays no part, as the console has no box of its own. Each row runs with
+// the reader's region HA off and on, except the rows about a box with only
+// a private address: only an edge in that box's own region with region HA
+// on can dial it, so those rows run for that reader alone (ElectHomes
+// counts a box any edge can dial; an edge in another region dials only
+// public addresses and cannot reach it at all).
+//
+// Not acceptance: the files are written by hand, not by the box's
+// edgesFilePass.
+func TestStatusElectsTheSameHomeAsTheEdge(t *testing.T) {
+ const host = "shop.example.com"
+ block := func(path, gen string, at int64) string {
+ return fmt.Sprintf(`"assets":{"paths":[%q],"gen":%q,"at":%d,"primary":%q}`, path, gen, at, host)
+ }
+ public := func(box, eip, entry string) string {
+ return fmt.Sprintf(`{"v":1,"box":%q,"eip":%q,"region":"eu-west-1","placement":"ie","hosts":{%q:{%s}}}`, box, eip, host, entry)
+ }
+ privateOnly := func(box, privateIP, entry string) string {
+ return fmt.Sprintf(`{"v":1,"box":%q,"eip":"","private_ip":%q,"private_cidr":"10.0.0.0/16","region":"eu-west-1","placement":"ie","hosts":{%q:{%s}}}`, box, privateIP, host, entry)
+ }
+ const owner = `"account":"acct1","app":"shop"`
+ rows := []struct {
+ name string
+ files map[string]string // bucket key name -> body
+ wantBox string // "" = no winner
+ inRegionOnly bool
+ }{
+ {"the higher stamp wins",
+ map[string]string{
+ "box-a": public("box-a", "192.0.2.1", `"role":"home","stamp":1,`+owner+`,`+block("/old/", "aaaaaaaaaaaaaaaa", 1761382800)),
+ "box-b": public("box-b", "192.0.2.2", `"role":"home","stamp":2,`+owner+`,`+block("/assets/", "bbbbbbbbbbbbbbbb", 1761381000)),
+ }, "box-b", false},
+ {"an undialable higher-stamped box loses to the reachable publisher",
+ map[string]string{
+ "box-a": public("box-a", "192.0.2.1", `"role":"home","stamp":1,`+owner+`,`+block("/assets/", "aaaaaaaaaaaaaaaa", 1761381000)),
+ "box-b": public("box-b", "", `"role":"home","stamp":9,`+owner+`,`+block("/new/", "bbbbbbbbbbbbbbbb", 1761382800)),
+ }, "box-a", false},
+ {"an undialable box earlier in key order does not hold the host",
+ map[string]string{
+ "box-a": public("box-a", "", `"role":"home","stamp":9,`+owner+`,`+block("/new/", "aaaaaaaaaaaaaaaa", 1761382800)),
+ "box-b": public("box-b", "192.0.2.2", `"role":"home",`+owner),
+ }, "box-b", false},
+ {"a private address that fails validation is no address",
+ map[string]string{
+ "box-a": public("box-a", "192.0.2.1", `"role":"home","stamp":1,`+owner+`,`+block("/assets/", "aaaaaaaaaaaaaaaa", 1761381000)),
+ "box-b": privateOnly("box-b", "169.254.169.254", `"role":"home","stamp":9,`+owner+`,`+block("/new/", "bbbbbbbbbbbbbbbb", 1761382800)),
+ }, "box-a", false},
+ {"only an undialable box publishes the host",
+ map[string]string{
+ "box-b": public("box-b", "", `"role":"home","stamp":9,`+owner+`,`+block("/new/", "bbbbbbbbbbbbbbbb", 1761382800)),
+ }, "", false},
+ {"a winning entry without assets publishes none",
+ map[string]string{
+ "box-a": public("box-a", "192.0.2.1", `"role":"home","stamp":1,`+owner+`,`+block("/assets/", "aaaaaaaaaaaaaaaa", 1761382800)),
+ "box-b": public("box-b", "192.0.2.2", `"role":"home","stamp":2,`+owner),
+ }, "box-b", false},
+ {"a route beats an alias with a higher stamp",
+ map[string]string{
+ "box-a": public("box-a", "192.0.2.1", `"role":"home",`+owner+`,`+block("/assets/", "aaaaaaaaaaaaaaaa", 1761381000)),
+ "box-b": public("box-b", "192.0.2.2", `"role":"home","alias":true,"stamp":9,`+owner+`,`+block("/img/", "bbbbbbbbbbbbbbbb", 1761382800)),
+ }, "box-a", false},
+ {"equal stamps keep the first file in key order",
+ map[string]string{
+ "box-a": public("box-a", "192.0.2.1", `"role":"home","stamp":3,`+owner+`,`+block("/assets/", "aaaaaaaaaaaaaaaa", 1761381000)),
+ "box-b": public("box-b", "192.0.2.2", `"role":"home","stamp":3,`+owner+`,`+block("/img/", "bbbbbbbbbbbbbbbb", 1761382800)),
+ }, "box-a", false},
+ {"key order is the bucket key's, not the box field's",
+ map[string]string{
+ "aaa": public("zed", "192.0.2.1", `"role":"home",`+owner+`,`+block("/assets/", "aaaaaaaaaaaaaaaa", 1761381000)),
+ "zzz": public("amy", "192.0.2.2", `"role":"home",`+owner+`,`+block("/img/", "bbbbbbbbbbbbbbbb", 1761382800)),
+ }, "zed", false},
+ {"a role this build does not know takes no part",
+ map[string]string{
+ "box-a": public("box-a", "192.0.2.1", `"role":"home","stamp":1,`+owner+`,`+block("/assets/", "aaaaaaaaaaaaaaaa", 1761381000)),
+ "box-b": public("box-b", "192.0.2.2", `"role":"read","stamp":9,`+owner+`,`+block("/img/", "bbbbbbbbbbbbbbbb", 1761382800)),
+ }, "box-a", false},
+ {"a higher-stamped box with only a private address wins in its region",
+ map[string]string{
+ "box-a": public("box-a", "192.0.2.1", `"role":"home","stamp":1,`+owner+`,`+block("/assets/", "aaaaaaaaaaaaaaaa", 1761381000)),
+ "box-b": privateOnly("box-b", "10.0.1.2", `"role":"home","stamp":9,`+owner+`,`+block("/new/", "bbbbbbbbbbbbbbbb", 1761382800)),
+ }, "box-b", true},
+ }
+ // The reader: in eu-west-1/ie on 10.0.0.0/16, homing nothing.
+ const reader = `{"v":1,"box":"reader","eip":"192.0.2.9","private_ip":"10.0.1.9","private_cidr":"10.0.0.0/16","region":"eu-west-1","placement":"ie","hosts":{}}`
+ for _, row := range rows {
+ for _, privateDial := range []bool{false, true} {
+ if row.inRegionOnly && !privateDial {
+ continue
+ }
+ t.Run(fmt.Sprintf("%s/regionHA=%v", row.name, privateDial), func(t *testing.T) {
+ s := meshTestStore(t)
+ putJSON(t, s, "control/edges/reader.json", reader)
+ for name, body := range row.files {
+ putJSON(t, s, "control/edges/"+name+".json", body)
+ }
+ m := newHomeMap(s, "reader")
+ m.privateDial = privateDial
+ refreshHomeMap(t, m)
+ edgeBox, edgeAssets := "", (*edgesAssetsView)(nil)
+ if h, ok := m.snapshot().hosts[host]; ok && h.dial {
+ edgeBox, edgeAssets = h.box, h.assets
+ }
+
+ snap, err := edgesfile.ReadSnapshot(context.Background(), s)
+ if err != nil || !snap.Complete {
+ t.Fatalf("ReadSnapshot = complete %v, %v", snap.Complete, err)
+ }
+ won, statusHas := edgesfile.ElectHomes(snap.Files)[host]
+
+ if edgeBox != row.wantBox {
+ t.Fatalf("the home map elects %q, want %q", edgeBox, row.wantBox)
+ }
+ if !statusHas {
+ if edgeBox != "" {
+ t.Fatalf("the status door elects no home, the home map elects %q", edgeBox)
+ }
+ return
+ }
+ if won.Box != edgeBox {
+ t.Fatalf("the status door elects %q, the home map elects %q", won.Box, edgeBox)
+ }
+ if !sameAssetsBlock(won.Assets, edgeAssets) {
+ t.Fatalf("the status door reports %+v, the home map holds %+v", won.Assets, edgeAssets)
+ }
+ })
+ }
+ }
+}
+
+// sameAssetsBlock compares the reader's decoded block with the edge's.
+func sameAssetsBlock(a *edgesfile.HostAssets, b *edgesAssetsView) bool {
+ if a == nil || b == nil {
+ return a == nil && b == nil
+ }
+ return slices.Equal(a.Paths, b.Paths) && a.Gen == b.Gen && a.At == b.At && a.Primary == b.Primary
+}
diff --git a/internal/edgesfile/edgesfile.go b/internal/edgesfile/edgesfile.go
index 0d0e7802d..20a896413 100644
--- a/internal/edgesfile/edgesfile.go
+++ b/internal/edgesfile/edgesfile.go
@@ -19,7 +19,9 @@
// polling and staleness machinery) and internal/steering (which reads no
// role values — since #162 it does read the per-host replica mark, but its
// decode stays its own for the same isolation reason). Both are named here
-// so the consumer list stays complete rather than merely short.
+// so the consumer list stays complete rather than merely short. The home
+// map does share the home election with the console's status door
+// (homeelect.go): the rule and the dial address, not the decoder.
package edgesfile
import (
diff --git a/internal/edgesfile/homeelect.go b/internal/edgesfile/homeelect.go
new file mode 100644
index 000000000..bb0fd6c97
--- /dev/null
+++ b/internal/edgesfile/homeelect.go
@@ -0,0 +1,160 @@
+package edgesfile
+
+import (
+ "encoding/json"
+ "slices"
+ "strings"
+)
+
+// The home election: which box's entry is THE home for a host when more
+// than one box publishes it. The edge's home map (internal/edge homemap.go
+// foldHomes) and the console's `carlos assets status` door both decide it
+// here, so the status door names the box an edge dials (#396). The edge
+// keeps its own decoder and its own fold, because the fold also merges
+// classes and excludes the edge's own box; what it shares is the rule
+// (HomeBeats) and who may take part (DialAddress).
+
+// DialPoint is the part of a box's file that says where it can be dialled:
+// its public address, its private address and network (region HA spec 2
+// §6), and the region and placement that decide which of the two a reader
+// uses.
+type DialPoint struct {
+ EIP string
+ PrivateIP string
+ PrivateCIDR string
+ Region string
+ Placement string
+}
+
+// DialAddress is where a reader dials f's box (region HA spec 2 §6). With
+// privateDial (the reader's own region HA switch) on, a box that publishes
+// the same AWS region and placement as the reader is dialled at its
+// private address, so the dial stays inside the region's network, but only
+// when that address passes PrivateAddress against the network the reader's
+// own file publishes (census ruling region-ha-2a). The home's placement
+// code is "", so two home boxes share a placement as two boxes of one named
+// region do; a home box and a named one never do. Every other box, and
+// every box with privateDial off, is dialled at its public address. self is
+// the reader's own file, which selfKnown says was found. "" is nothing to
+// dial, and a home entry of a box with nothing to dial takes no part in
+// the election.
+func DialAddress(f, self DialPoint, selfKnown, privateDial bool) string {
+ if privateDial && selfKnown && f.Region != "" &&
+ f.Region == self.Region && f.Placement == self.Placement {
+ if addr, _ := PrivateAddress(f.PrivateIP, []string{self.PrivateCIDR}); addr != "" {
+ return addr
+ }
+ }
+ return f.EIP
+}
+
+// HomeClaim is one box's entry for a host as the election orders it.
+type HomeClaim struct {
+ // Dial: the entry is a dial target, a home-role entry of a box the
+ // reader has an address for.
+ Dial bool
+ // Alias: an attached custom domain's entry (#287).
+ Alias bool
+ // Stamp is the claim's installation stamp, 0 when unstamped.
+ Stamp int64
+}
+
+// HomeBeats reports whether a later file's claim (in) takes the host from
+// the one already held (prev). Claims are offered in sorted file-key order,
+// so a duplicate claim resolves the same way on every reader. In order:
+//
+// - only a dial target can take it, and any dial target beats none;
+// - a ROUTE beats an ALIAS whatever else is true (#287);
+// - between two of the same kind, the newer installation wins: a stamped
+// claim beats an unstamped one, and a higher stamp beats a lower one
+// (region HA spec 1 HA4). A dead box's file lingers; its successor's
+// stamp is always higher, so the stale one loses without any liveness
+// rule;
+// - otherwise the earlier file keeps it.
+func HomeBeats(in, prev HomeClaim) bool {
+ if !in.Dial {
+ return false
+ }
+ if !prev.Dial {
+ return true
+ }
+ if prev.Alias != in.Alias {
+ return prev.Alias && !in.Alias
+ }
+ return in.Stamp > prev.Stamp
+}
+
+// Dialable reports whether some edge can dial f's box: DialAddress's answer
+// for the best-placed reader, an edge in the box's own region and
+// placement on its network with region HA on. A box with a public address
+// is dialable from anywhere; a box with only a private address is dialable
+// from inside its region; a box with neither is dialable from nowhere.
+func Dialable(f DialPoint) bool {
+ return DialAddress(f, f, true, true) != ""
+}
+
+// Elected is a host's winning home entry: the box that published it and
+// its assets block, nil when the winner publishes none. The block is the
+// winner's whole, never merged with a losing box's.
+type Elected struct {
+ Box string
+ Assets *HostAssets
+}
+
+// electedEntry is the part of a host entry the election reads, beside the
+// reader's Host: the installation stamp the writer publishes.
+type electedEntry struct {
+ Host
+ Stamp int64 `json:"stamp"`
+}
+
+// ElectHomes is the election as a reader that is no box (the console)
+// makes it: host -> the winning home entry, over files read by ReadSnapshot.
+// Files are taken in bucket-key order (PlacementView.Key, or Key(Box) for
+// a view built by hand), as the edge's fold takes them. Only a home-role entry of
+// a Dialable box is a claim; claims are ordered by HomeBeats. A reader that
+// is no box has no own box to leave out and no region of its own, so it
+// counts every box some edge can dial (Dialable): a box with only a private
+// address takes part, as it does for the edges of its own region. A host
+// entry that does not decode is skipped, as ReadSnapshot skips a file.
+func ElectHomes(files []PlacementView) map[string]Elected {
+ sorted := slices.Clone(files)
+ key := func(f PlacementView) string {
+ if f.Key != "" {
+ return f.Key
+ }
+ return Key(f.Box)
+ }
+ slices.SortStableFunc(sorted, func(a, b PlacementView) int { return strings.Compare(key(a), key(b)) })
+ type held struct {
+ claim HomeClaim
+ e Elected
+ }
+ won := map[string]held{}
+ for _, f := range sorted {
+ if f.Box == "" || !Dialable(f.DialPoint()) {
+ continue
+ }
+ for host, raw := range f.Hosts {
+ var in electedEntry
+ if host == "" || json.Unmarshal(raw, &in) != nil || in.Role != RoleHome {
+ continue
+ }
+ c := HomeClaim{Dial: true, Alias: in.Alias, Stamp: in.Stamp}
+ if prev, ok := won[host]; ok && !HomeBeats(c, prev.claim) {
+ continue
+ }
+ won[host] = held{claim: c, e: Elected{Box: f.Box, Assets: in.Assets}}
+ }
+ }
+ out := make(map[string]Elected, len(won))
+ for host, h := range won {
+ out[host] = h.e
+ }
+ return out
+}
+
+// DialPoint is f's dial fields.
+func (f PlacementView) DialPoint() DialPoint {
+ return DialPoint{EIP: f.EIP, PrivateIP: f.PrivateIP, PrivateCIDR: f.PrivateCIDR, Region: f.Region, Placement: f.Placement}
+}
diff --git a/internal/edgesfile/homeelect_test.go b/internal/edgesfile/homeelect_test.go
new file mode 100644
index 000000000..b08c1021d
--- /dev/null
+++ b/internal/edgesfile/homeelect_test.go
@@ -0,0 +1,68 @@
+package edgesfile
+
+import (
+ "context"
+ "testing"
+
+ "github.com/carlosframework/platform/internal/release"
+)
+
+// TestDialableIsDialAddressForSomeReader: a box is Dialable exactly when
+// DialAddress answers an address for the best-placed reader, and that is
+// what the status door's election counts (#396). A public address is
+// dialable from anywhere, a valid private address from its own region, and
+// a box with neither, or with a private address that fails PrivateAddress
+// (the metadata range, a malformed one, one outside its own network, or no
+// region to match on), from nowhere.
+func TestDialableIsDialAddressForSomeReader(t *testing.T) {
+ cases := []struct {
+ name string
+ f DialPoint
+ want bool
+ }{
+ {"a public address", DialPoint{EIP: "192.0.2.1"}, true},
+ {"a public address and a private one", DialPoint{EIP: "192.0.2.1", PrivateIP: "10.0.1.2", PrivateCIDR: "10.0.0.0/16", Region: "eu-west-1"}, true},
+ {"a private address alone", DialPoint{PrivateIP: "10.0.1.2", PrivateCIDR: "10.0.0.0/16", Region: "eu-west-1", Placement: "ie"}, true},
+ {"neither", DialPoint{Region: "eu-west-1", Placement: "ie"}, false},
+ {"a private address with no region", DialPoint{PrivateIP: "10.0.1.2", PrivateCIDR: "10.0.0.0/16"}, false},
+ {"the metadata range", DialPoint{PrivateIP: "169.254.169.254", PrivateCIDR: "169.254.0.0/16", Region: "eu-west-1"}, false},
+ {"a malformed private address", DialPoint{PrivateIP: "10.0.1", PrivateCIDR: "10.0.0.0/16", Region: "eu-west-1"}, false},
+ {"a private address outside its own network", DialPoint{PrivateIP: "10.9.1.2", PrivateCIDR: "10.0.0.0/16", Region: "eu-west-1"}, false},
+ }
+ for _, c := range cases {
+ t.Run(c.name, func(t *testing.T) {
+ if got := Dialable(c.f); got != c.want {
+ t.Fatalf("Dialable(%+v) = %v, want %v", c.f, got, c.want)
+ }
+ // An edge in another region dials the public address alone.
+ if got := DialAddress(c.f, DialPoint{Region: "us-east-1"}, true, true); got != c.f.EIP {
+ t.Fatalf("from another region: DialAddress = %q, want the public %q", got, c.f.EIP)
+ }
+ })
+ }
+}
+
+// TestReadSnapshotKeepsEachFilesKey: the election orders files by the key
+// they were read from, which need not match the box field.
+func TestReadSnapshotKeepsEachFilesKey(t *testing.T) {
+ s := release.NewDirStore(t.TempDir())
+ ctx := context.Background()
+ if _, err := s.Put(ctx, Prefix+"aaa.json", []byte(`{"v":1,"box":"zed","eip":"192.0.2.1","hosts":{"shop.example.com":{"role":"home"}}}`), ""); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := s.Put(ctx, Prefix+"zzz.json", []byte(`{"v":1,"box":"amy","eip":"192.0.2.2","hosts":{"shop.example.com":{"role":"home"}}}`), ""); err != nil {
+ t.Fatal(err)
+ }
+ snap, err := ReadSnapshot(ctx, s)
+ if err != nil || !snap.Complete || len(snap.Files) != 2 {
+ t.Fatalf("ReadSnapshot = %+v, %v", snap, err)
+ }
+ for _, f := range snap.Files {
+ if want := map[string]string{"zed": Prefix + "aaa.json", "amy": Prefix + "zzz.json"}[f.Box]; f.Key != want {
+ t.Errorf("%s: Key = %q, want %q", f.Box, f.Key, want)
+ }
+ }
+ if got := ElectHomes(snap.Files)["shop.example.com"].Box; got != "zed" {
+ t.Errorf("unstamped duplicates elect %q, want zed, the first file in key order", got)
+ }
+}
diff --git a/internal/edgesfile/snapshot.go b/internal/edgesfile/snapshot.go
index bbfd5c6b5..8a496d716 100644
--- a/internal/edgesfile/snapshot.go
+++ b/internal/edgesfile/snapshot.go
@@ -31,6 +31,15 @@ type PlacementView struct {
EIP string `json:"eip"`
Region string `json:"region"`
Placement string `json:"placement"`
+ // PrivateIP and PrivateCIDR are the box's private address and its
+ // region network (region HA spec 2 §6), absent from a writer that
+ // predates them. Read only by the home election (ElectHomes), which
+ // needs to know whether any edge can dial the box.
+ PrivateIP string `json:"private_ip"`
+ PrivateCIDR string `json:"private_cidr"`
+ // Key is not on the wire: ReadSnapshot sets it to the bucket key the
+ // file was read from, the order the home election takes files in.
+ Key string `json:"-"`
// DataBucket is the box's CARLOS_HIBERNATE_BUCKET, verbatim
// (internal/host/edgesfile.go writes it from that env and omits the key
// entirely when it is unset). It carries the move lane's actual
@@ -245,6 +254,7 @@ func ReadSnapshot(ctx context.Context, s release.Store) (Snapshot, error) {
snap.Complete = false
continue
}
+ f.Key = key
snap.Files = append(snap.Files, f)
}
return snap, nil