Add cached box roles and admission-aware serving projections
Read operator roles through the armed change-index gate with bounded retries. Publish effective admission through the existing edges writer and project it into home election and the merged cold-wake chooser. Preserve namespace reservations during startup withdrawal while keeping holder evidence separate. Task 2 focused tests, race checks, eight mutations, census, vet and cross-builds pass. Full package runs are not green; the Task 2 report records their failures and timeouts, including baseline reproductions.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
docs/superpowers/notes/census-proposal-region-ha-p3a.md+16 −3docs/superpowers/notes/census-region-ha-p3a-claims.tsv+5 −0internal/boxroles/roles.go+143 −0internal/boxroles/roles_test.go+86 −0internal/console/apiplacements.go+1 −1internal/console/boxroles_test.go+48 −0internal/console/instancesplacement.go+4 −1internal/edge/boxroles_test.go+93 −0internal/edge/homemap.go+35 −7internal/edge/wakeplacement.go+1 −1internal/edge/wakeplacement_test.go+6 −1internal/edgesfile/admission.go+34 −0internal/edgesfile/admission_test.go+45 −0internal/edgesfile/edgesfile.go+8 −6internal/edgesfile/fold.go+3 −0internal/edgesfile/homeelect.go+20 −7internal/edgesfile/snapshot.go+8 −6internal/host/agent.go+1 −0internal/host/boxroles.go+162 −0internal/host/boxroles_config.go+39 −0internal/host/boxroles_config_linux.go+32 −0internal/host/boxroles_config_other.go+9 −0internal/host/boxroles_config_test.go+55 −0internal/host/boxroles_test.go+481 −0internal/host/edgesfile.go+28 −9internal/hostenv/boxroles_test.go+9 −0internal/hostenv/hostenv.go+1 −0internal/provision/testdata/plan14-root-reads-chain.tsv+1 −1internal/provision/testdata/plan14-root-reads-region-ha-p3a.tsv+17 −2internal/release/boxroles_test.go+11 −0internal/release/changeindex.go+1 −1
Intent
<task-notification> <task-id>bsb6nlgle</task-id> <tool-use-id>toolu_01HgqYiNqrgyQZGQgfsQkqFY</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/6cb8c43c-d494-478a-8f04-1067486903df/tasks/bsb6nlgle.output</output-file> <status>completed</status> <summary>Background command "W=/home/paulca/amadan.net/carlos/platform/.claude/worktrees/region-ha-p3/.superpowers/sdd/2026-11-03-region-ha-p3a; until [ -s $W/task-1-astra-a.md ]; do sleep 60; done; cat $W/task-1-astra-a.md" completed (exit code 0)</summary> </task-notification>
<task-notification> <task-id>a414ba25549c98ed0</task-id> <tool-use-id>toolu_01La4uUmn5d4VXgd2NQv1GWg</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/6cb8c43c-d494-478a-8f04-1067486903df/tasks/a414ba25549c98ed0.output</output-file> <status>completed</status> <summary>Agent "Opus review P3a Task 1" finished</summary> <note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note> <result>**Verdict: READY AFTER FIXES.** One P1, two P2, seven P3. The full review is in `/home/paulca/amadan.net/carlos/platform/.claude/worktrees/region-ha-p3/.superpowers/sdd/2026-11-03-region-ha-p3a/task-1-review-opus.md`. - **P1 (E1), F1:** the gate approves a plan that moves the fixed box's public address. A new `aws_eip` whose `instance` or `network_interface` is the fixed instance or its network interface (ENI) gets exit 0, even when named `aws_eip.public[...]`. So does an `aws_eip_association` that names the fixed ENI and an allocation from outside the state. The relation check (`check-region-group-plan.py:316-325`) only looks at `aws_eip_association`'s `allocation_id`, `instance_id` and `public_ip`. - **P2 (E1), F2:** a move can rename a guarded resource out of the guard. `aws_eip.host` → `aws_eip.public["a"]` passes as an unchanged no-op, and a later plan that changes its `instance` passes too. Renaming `aws_security_group.host` works the same way. The move check (`:107-112`) compares only the type, not the name. - **P2 (E1/T1), F3:** other resource types can change a fixed box and are not guarded. Each of these passed with exit 0: `aws_ec2_instance_state` (stops the box), `aws_network_interface_sg_attachment` and `aws_volume_attachment` on the fixed box, and `aws_iam_role_policies_exclusive` (`role_name` is never checked). `host_auto_recover` could also be changed to terminate the box. The suggested fix is one check that refuses any change referencing a fixed ID, with an exemption for creating or deleting target-group attachments; that also closes F1. The ingress module, its contract values, the fixture root and `fixed_state_unchanged` all match the brief. No P3b work was built, and the fixed region-host files are byte-identical to `f7ca1a43`. The 16 gate tests pass. The P3s include: an empty plan gets exit 0, two mock tests are duplicates, and the VPC CIDR check counts disassociated CIDRs. Separately, the worktree has uncommitted changes I did not make, in `internal/edge`, `internal/edgesfile`, `internal/host`, `internal/release` and `internal/boxroles`. It looks like another task is running in the same worktree. My only write was the review file, and the probe scratch I used is deleted.</result> <usage><subagent_tokens>113702</subagent_tokens><tool_uses>13</tool_uses><duration_ms>296754</duration_ms></usage> </task-notification>
Attributed to this commit: 12.6 g CO₂e (1,526,151 tokens). This is an attribution, not a measurement — usage counted from this commit's own marker forward to the next one on region-ha-p3-group, never backward from it. A turn that produced more than one commit books all of its tokens to the last one, and a concurrent session on this branch can add to the same figure. Some of it was priced using the shared default rate, because no model-specific factor row exists yet for at least one model involved. The Carbon view has the repo total, which is never derived from this attribution.
diff --git a/docs/superpowers/notes/census-proposal-region-ha-p3a.md b/docs/superpowers/notes/census-proposal-region-ha-p3a.md| index 05789fe39..2f45b81f2 100644 |
| --- a/docs/superpowers/notes/census-proposal-region-ha-p3a.md |
| +++ b/docs/superpowers/notes/census-proposal-region-ha-p3a.md |
| @@ -1,11 +1,21 @@ |
| # Census approval: region-ha-p3a |
| -Ruling `census-ruling-region-ha-p3a`. The independent reviewer approves or rejects every change below, 10 with a new disposition; nothing goes to the census owner (Paul, #280, 2026-10-26). |
| +Ruling `census-ruling-region-ha-p3a`. The independent reviewer approves or rejects every change below, 13 with a new disposition; nothing goes to the census owner (Paul, #280, 2026-10-26). |
| -Envelopes re-pinned: `infra/modules/region-host/ingress`, `infra/modules/region-host/ingress/tests`, `infra/modules/region-host/ingress/tests/fixed-targets`, `infra/modules/region-host/ingress/tests/fixed-targets/tests`, `infra/modules/region-host/tests`. |
| +| unit | change | read sites | what changed | |
| +|---|---|---|---| |
| +| `internal/host/agent.go` `fastTick` | body | unchanged (1) | Run the optional desired-role reader on the existing tick after observing the armed change index; no new root path or timer, nil reader is unchanged. | |
| +| `internal/host/edgesfile.go` `edgesFileWriteClaims` | body | unchanged (65) | Publish injected effective role and admission facts, withdraw booting home/alias rows into non-serving namespace reservations, and acknowledge only successful writes; existing registry reads unchanged. | |
| + |
| +Envelopes re-pinned: `infra/modules/region-host/ingress`, `infra/modules/region-host/ingress/tests`, `infra/modules/region-host/ingress/tests/fixed-targets`, `infra/modules/region-host/ingress/tests/fixed-targets/tests`, `infra/modules/region-host/tests`, `internal/boxroles`, `internal/edge`, `internal/edgesfile`, `internal/host`, `internal/hostenv`, `internal/release`. |
| 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. |
| +Recorded dispositions, which each change must still satisfy: |
| + |
| +- `internal/host/agent.go` `fastTick`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=J1;basis=root-route;rev3=PROPOSED-s3-change-index;identity=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos);basis=observes the change index before any pass (observeIndex), runs the backstop's requested full pass and a scoped pass for moved app scopes (indexTick), and arms the canary pointer gate on the sweep (canaryPointerGate) only on a tick whose own index observation succeeded; read site unchanged, offset moved;rev3=census-ruling-stateless-replicas-1;basis=Call coordinator Tick on the existing tick before convergence; client renews held terms only at the pinned interval. Existing registry read unchanged. Final review I3: signal the owned renewal worker instead of waiting for its sequential console HTTP calls. Existing convergence and record read unchanged. |
| +- `internal/host/edgesfile.go` `edgesFileWriteClaims`: authority, task F,J1. Basis: rev3=census-ruling-self-serve-moves-1;basis=root-route;kept=F;scope=protected-decision-only; the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): region-ha-2a's body, which with the box's lifetimes switch on also publishes each served row's lifetime pair (registry:Incarnation and registry:ServingSeq, two new sites on the rows it already lists) and an alias's or served catch-all's primary's pair, and names that primary as target_host whatever the switch; a report the edge orders unstamped entries by, not a decision; no record, /data, release or claim read added; F,J1 authority retained; self-serve moves 1 Task 8;rev3=census-ruling-instance-egress-sizes-328-329;basis=#328 plan 2 Task 8: takes a localAddrs reader (instancectl.LocalAddresses in production, which reads /proc/net/fib_trie and /proc/net/if_inet6 in the agent) and publishes its non-loopback entries as the edges file's addrs before the write gate (boxAddrs, no read of its own), so an address change writes once. The same 44 sites, offsets moved; no record, /data, release or claim read added; a report the console's egress grant check reads, not a root decision; F,J1 authority retained.;rev3=census-ruling-edge-asset-cache-3;basis=starts with assets = assets.active(), so a policy whose box has not opened its asset store publishes no assets blocks and reads no manifests, and copies the decision's Primary (the route host the block was decided for, drift D4) into the published assets block; read sites unchanged (44); no read added. Merged onto main's #328 body, which takes the localAddrs reader: the assets.active() line sits after that signature and the loop passes pub and instancectl.LocalAddresses;rev3=census-ruling-region-ha-p1a;basis=the agent as carlos: the claims argument (*edgesClaims) becomes addrs (AddressSource) and the applyEdgesClaims(ctx, claims, routes, hosts) call is deleted with edgesclaims.go, which is the one whole:Route site removed: no host claim is read and every served row publishes as with region HA off; the box-address publication is the same code reading addrs.BoxAddresses() instead of claims.addrs; a report the edge reads, not a root decision; no read added; merge of origin/main d7ae1d76: main's edge asset cache plan 3 body is kept (census-ruling-edge-asset-cache-3): the first line is assets = assets.active(), so a policy whose store has not opened publishes no assets blocks and reads no manifests, and edgesFileLoop passes pub (assets.active() for that tick) in the assets argument; main's claims *edgesClaims argument is this branch's addrs AddressSource, and no edgesClaims, applyEdgesClaims or hostclaim reference remains;rev3=census-ruling-alias-wake-338;basis=#338 follow-up: skips publishing a platform alias edge.PlatformAliasFold refuses (and so anything attached to it); reads the same route listing;rev3=census-ruling-fleet-public-routes;basis=fleet public routes (spec 2026-10-29 rev 4, §4.2 writer rule): Task 6 and its fix rounds: publishes by FleetArmVerdict (via fleetRefusedFor): withheld rows left out; a forward host's path rows left out of its owner; no assets for forward rows; the alias loop replays Reload's alias fold from the served rows so a chained alias carries its root primary's owner; certRefused and parentRefused leave out a refused claim's wildcard parent (+registry:Alias x5, +registry:Host x4, +whole:Route, +whole:RouteAlias x2, +whole:RoutePath x7, +whole:WildcardDomain). Rows already read in the pass; keeps authority F,J1; publishes less, never more.;rev3=census-ruling-probe-burst-limit;basis=sets the constant BurstNotices=true on the box's own edges file (this build's edge answers probe-burst notices, so peers may send them); not from config or any read; the same 65 sites; a report other edges read, not a root decision; F,J1 authority retained; no new root read or write kind |
| + |
| New dispositions, which census-propose wrote and the reviewer checks against the unit's reads and the diff: |
| - new `infra/modules/region-host/ingress/main.tf:external`: reads +file:external; written legacy, accepted-legacy, frozen |
| @@ -18,7 +28,10 @@ New dispositions, which census-propose wrote and the reviewer checks against the |
| - new `infra/modules/region-host/ingress/variables.tf:external`: reads +file:external; written legacy, accepted-legacy, frozen |
| - new `infra/modules/region-host/ingress/versions.tf:external`: reads +file:external; written legacy, accepted-legacy, frozen |
| - new `infra/modules/region-host/tests/fixed_state_unchanged.tftest.hcl:external`: reads +file:external; written legacy, accepted-legacy, frozen |
| +- new `internal/boxroles/roles.go:Read`: reads +file:Read; written legacy, accepted-legacy, frozen |
| +- new `internal/host/boxroles.go:boxRoleReader.pass`: reads +file:Read; written legacy, accepted-legacy, frozen |
| +- new `internal/host/boxroles_config_linux.go:readRoleRegionConfig`: reads +file:Fstat, +file:Openat2, +file:ReadAll; written legacy, accepted-legacy, frozen |
| -Seal: `c68e2453bfc8afaf3794eb4c08850428982fa6954269b6b99bddfda4e6242929` → `f2d9c89885a0019f5a30651f8019bb6f0c55bf84b412e045e59e30b66b4bf32e`. |
| +Seal: `c68e2453bfc8afaf3794eb4c08850428982fa6954269b6b99bddfda4e6242929` → `a27d94a93013e3e0c9f69bacad970ece395fb39d9b0f3c7cac0c47ab55542dbf`. |
| Overlay: `internal/provision/testdata/plan14-root-reads-region-ha-p3a.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`. |
diff --git a/docs/superpowers/notes/census-region-ha-p3a-claims.tsv b/docs/superpowers/notes/census-region-ha-p3a-claims.tsv| index b0abac5f4..f6912495b 100644 |
| --- a/docs/superpowers/notes/census-region-ha-p3a-claims.tsv |
| +++ b/docs/superpowers/notes/census-region-ha-p3a-claims.tsv |
| @@ -8,3 +8,8 @@ infra/modules/region-host/ingress/tests/group_ingress.tftest.hcl:external Add pl |
| infra/modules/region-host/ingress/variables.tf:external Add ingress-only inputs and topology/CIDR validation; no root runtime reads. |
| infra/modules/region-host/ingress/versions.tf:external Declare OpenTofu and AWS provider requirements for the isolated ingress child; no root runtime reads. |
| infra/modules/region-host/tests/fixed_state_unchanged.tftest.hcl:external Add mock regression for the unchanged fixed instance/profile/SG/root-volume wiring and legacy outputs; no root runtime reads. |
| +internal/host/agent.go:fastTick Run the optional desired-role reader on the existing tick after observing the armed change index; no new root path or timer, nil reader is unchanged. |
| +internal/host/edgesfile.go:edgesFileWriteClaims Publish injected effective role and admission facts, withdraw booting home/alias rows into non-serving namespace reservations, and acknowledge only successful writes; existing registry reads unchanged. |
| +internal/boxroles/roles.go:Read Two point GETs of validated own and canonical-region desired-role keys; strict bounded parsing, errors never default to serve; no filesystem read or root authority grant. |
| +internal/host/boxroles.go:boxRoleReader.pass Apply desired roles through the startup-injected callback with one existing ReadGate and bounded retry backoff; preserve restrictions and close new starts on unknown evidence; no filesystem read. |
| +internal/host/boxroles_config_linux.go:readRoleRegionConfig Read the fixed operator-delivered /etc/carlos/region-config.json through no-symlink openat2, fstat root ownership/regular-file/non-writable checks, single-link check and 4097-byte limited read; validate explicit canonical code and unchanged raw placement, never infer from AWS. |
diff --git a/internal/boxroles/roles.go b/internal/boxroles/roles.go| new file mode 100644 |
| index 000000000..7a2edfc16 |
| --- /dev/null |
| +++ b/internal/boxroles/roles.go |
| @@ -0,0 +1,143 @@ |
| +package boxroles |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "encoding/json" |
| + "errors" |
| + "fmt" |
| + "io" |
| + "os" |
| + "regexp" |
| + "slices" |
| + "strings" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/release" |
| +) |
| + |
| +type Role string |
| + |
| +const ( |
| + Booting Role = "booting" |
| + Serve Role = "serve" |
| + Drain Role = "drain" |
| + Platform Role = "platform" |
| + Scope = "control/box-roles" |
| + MaxBody = 4096 |
| +) |
| + |
| +type Record struct { |
| + Role Role `json:"role"` |
| + By string `json:"by,omitempty"` |
| + At time.Time `json:"at,omitempty"` |
| +} |
| + |
| +var label = regexp.MustCompile(`^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$`) |
| + |
| +func ValidLabel(v string, max int) bool { return len(v) > 0 && len(v) <= max && label.MatchString(v) } |
| +func ValidateRegion(region string, configured []string) error { |
| + if !ValidLabel(region, 32) || !slices.Contains(configured, region) { |
| + return fmt.Errorf("boxroles: unconfigured region %q", region) |
| + } |
| + return nil |
| +} |
| +func Key(target string) (string, error) { |
| + value, max := target, 63 |
| + if strings.HasPrefix(target, "@region-") { |
| + value, max = strings.TrimPrefix(target, "@region-"), 32 |
| + } |
| + if !ValidLabel(value, max) { |
| + return "", fmt.Errorf("boxroles: invalid target %q", target) |
| + } |
| + return Scope + "/" + target + ".json", nil |
| +} |
| + |
| +// Read always charges both point reads, including when the first fails. |
| +func Read(ctx context.Context, s release.Store, ref, region string) (Role, error) { |
| + if !ValidLabel(ref, 63) || !ValidLabel(region, 32) { |
| + return Booting, errors.New("boxroles: invalid box or region") |
| + } |
| + own, _ := Key(ref) |
| + regional, _ := Key("@region-" + region) |
| + a, ae := read(ctx, s, own) |
| + b, be := read(ctx, s, regional) |
| + if err := errors.Join(ae, be); err != nil { |
| + return Booting, err |
| + } |
| + if a != nil { |
| + return a.Role, nil |
| + } |
| + if b != nil { |
| + return b.Role, nil |
| + } |
| + return Serve, nil |
| +} |
| +func read(ctx context.Context, s release.Store, key string) (*Record, error) { |
| + body, _, err := s.Get(ctx, key) |
| + if errors.Is(err, os.ErrNotExist) { |
| + return nil, nil |
| + } |
| + if err != nil { |
| + return nil, err |
| + } |
| + r, err := Decode(body) |
| + if err != nil { |
| + return nil, fmt.Errorf("boxroles: %s: %w", key, err) |
| + } |
| + return &r, nil |
| +} |
| +func Decode(body []byte) (Record, error) { |
| + if len(body) > MaxBody { |
| + return Record{}, errors.New("boxroles: body exceeds 4096 bytes") |
| + } |
| + // Tokenize the object to reject duplicate keys as well as unknown fields. |
| + d := json.NewDecoder(bytes.NewReader(body)) |
| + tok, err := d.Token() |
| + if err != nil || tok != json.Delim('{') { |
| + return Record{}, errors.New("boxroles: expected object") |
| + } |
| + r := Record{} |
| + seen := map[string]bool{} |
| + for d.More() { |
| + tok, err = d.Token() |
| + if err != nil { |
| + return Record{}, err |
| + } |
| + k, ok := tok.(string) |
| + if !ok || seen[k] { |
| + return Record{}, errors.New("boxroles: duplicate field") |
| + } |
| + seen[k] = true |
| + var raw json.RawMessage |
| + if err = d.Decode(&raw); err != nil { |
| + return Record{}, err |
| + } |
| + if bytes.Equal(bytes.TrimSpace(raw), []byte("null")) { |
| + return Record{}, errors.New("boxroles: null field") |
| + } |
| + switch k { |
| + case "role": |
| + err = json.Unmarshal(raw, &r.Role) |
| + case "by": |
| + err = json.Unmarshal(raw, &r.By) |
| + case "at": |
| + err = json.Unmarshal(raw, &r.At) |
| + default: |
| + return Record{}, fmt.Errorf("boxroles: unknown field %q", k) |
| + } |
| + if err != nil { |
| + return Record{}, err |
| + } |
| + } |
| + if _, err = d.Token(); err != nil { |
| + return Record{}, err |
| + } |
| + if err = d.Decode(new(any)); err != io.EOF { |
| + return Record{}, errors.New("boxroles: trailing data") |
| + } |
| + if r.Role != Serve && r.Role != Drain && r.Role != Platform { |
| + return Record{}, errors.New("boxroles: invalid desired role") |
| + } |
| + return r, nil |
| +} |
diff --git a/internal/boxroles/roles_test.go b/internal/boxroles/roles_test.go| new file mode 100644 |
| index 000000000..968bb3cfc |
| --- /dev/null |
| +++ b/internal/boxroles/roles_test.go |
| @@ -0,0 +1,86 @@ |
| +package boxroles |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "os" |
| + "strings" |
| + "testing" |
| + |
| + "github.com/carlosframework/platform/internal/release" |
| +) |
| + |
| +type roleStore struct { |
| + release.Store |
| + bodies map[string]string |
| + gets []string |
| + fail string |
| +} |
| + |
| +func (s *roleStore) Get(_ context.Context, k string) ([]byte, string, error) { |
| + s.gets = append(s.gets, k) |
| + if k == s.fail { |
| + return nil, "", errors.New("unreadable") |
| + } |
| + b, ok := s.bodies[k] |
| + if !ok { |
| + return nil, "", os.ErrNotExist |
| + } |
| + return []byte(b), "", nil |
| +} |
| +func TestRolePrecedence(t *testing.T) { |
| + for _, tc := range []struct { |
| + own, region string |
| + want Role |
| + }{ |
| + {`{"role":"serve"}`, `{"role":"drain"}`, Serve}, |
| + {"", `{"role":"platform"}`, Platform}, {"", "", Serve}, |
| + } { |
| + s := &roleStore{bodies: map[string]string{}} |
| + if tc.own != "" { |
| + s.bodies["control/box-roles/box.json"] = tc.own |
| + } |
| + if tc.region != "" { |
| + s.bodies["control/box-roles/@region-ie.json"] = tc.region |
| + } |
| + got, err := Read(context.Background(), s, "box", "ie") |
| + if err != nil || got != tc.want || len(s.gets) != 2 { |
| + t.Fatalf("role=%s err=%v gets=%v", got, err, s.gets) |
| + } |
| + } |
| +} |
| +func TestRoleUnreadableIsClosed(t *testing.T) { |
| + for _, bad := range []string{`{"role":"booting"}`, `{"role":false}`, `{"role":"serve","extra":1}`, `null`, `{}`, `{"role":"serve","by":null}`, `{"role":"serve","at":false}`, `{"role":"serve"} {}`, strings.Repeat(" ", 4097), `{"role":"serve","role":"drain"}`} { |
| + s := &roleStore{bodies: map[string]string{"control/box-roles/@region-ie.json": bad, "control/box-roles/box.json": `{"role":"serve"}`}} |
| + if _, err := Read(context.Background(), s, "box", "ie"); err == nil { |
| + t.Errorf("accepted %q", bad) |
| + } |
| + if len(s.gets) != 2 { |
| + t.Fatalf("reads %v", s.gets) |
| + } |
| + } |
| + s := &roleStore{fail: "control/box-roles/box.json"} |
| + if _, err := Read(context.Background(), s, "box", "ie"); err == nil { |
| + t.Fatal("unreadable served") |
| + } |
| + if len(s.gets) != 2 { |
| + t.Fatalf("partial errors charged: %v", s.gets) |
| + } |
| +} |
| +func TestRoleKeys(t *testing.T) { |
| + for _, v := range []string{"", "a/b", "a\\b", "..", "-box", "box-", "BOX", "a.b", strings.Repeat("a", 64), "@region-", "@region-" + strings.Repeat("a", 33)} { |
| + if _, err := Key(v); err == nil { |
| + t.Errorf("accepted %q", v) |
| + } |
| + } |
| + for _, v := range []string{"box", "g-123", "@region-ie"} { |
| + if _, err := Key(v); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + for _, region := range []string{"", "../ie", "ie/uk", "unknown"} { |
| + if err := ValidateRegion(region, []string{"ie", "uk"}); err == nil { |
| + t.Errorf("accepted region %q", region) |
| + } |
| + } |
| +} |
diff --git a/internal/console/apiplacements.go b/internal/console/apiplacements.go| index d52d96839..0548d0413 100644 |
| --- a/internal/console/apiplacements.go |
| +++ b/internal/console/apiplacements.go |
| @@ -312,7 +312,7 @@ func servingBoxes(snap edgesfile.Snapshot, code, target string) []edgesfile.Plac |
| func servingFiles(snap edgesfile.Snapshot, target string, keep func(edgesfile.PlacementView) bool) []edgesfile.PlacementView { |
| var out []edgesfile.PlacementView |
| for _, f := range snap.Files { |
| - if !f.Fresh || !keep(f) { |
| + if !f.Fresh || !keep(f) || !f.HomeEligible() { |
| continue |
| } |
| raw, ok := f.Hosts[target] |
diff --git a/internal/console/boxroles_test.go b/internal/console/boxroles_test.go| new file mode 100644 |
| index 000000000..2f24bdffc |
| --- /dev/null |
| +++ b/internal/console/boxroles_test.go |
| @@ -0,0 +1,48 @@ |
| +package console |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "github.com/carlosframework/platform/internal/edgesfile" |
| + "github.com/carlosframework/platform/internal/release" |
| + "testing" |
| +) |
| + |
| +func TestAdmissionWithdrawalWindow(t *testing.T) { |
| + ctx := context.Background() |
| + s := release.NewDirStore(t.TempDir()) |
| + for _, phase := range []string{"serve", "booting", "drain", "platform", "serve"} { |
| + body := map[string]any{"v": 1, "box": "box", "eip": "203.0.113.1", "region": "eu-west-1", "placement": "ie", "box_role": phase, "admitted": phase != "booting", "drained": false, "hosts": map[string]any{"shop.example.com": map[string]any{"role": "home"}}, "namespace": map[string]any{"shop.example.com": map[string]any{"platform": true}}} |
| + if phase == "booting" { |
| + body["hosts"] = map[string]any{} |
| + } |
| + b, _ := json.Marshal(body) |
| + _, etag, _ := s.Get(ctx, edgesfile.Key("box")) |
| + if _, err := s.Put(ctx, edgesfile.Key("box"), b, etag); err != nil { |
| + t.Fatal(err) |
| + } |
| + joined := loadEdgesJoin(ctx, s) |
| + if phase == "serve" { |
| + if len(joined["shop.example.com"]) != 1 { |
| + t.Fatal(joined) |
| + } |
| + } else if len(joined["shop.example.com"]) != 0 { |
| + t.Fatalf("%s reported serving: %v", phase, joined) |
| + } |
| + snap, err := edgesfile.ReadSnapshot(ctx, s) |
| + if err != nil || len(snap.Files) != 1 { |
| + t.Fatal(snap, err) |
| + } |
| + f := snap.Files[0] |
| + f.Fresh = true |
| + if got := servingFiles(edgesfile.Snapshot{Files: []edgesfile.PlacementView{f}}, "shop.example.com", func(edgesfile.PlacementView) bool { return true }); (len(got) == 1) != (phase == "serve") { |
| + t.Fatal(phase, got) |
| + } |
| + if phase != "serve" && foldCapability(placementCapability{}, f).Reachable { |
| + t.Fatal("closed box is placement target") |
| + } |
| + if string(f.BoxRole) != `"`+phase+`"` { |
| + t.Fatal("lost diagnostic role", string(f.BoxRole)) |
| + } |
| + } |
| +} |
diff --git a/internal/console/instancesplacement.go b/internal/console/instancesplacement.go| index 5ebd5a19f..5e5f62320 100644 |
| --- a/internal/console/instancesplacement.go |
| +++ b/internal/console/instancesplacement.go |
| @@ -48,6 +48,9 @@ type edgesFilePlacementView = edgesfile.PlacementView |
| func loadEdgesJoin(ctx context.Context, s release.Store) map[string][]servedBy { |
| out := map[string][]servedBy{} |
| for _, f := range readEdgesFilesWith(ctx, s, readEdgesSnapshotConcurrently) { |
| + if !f.HomeEligible() { |
| + continue |
| + } |
| for host := range f.Hosts { |
| out[host] = append(out[host], servedBy{Box: f.Box, Region: f.Region}) |
| } |
| @@ -196,7 +199,7 @@ func foldCapability(c placementCapability, f edgesFilePlacementView) placementCa |
| // address contributes nothing, however well configured it is. The code |
| // is still RECORDED, so an unreachable region reads as known-and-unarmed |
| // rather than as absent. |
| - if f.EIP == "" { |
| + if f.EIP == "" || !f.HomeEligible() { |
| return c |
| } |
| // Unknown is not no. An absent hibernation_configured with no |
diff --git a/internal/edge/boxroles_test.go b/internal/edge/boxroles_test.go| new file mode 100644 |
| index 000000000..78ea30621 |
| --- /dev/null |
| +++ b/internal/edge/boxroles_test.go |
| @@ -0,0 +1,93 @@ |
| +package edge |
| + |
| +import ( |
| + "encoding/json" |
| + "testing" |
| + |
| + "github.com/carlosframework/platform/internal/edgesfile" |
| +) |
| + |
| +func TestRoleServingProjection(t *testing.T) { |
| + for _, tc := range []struct { |
| + key string |
| + value any |
| + }{{"box_role", "booting"}, {"box_role", "drain"}, {"box_role", "platform"}, {"box_role", false}, {"admitted", false}, {"admitted", nil}, {"admitted", "true"}, {"drained", true}, {"drained", nil}} { |
| + peer := wakeFile("peer") |
| + peer["box_role"], peer["admitted"], peer["drained"] = "serve", true, false |
| + peer[tc.key] = tc.value |
| + m := wakeMap(t, wakeFile("self"), peer) |
| + wantWakeRefs(t, m, "self") |
| + if _, ok := m.boxInView("peer", wakeNow); !ok { |
| + t.Fatal("safety addition removed holder") |
| + } |
| + } |
| + peer := wakeFile("peer") |
| + peer["box_role"] = "serve" |
| + peer["admitted"] = true |
| + peer["drained"] = false |
| + wantWakeRefs(t, wakeMap(t, wakeFile("self"), peer), "peer", "self") |
| +} |
| +func TestRoleHomeElection(t *testing.T) { |
| + for _, role := range []string{"booting", "drain", "platform"} { |
| + closed := wakeFile("g-first") |
| + closed["box_role"] = role |
| + closed["admitted"] = role != "booting" |
| + closed["drained"] = false |
| + closed["hosts"] = map[string]any{wakeRoute.Host: map[string]any{"role": "home", "stamp": 99}} |
| + peer := wakeFile("z-peer") |
| + peer["box_role"], peer["admitted"], peer["drained"] = "serve", true, false |
| + bodies := map[string][]byte{edgesfile.Key("g-first"): wakeBody(t, closed), edgesfile.Key("z-peer"): wakeBody(t, peer)} |
| + var files []edgesfile.PlacementView |
| + for key, body := range bodies { |
| + var f edgesfile.PlacementView |
| + if err := json.Unmarshal(body, &f); err != nil { |
| + t.Fatal(err) |
| + } |
| + f.Key = key |
| + files = append(files, f) |
| + } |
| + home, ok, err := FoldedHome(bodies, "observer", wakeRoute.Host) |
| + if err != nil || !ok || home != "z-peer" { |
| + t.Fatalf("role %s elected %s %v %v", role, home, ok, err) |
| + } |
| + won, _, err := edgesfile.ElectHomesForEveryReader(files) |
| + if err != nil || won[wakeRoute.Host].Box != "z-peer" { |
| + t.Fatalf("console %v %v", won, err) |
| + } |
| + delete(bodies, edgesfile.Key("z-peer")) |
| + if home, ok, err = FoldedHome(bodies, "observer", wakeRoute.Host); err != nil || ok { |
| + t.Fatalf("closed home %s %v %v", home, ok, err) |
| + } |
| + } |
| +} |
| + |
| +func TestAdmissionWithdrawalWindow(t *testing.T) { |
| + // These are the writer's namespace-only bytes during a fixed restart. |
| + // The real fold and wildcard-parent readers must keep their namespace. |
| + for _, admitted := range []bool{true, false, true} { |
| + f := wakeFile("g-first") |
| + f["box_role"] = "serve" |
| + f["admitted"] = admitted |
| + f["drained"] = false |
| + if admitted { |
| + f["hosts"] = map[string]any{"shop.example.com": map[string]any{"role": "home", "platform": true}, "*.customer.example.com": map[string]any{"role": "wildcard", "wildcard": true}} |
| + } else { |
| + f["box_role"] = "booting" |
| + f["hosts"] = map[string]any{} |
| + f["namespace"] = map[string]any{"shop.example.com": map[string]any{"platform": true}, "*.customer.example.com": map[string]any{"wildcard": true}} |
| + } |
| + alias := wakeFile("z-alias") |
| + alias["hosts"] = map[string]any{"shop.example.com": map[string]any{"role": "home", "alias": true, "stamp": 100}} |
| + m := wakeMap(t, wakeFile("self"), f, alias) |
| + if hosts := m.Hosts(); len(hosts) != 1 || hosts[0] != "shop.example.com" { |
| + t.Fatalf("parent changed %v", hosts) |
| + } |
| + if parents := m.WildcardParents(); len(parents) != 1 || parents[0] != "customer.example.com" { |
| + t.Fatalf("delegated parents changed %v", parents) |
| + } |
| + _, box, ok := m.Home("shop.example.com") |
| + if ok != admitted || (ok && box != "g-first") { |
| + t.Fatalf("alias takeover %s %v", box, ok) |
| + } |
| + } |
| +} |
diff --git a/internal/edge/homemap.go b/internal/edge/homemap.go| index ac0170d8c..3e7ce6195 100644 |
| --- a/internal/edge/homemap.go |
| +++ b/internal/edge/homemap.go |
| @@ -133,11 +133,13 @@ var ( |
| // version. Additive growth on the writer's side lands here as fields this |
| // decoder ignores, which is the point. |
| type edgesFileView struct { |
| - etag string |
| - V int `json:"v"` |
| - Box string `json:"box"` |
| - EIP string `json:"eip"` |
| - Hosts map[string]edgesHostView `json:"hosts"` |
| + edgesfile.AdmissionFields |
| + Namespace map[string]edgesfile.NamespaceHost `json:"namespace,omitempty"` |
| + etag string |
| + V int `json:"v"` |
| + Box string `json:"box"` |
| + EIP string `json:"eip"` |
| + Hosts map[string]edgesHostView `json:"hosts"` |
| // PrivateIP, PrivateCIDR, Region and Placement choose the dial address |
| // (region HA spec 2 §6, edgesfile.Reader.Dial). All are absent from a writer that |
| // predates them, and the dial is then EIP, as before. |
| @@ -164,7 +166,6 @@ type edgesFileView struct { |
| 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"` |
| // placementNull is an explicit "placement": null. The holder decoder |
| // reads it as "" as before; cold-wake placement refuses it, because an |
| @@ -863,13 +864,36 @@ func foldHomes(files map[string]edgesFileView, self string, privateDial bool) (m |
| } |
| reader := edgesfile.Reader{Box: self, Self: own.dialPoint(), SelfKnown: ownKnown, PrivateDial: privateDial} |
| hosts := make(map[string]homeEntry) |
| + reserved := map[string]bool{} |
| + for _, f := range files { |
| + for host := range f.Namespace { |
| + reserved[host] = true |
| + } |
| + for host, h := range f.Hosts { |
| + if !f.HomeEligible() && h.Role == edgeRoleHome && !h.Alias { |
| + reserved[host] = true |
| + } |
| + } |
| + } |
| for _, k := range keys { |
| f := files[k] |
| if f.Box == "" || f.Box == self { |
| continue |
| } |
| addr := reader.Dial(f.dialPoint()) |
| + entries := make(map[string]edgesHostView, len(f.Hosts)+len(f.Namespace)) |
| for host, h := range f.Hosts { |
| + entries[host] = h |
| + } |
| + for host, n := range f.Namespace { |
| + if _, ok := entries[host]; !ok { |
| + entries[host] = edgesHostView{Role: "reserved", Platform: n.Platform, Wildcard: n.Wildcard} |
| + } |
| + } |
| + for host, h := range entries { |
| + if h.Alias && reserved[host] { |
| + continue |
| + } |
| if host == "" { |
| continue |
| } |
| @@ -884,6 +908,10 @@ func foldHomes(files map[string]edgesFileView, self string, privateDial bool) (m |
| } |
| h.Role = edgeRoleWildcard |
| } |
| + case "reserved": |
| + if _, fromHosts := f.Hosts[host]; fromHosts { |
| + continue |
| + } |
| case edgeRoleWildcard: |
| // The cert-only role is defined for marked catch-all keys |
| // alone; on an exact key it would be a KnownHost admission |
| @@ -894,7 +922,7 @@ func foldHomes(files map[string]edgesFileView, self string, privateDial bool) (m |
| default: |
| continue |
| } |
| - in := homeEntry{eip: addr, box: f.Box, platform: h.Platform && !h.Alias && !h.Wildcard, alias: h.Alias, wildcard: h.Wildcard, dial: h.Role == edgeRoleHome, |
| + in := homeEntry{eip: addr, box: f.Box, platform: h.Platform && !h.Alias && !h.Wildcard, alias: h.Alias, wildcard: h.Wildcard, dial: h.Role == edgeRoleHome && f.HomeEligible(), |
| account: h.Account, app: h.App, stamp: h.Stamp, incarnation: h.Incarnation, servingSeq: h.ServingSeq, targetHost: h.TargetHost, assets: h.Assets} |
| prev, dup := hosts[host] |
| if !dup { |
diff --git a/internal/edge/wakeplacement.go b/internal/edge/wakeplacement.go| index b15b2822f..c0d606326 100644 |
| --- a/internal/edge/wakeplacement.go |
| +++ b/internal/edge/wakeplacement.go |
| @@ -37,7 +37,7 @@ func decodeWakePlacement(f edgesFileView) wakePlacementFields { |
| 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.localDenied = !roleOK || !drainingOK || !drainedOK || role != "serve" || draining || drained || !f.HomeEligible() |
| p.valid = roleOK && drainingOK && drainedOK |
| p.valid = placementField(f.Generation, &p.generation) && p.valid |
| var capabilities []json.RawMessage |
diff --git a/internal/edge/wakeplacement_test.go b/internal/edge/wakeplacement_test.go| index efaea3297..698c59a07 100644 |
| --- a/internal/edge/wakeplacement_test.go |
| +++ b/internal/edge/wakeplacement_test.go |
| @@ -351,7 +351,12 @@ func TestWakeSnapshotMalformedAdditionsPreserveHolder(t *testing.T) { |
| if _, ok := m.boxInView("peer", wakeNow); !ok { |
| t.Fatal("malformed addition removed holder") |
| } |
| - if addr, _, ok := m.Home(wakeRoute.Host); !ok || addr == "" { |
| + addr, _, ok := m.Home(wakeRoute.Host) |
| + if tc.name == "drained" { |
| + if ok { |
| + t.Fatal("malformed safety field won a home election") |
| + } |
| + } else if !ok || addr == "" { |
| t.Fatal("malformed addition removed folded home") |
| } |
| }) |
diff --git a/internal/edgesfile/admission.go b/internal/edgesfile/admission.go| new file mode 100644 |
| index 000000000..1e6070e8b |
| --- /dev/null |
| +++ b/internal/edgesfile/admission.go |
| @@ -0,0 +1,34 @@ |
| +package edgesfile |
| + |
| +import ( |
| + "bytes" |
| + "encoding/json" |
| +) |
| + |
| +// AdmissionFields leaves malformed additions available to the serving |
| +// projection without discarding a file needed to diagnose a lease holder. |
| +type AdmissionFields struct { |
| + BoxRole json.RawMessage `json:"box_role,omitempty"` |
| + Admitted json.RawMessage `json:"admitted,omitempty"` |
| + Drained json.RawMessage `json:"drained,omitempty"` |
| +} |
| + |
| +func admissionField[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 (f AdmissionFields) HomeEligible() bool { |
| + role, admitted, drained := "serve", true, false |
| + if len(f.BoxRole) > 0 || len(f.Admitted) > 0 { |
| + if len(f.BoxRole) == 0 || len(f.Admitted) == 0 || len(f.Drained) == 0 { |
| + return false |
| + } |
| + } |
| + return admissionField(f.BoxRole, &role) && admissionField(f.Admitted, &admitted) && admissionField(f.Drained, &drained) && role == "serve" && admitted && !drained |
| +} |
| + |
| +// NamespaceHost preserves name ownership during startup withdrawal. It |
| +// carries no address, owner, alias target or serving role. |
| +type NamespaceHost struct { |
| + Platform bool `json:"platform,omitempty"` |
| + Wildcard bool `json:"wildcard,omitempty"` |
| +} |
diff --git a/internal/edgesfile/admission_test.go b/internal/edgesfile/admission_test.go| new file mode 100644 |
| index 000000000..6c92611e3 |
| --- /dev/null |
| +++ b/internal/edgesfile/admission_test.go |
| @@ -0,0 +1,45 @@ |
| +package edgesfile |
| + |
| +import ( |
| + "encoding/json" |
| + "testing" |
| +) |
| + |
| +func TestRoleFieldsAreNotHostRoles(t *testing.T) { |
| + for _, tc := range []struct { |
| + fields string |
| + eligible bool |
| + }{ |
| + {``, true}, |
| + {`,"box_role":"serve","admitted":true,"drained":false`, true}, |
| + {`,"box_role":"serve","admitted":false,"drained":false`, false}, |
| + {`,"box_role":"serve","admitted":true,"drained":true`, false}, |
| + {`,"box_role":"drain","admitted":true,"drained":false`, false}, |
| + {`,"box_role":"platform","admitted":true,"drained":false`, false}, |
| + {`,"box_role":"booting","admitted":false,"drained":false`, false}, |
| + {`,"box_role":"serve"`, false}, |
| + {`,"admitted":false`, false}, |
| + {`,"box_role":false,"admitted":true,"drained":false`, false}, |
| + {`,"box_role":"serve","admitted":null,"drained":false`, false}, |
| + } { |
| + b := []byte(`{"v":1,"box":"box","hosts":{"shop.example.com":{"role":"home"}}` + tc.fields + `}`) |
| + f, err := Parse(b) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if f.Hosts["shop.example.com"].Role != "home" || f.HomeEligible() != tc.eligible { |
| + t.Fatalf("parse %s: %+v", b, f) |
| + } |
| + var p PlacementView |
| + if err = json.Unmarshal(b, &p); err != nil { |
| + t.Fatal(err) |
| + } |
| + if p.HomeEligible() != tc.eligible { |
| + t.Fatal(string(b)) |
| + } |
| + choice := (Snapshot{Files: []PlacementView{p}}).BoxChoice() |
| + if choice.Boxes[0].Draining == tc.eligible { |
| + t.Fatal("placement did not close", string(b)) |
| + } |
| + } |
| +} |
diff --git a/internal/edgesfile/edgesfile.go b/internal/edgesfile/edgesfile.go| index c6691b287..fc87da059 100644 |
| --- a/internal/edgesfile/edgesfile.go |
| +++ b/internal/edgesfile/edgesfile.go |
| @@ -86,12 +86,14 @@ type HostAssets struct { |
| // File is one box's published file. |
| type File struct { |
| - V int `json:"v"` |
| - Box string `json:"box"` |
| - EIP string `json:"eip"` |
| - Region string `json:"region,omitempty"` |
| - Generation string `json:"generation,omitempty"` |
| - Hosts map[string]Host `json:"hosts"` |
| + AdmissionFields |
| + Namespace map[string]NamespaceHost `json:"namespace,omitempty"` |
| + V int `json:"v"` |
| + Box string `json:"box"` |
| + EIP string `json:"eip"` |
| + Region string `json:"region,omitempty"` |
| + Generation string `json:"generation,omitempty"` |
| + Hosts map[string]Host `json:"hosts"` |
| // Addrs is every non-loopback address the box holds, each a bare |
| // address or a prefix (#328). nil is absent or null: a writer that |
| // predates the field, or a box whose read failed. Empty is a box with |
diff --git a/internal/edgesfile/fold.go b/internal/edgesfile/fold.go| index aea71c76d..9dbd1d488 100644 |
| --- a/internal/edgesfile/fold.go |
| +++ b/internal/edgesfile/fold.go |
| @@ -190,6 +190,9 @@ func DeploymentRoutesComplete(ctx context.Context, s release.Store, now time.Tim |
| continue // no fresh snapshot: not evidence of a live route |
| } |
| joined++ |
| + for host := range f.Namespace { |
| + out[host] = true |
| + } |
| for host, h := range f.Hosts { |
| if h.Role == RoleHome && !h.Alias { |
| out[host] = true |
diff --git a/internal/edgesfile/homeelect.go b/internal/edgesfile/homeelect.go| index 86395456c..fc03e0457 100644 |
| --- a/internal/edgesfile/homeelect.go |
| +++ b/internal/edgesfile/homeelect.go |
| @@ -136,10 +136,12 @@ type electedEntry struct { |
| // electFile is one file's entries, decoded once for every reader. |
| type electFile struct { |
| - key string |
| - box string |
| - dial DialPoint |
| - hosts map[string]electedEntry |
| + eligible bool |
| + namespace map[string]NamespaceHost |
| + key string |
| + box string |
| + dial DialPoint |
| + hosts map[string]electedEntry |
| } |
| // decodeForElection decodes every host entry of every file, in bucket-key |
| @@ -160,7 +162,7 @@ func decodeForElection(files []PlacementView) ([]electFile, error) { |
| slices.SortStableFunc(sorted, func(a, b PlacementView) int { return strings.Compare(key(a), key(b)) }) |
| out := make([]electFile, 0, len(sorted)) |
| for _, f := range sorted { |
| - ef := electFile{key: key(f), box: f.Box, dial: f.DialPoint(), hosts: make(map[string]electedEntry, len(f.Hosts))} |
| + ef := electFile{eligible: f.HomeEligible(), namespace: f.Namespace, key: key(f), box: f.Box, dial: f.DialPoint(), hosts: make(map[string]electedEntry, len(f.Hosts))} |
| for host, raw := range f.Hosts { |
| var in electedEntry |
| if err := json.Unmarshal(raw, &in); err != nil { |
| @@ -182,12 +184,23 @@ func elect(files []electFile, r Reader) map[string]Elected { |
| e Elected |
| } |
| won := map[string]held{} |
| + reserved := map[string]bool{} |
| for _, f := range files { |
| - if f.box == "" || f.box == r.Box || r.Dial(f.dial) == "" { |
| + for host := range f.namespace { |
| + reserved[host] = true |
| + } |
| + for host, h := range f.hosts { |
| + if !f.eligible && h.Role == RoleHome && !h.Alias { |
| + reserved[host] = true |
| + } |
| + } |
| + } |
| + for _, f := range files { |
| + if !f.eligible || f.box == "" || f.box == r.Box || r.Dial(f.dial) == "" { |
| continue |
| } |
| for host, in := range f.hosts { |
| - if host == "" || in.Role != RoleHome { |
| + if host == "" || in.Role != RoleHome || (in.Alias && reserved[host]) { |
| continue |
| } |
| c := HomeClaim{Dial: true, Alias: in.Alias, Stamp: in.Stamp, |
diff --git a/internal/edgesfile/snapshot.go b/internal/edgesfile/snapshot.go| index e8f4a5435..b0d346801 100644 |
| --- a/internal/edgesfile/snapshot.go |
| +++ b/internal/edgesfile/snapshot.go |
| @@ -26,11 +26,13 @@ import ( |
| // capacity, and "where is this instance" is the question, not "who is its |
| // write home" (that is the home map's question, internal/edge). |
| type PlacementView struct { |
| - V int `json:"v"` |
| - Box string `json:"box"` |
| - EIP string `json:"eip"` |
| - Region string `json:"region"` |
| - Placement string `json:"placement"` |
| + AdmissionFields |
| + Namespace map[string]NamespaceHost `json:"namespace,omitempty"` |
| + V int `json:"v"` |
| + Box string `json:"box"` |
| + 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 |
| @@ -284,7 +286,7 @@ func (s Snapshot) BoxChoice() boxchoice.Snapshot { |
| Box: f.Box, BoxID: f.BoxID, EIP: f.EIP, Region: f.Region, Placement: f.Placement, |
| HibernationConfigured: f.HibernationConfigured, ServesSharedPool: f.ServesSharedPool, |
| AcceptsInbound: f.AcceptsInbound, SecretsKeyFP: f.SecretsKeyFP, Capabilities: f.Capabilities, |
| - Draining: f.Draining, Generation: f.Generation, Fresh: f.Fresh, |
| + Draining: f.Draining || !f.HomeEligible(), Generation: f.Generation, Fresh: f.Fresh, |
| } |
| if f.Headroom != nil { |
| b.Headroom = &boxchoice.Headroom{MemFreeMiB: f.Headroom.MemFreeMiB, DiskFreeMiB: f.Headroom.DiskFreeMiB, |
diff --git a/internal/host/agent.go b/internal/host/agent.go| index 521c5c770..eda8ba425 100644 |
| --- a/internal/host/agent.go |
| +++ b/internal/host/agent.go |
| @@ -2981,6 +2981,7 @@ func fastTick(ctx context.Context, d *fastDeps, now time.Time) { |
| // The index is observed BEFORE any pass this tick runs, so a pass covers |
| // at least what was observed and indexActed can take it afterwards. |
| obs, indexOK := d.observeIndex(ctx) |
| + armedBoxRoleReader.Load().pass(ctx, now) |
| fullRan := false |
| doc, _, err := release.ReadSerial(ctx, d.store) |
| switch { |
diff --git a/internal/host/boxroles.go b/internal/host/boxroles.go| new file mode 100644 |
| index 000000000..50c66383f |
| --- /dev/null |
| +++ b/internal/host/boxroles.go |
| @@ -0,0 +1,162 @@ |
| +package host |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "errors" |
| + "fmt" |
| + "log" |
| + "strings" |
| + "sync" |
| + "sync/atomic" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/boxroles" |
| + "github.com/carlosframework/platform/internal/edgesfile" |
| + "github.com/carlosframework/platform/internal/release" |
| +) |
| + |
| +// Task 3 installs these before starting the agent loops. A nil source is |
| +// switch-off; neither roles nor publication change on a legacy fixed box. |
| +type edgesRoleSource interface { |
| + EdgesRole() (boxroles.Role, bool, bool) |
| + EdgesPublished() |
| +} |
| +type boxRolePublisher struct{ Source edgesRoleSource } |
| + |
| +var armedBoxRolePublisher atomic.Pointer[boxRolePublisher] |
| +var armedBoxRoleReader atomic.Pointer[boxRoleReader] |
| + |
| +type boxRoleReader struct { |
| + mu sync.Mutex |
| + store release.Store |
| + watch *release.ChangeWatch |
| + gate *release.ReadGate |
| + ref, region string |
| + apply func(boxroles.Role, bool) error |
| + role boxroles.Role |
| + retryAt time.Time |
| + backoff time.Duration |
| +} |
| + |
| +func newBoxRoleReader(getenv func(string) string, w *release.ChangeWatch, s release.Store, ref, region string, apply func(boxroles.Role, bool) error) (*boxRoleReader, error) { |
| + if getenv("CARLOS_GROUP_ADMISSION") != "1" { |
| + return nil, nil |
| + } |
| + if !changeIndexArmed(getenv) || w == nil { |
| + return nil, errors.New("tenant admission is closed. CARLOS_CHANGE_INDEX=read and an armed change watch are required. set CARLOS_CHANGE_INDEX=read and fix the change watch, or remove CARLOS_GROUP_ADMISSION=1") |
| + } |
| + if !boxroles.ValidLabel(ref, 63) || !boxroles.ValidLabel(region, 32) || s == nil || apply == nil { |
| + return nil, errors.New("boxroles: invalid reader configuration") |
| + } |
| + return &boxRoleReader{store: s, watch: w, gate: release.NewReadGate(w, release.ChangeIndexBackstop), ref: ref, region: region, apply: apply, role: boxroles.Booting}, nil |
| +} |
| +func (r *boxRoleReader) pass(ctx context.Context, now time.Time) { |
| + if r == nil { |
| + return |
| + } |
| + r.mu.Lock() |
| + defer r.mu.Unlock() |
| + if now.Before(r.retryAt) { |
| + return |
| + } |
| + gen, due := r.gate.Due(boxroles.Scope, now) |
| + if !due && r.backoff == 0 { |
| + return |
| + } |
| + role, err := boxroles.Read(ctx, r.store, r.ref, r.region) |
| + if err == nil && !r.watch.Usable() { |
| + err = errors.New("boxroles: change watch is unusable") |
| + } |
| + if err == nil { |
| + err = r.apply(role, true) |
| + } |
| + if err != nil { |
| + // Keep the last restriction, while the separate known bit closes new starts. |
| + _ = r.apply(r.role, false) |
| + log.Printf("could not read the desired role. keeping the last restriction and starting no new tenant work: %v", err) |
| + if r.backoff == 0 { |
| + r.backoff = 5 * time.Second |
| + } |
| + r.retryAt = now.Add(r.backoff) |
| + r.backoff = min(2*r.backoff, time.Minute) |
| + return |
| + } |
| + r.role = role |
| + r.retryAt = time.Time{} |
| + r.backoff = 0 |
| + r.gate.Mark(boxroles.Scope, gen, now, true) |
| +} |
| + |
| +func withBoxRole(f edgesFile, last []byte) edgesFile { |
| + if f.RoleSource == nil { |
| + return f |
| + } |
| + role, admitted, drained := f.RoleSource.EdgesRole() |
| + if !admitted || (role != boxroles.Serve && role != boxroles.Drain && role != boxroles.Platform) { |
| + role, admitted, drained = boxroles.Booting, false, false |
| + } |
| + f.BoxRole, f.Admitted, f.Drained = role, &admitted, &drained |
| + if role != boxroles.Booting { |
| + return f |
| + } |
| + f.Namespace = map[string]edgesfile.NamespaceHost{} |
| + reserve := func(hosts map[string]edgeHost) { |
| + for host, h := range hosts { |
| + if !h.Alias || h.Wildcard { |
| + n := f.Namespace[host] |
| + n.Platform = n.Platform || (h.Platform && !h.Alias) |
| + n.Wildcard = n.Wildcard || h.Wildcard |
| + f.Namespace[host] = n |
| + } |
| + } |
| + } |
| + var prior edgesFile |
| + if json.Unmarshal(last, &prior) == nil { |
| + for host, n := range prior.Namespace { |
| + f.Namespace[host] = n |
| + } |
| + reserve(prior.Hosts) |
| + } |
| + reserve(f.Hosts) |
| + f.Hosts = map[string]edgeHost{} |
| + return f |
| +} |
| + |
| +// armBoxRoles is called by admission startup after armChangeIndex. A |
| +// configuration refusal leaves no reader installed and makes no role GETs. |
| +func armBoxRoles(ctx context.Context, getenv func(string) string, ref string, apply func(boxroles.Role, bool) error) error { |
| + if getenv("CARLOS_GROUP_ADMISSION") != "1" { |
| + return nil |
| + } |
| + w := armedChangeWatch.Load() |
| + if !changeIndexArmed(getenv) || w == nil { |
| + _, err := newBoxRoleReader(getenv, w, nil, ref, "", apply) |
| + return err |
| + } |
| + c, err := readRoleRegionConfig(roleRegionConfigPath, strings.TrimSpace(getenv("CARLOS_REGION"))) |
| + if err != nil { |
| + return err |
| + } |
| + s, err := openDeployStore(ctx) |
| + if err != nil { |
| + return err |
| + } |
| + r, err := newBoxRoleReader(getenv, w, s, ref, c.RegionCode, apply) |
| + if err != nil { |
| + return err |
| + } |
| + armedBoxRoleReader.Store(r) |
| + r.pass(ctx, time.Now()) |
| + return nil |
| +} |
| + |
| +// dueWithRole uses the existing publication schedule and its retry budget. |
| +func (s *edgesLoopState) dueWithRole(now time.Time, key string, fpOK, assetsDue bool, ident edgesFile) bool { |
| + if ident.RoleSource != nil { |
| + role, admitted, drained := ident.RoleSource.EdgesRole() |
| + key += fmt.Sprintf("|%s|%t|%t", role, admitted, drained) |
| + assetsDue = assetsDue || ident.RolePublishRequired |
| + } |
| + return s.dueWith(now, key, fpOK, assetsDue) |
| +} |
diff --git a/internal/host/boxroles_config.go b/internal/host/boxroles_config.go| new file mode 100644 |
| index 000000000..66dda0f0f |
| --- /dev/null |
| +++ b/internal/host/boxroles_config.go |
| @@ -0,0 +1,39 @@ |
| +package host |
| + |
| +import ( |
| + "bytes" |
| + "encoding/json" |
| + "errors" |
| + "io" |
| + |
| + "github.com/carlosframework/platform/internal/boxroles" |
| +) |
| + |
| +const roleRegionConfigPath = "/etc/carlos/region-config.json" |
| + |
| +// RegionCode is the operator's canonical deployment code. Placement keeps |
| +// the record scope, including the empty home scope, without translation. |
| +type roleRegionConfig struct { |
| + V int `json:"v"` |
| + RegionCode string `json:"region_code"` |
| + Placement *string `json:"placement"` |
| +} |
| + |
| +func parseRoleRegionConfig(body []byte, placement string) (roleRegionConfig, error) { |
| + var c roleRegionConfig |
| + if len(body) > 4096 { |
| + return c, errors.New("boxroles: region config exceeds 4096 bytes") |
| + } |
| + d := json.NewDecoder(bytes.NewReader(body)) |
| + d.DisallowUnknownFields() |
| + if err := d.Decode(&c); err != nil { |
| + return c, err |
| + } |
| + if err := d.Decode(new(any)); err != io.EOF { |
| + return c, errors.New("boxroles: trailing region config") |
| + } |
| + if c.V != 1 || !boxroles.ValidLabel(c.RegionCode, 32) || c.Placement == nil || *c.Placement != placement || (placement != "" && c.RegionCode != placement) { |
| + return c, errors.New("boxroles: invalid canonical region or placement") |
| + } |
| + return c, nil |
| +} |
diff --git a/internal/host/boxroles_config_linux.go b/internal/host/boxroles_config_linux.go| new file mode 100644 |
| index 000000000..0a403fe70 |
| --- /dev/null |
| +++ b/internal/host/boxroles_config_linux.go |
| @@ -0,0 +1,32 @@ |
| +//go:build linux |
| + |
| +package host |
| + |
| +import ( |
| + "errors" |
| + "io" |
| + "os" |
| + |
| + "golang.org/x/sys/unix" |
| +) |
| + |
| +func readRoleRegionConfig(path, placement string) (roleRegionConfig, error) { |
| + fd, err := unix.Openat2(unix.AT_FDCWD, path, &unix.OpenHow{Flags: unix.O_RDONLY | unix.O_CLOEXEC | unix.O_NOFOLLOW | unix.O_NONBLOCK, Resolve: unix.RESOLVE_NO_SYMLINKS | unix.RESOLVE_NO_MAGICLINKS}) |
| + if err != nil { |
| + return roleRegionConfig{}, err |
| + } |
| + f := os.NewFile(uintptr(fd), path) |
| + defer f.Close() |
| + var st unix.Stat_t |
| + if err = unix.Fstat(fd, &st); err != nil { |
| + return roleRegionConfig{}, err |
| + } |
| + if st.Uid != 0 || st.Mode&unix.S_IFMT != unix.S_IFREG || st.Mode&0022 != 0 || st.Nlink != 1 { |
| + return roleRegionConfig{}, errors.New("boxroles: region config must be a root-owned regular file without group or other write access") |
| + } |
| + body, err := io.ReadAll(io.LimitReader(f, 4097)) |
| + if err != nil { |
| + return roleRegionConfig{}, err |
| + } |
| + return parseRoleRegionConfig(body, placement) |
| +} |
diff --git a/internal/host/boxroles_config_other.go b/internal/host/boxroles_config_other.go| new file mode 100644 |
| index 000000000..0dfc25df0 |
| --- /dev/null |
| +++ b/internal/host/boxroles_config_other.go |
| @@ -0,0 +1,9 @@ |
| +//go:build !linux |
| + |
| +package host |
| + |
| +import "errors" |
| + |
| +func readRoleRegionConfig(path, placement string) (roleRegionConfig, error) { |
| + return roleRegionConfig{}, errors.New("boxroles: protected region config requires Linux") |
| +} |
diff --git a/internal/host/boxroles_config_test.go b/internal/host/boxroles_config_test.go| new file mode 100644 |
| index 000000000..dce9ffe22 |
| --- /dev/null |
| +++ b/internal/host/boxroles_config_test.go |
| @@ -0,0 +1,55 @@ |
| +package host |
| + |
| +import ( |
| + "os" |
| + "path/filepath" |
| + "runtime" |
| + "testing" |
| +) |
| + |
| +func TestRoleRegionConfig(t *testing.T) { |
| + for _, body := range []string{`{"v":1,"region_code":"ie","placement":""}`, `{"v":1,"region_code":"uk","placement":"uk"}`} { |
| + placement := "" |
| + if body == `{"v":1,"region_code":"uk","placement":"uk"}` { |
| + placement = "uk" |
| + } |
| + if _, err := parseRoleRegionConfig([]byte(body), placement); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + for _, body := range []string{`{}`, `{"v":2,"region_code":"ie","placement":""}`, `{"v":1,"region_code":"","placement":""}`, `{"v":1,"region_code":"../ie","placement":""}`, `{"v":1,"region_code":"ie","placement":"uk"}`, `{"v":1,"region_code":"ie","placement":"","extra":true}`, `{"v":1,"region_code":"ie","placement":null}`, `{"v":1,"region_code":"ie"}`} { |
| + if _, err := parseRoleRegionConfig([]byte(body), ""); err == nil { |
| + t.Fatalf("accepted %s", body) |
| + } |
| + } |
| +} |
| + |
| +func TestRoleConfigRefusesUntrustedFile(t *testing.T) { |
| + if runtime.GOOS != "linux" { |
| + t.Skip("Linux protected configuration") |
| + } |
| + dir := t.TempDir() |
| + path := filepath.Join(dir, "region-config.json") |
| + body := []byte(`{"v":1,"region_code":"ie","placement":""}`) |
| + if err := os.WriteFile(path, body, 0666); err != nil { |
| + t.Fatal(err) |
| + } |
| + if os.Getuid() != 0 { |
| + if _, err := readRoleRegionConfig(path, ""); err == nil { |
| + t.Fatal("accepted agent-owned config") |
| + } |
| + } |
| + if err := os.Chmod(path, 0666); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := readRoleRegionConfig(path, ""); err == nil { |
| + t.Fatal("accepted writable config") |
| + } |
| + link := filepath.Join(dir, "link") |
| + if err := os.Symlink(path, link); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := readRoleRegionConfig(link, ""); err == nil { |
| + t.Fatal("accepted symlink") |
| + } |
| +} |
diff --git a/internal/host/boxroles_test.go b/internal/host/boxroles_test.go| new file mode 100644 |
| index 000000000..8b9a1c417 |
| --- /dev/null |
| +++ b/internal/host/boxroles_test.go |
| @@ -0,0 +1,481 @@ |
| +package host |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "errors" |
| + "github.com/carlosframework/platform/internal/boxroles" |
| + "github.com/carlosframework/platform/internal/domains" |
| + "github.com/carlosframework/platform/internal/edge" |
| + "github.com/carlosframework/platform/internal/edgesfile" |
| + "github.com/carlosframework/platform/internal/registry" |
| + "github.com/carlosframework/platform/internal/release" |
| + "github.com/carlosframework/platform/internal/status" |
| + "strings" |
| + "testing" |
| + "time" |
| +) |
| + |
| +type roleReadStore struct { |
| + *release.DirStore |
| + root string |
| + gets int |
| + fail string |
| + during func() |
| +} |
| + |
| +func (s *roleReadStore) Get(ctx context.Context, k string) ([]byte, string, error) { |
| + if strings.HasPrefix(k, boxroles.Scope+"/") { |
| + s.gets++ |
| + if s.during != nil { |
| + f := s.during |
| + s.during = nil |
| + f() |
| + } |
| + if s.fail == k { |
| + return nil, "", errors.New("read failed") |
| + } |
| + } |
| + return s.DirStore.Get(ctx, k) |
| +} |
| +func roleEnv(k string) string { |
| + switch k { |
| + case "CARLOS_GROUP_ADMISSION": |
| + return "1" |
| + case "CARLOS_CHANGE_INDEX": |
| + return "read" |
| + } |
| + return "" |
| +} |
| +func roleReaderFixture(t *testing.T) (*boxRoleReader, *roleReadStore, *release.ChangeWatch, *boxroles.Role, *bool) { |
| + t.Helper() |
| + dir := t.TempDir() |
| + s := &roleReadStore{DirStore: release.NewDirStore(dir), root: dir} |
| + s.EnableChangeIndex() |
| + w := release.NewChangeWatch(s) |
| + if _, err := w.Poll(context.Background()); err != nil { |
| + t.Fatal(err) |
| + } |
| + role, known := boxroles.Booting, false |
| + r, err := newBoxRoleReader(roleEnv, w, s, "box", "ie", func(v boxroles.Role, ok bool) error { role, known = v, ok; return nil }) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return r, s, w, &role, &known |
| +} |
| +func TestRoleScopeBudget(t *testing.T) { |
| + r, s, w, role, known := roleReaderFixture(t) |
| + ctx := context.Background() |
| + now := time.Now() |
| + r.pass(ctx, now) |
| + if s.gets != 2 || *role != boxroles.Serve || !*known { |
| + t.Fatalf("first %d %s %v", s.gets, *role, *known) |
| + } |
| + r.pass(ctx, now.Add(time.Minute)) |
| + if s.gets != 2 { |
| + t.Fatal(s.gets) |
| + } |
| + if _, err := s.Put(ctx, "control/box-roles/box.json", []byte(`{"role":"drain"}`), ""); err != nil { |
| + t.Fatal(err) |
| + } |
| + w.Poll(ctx) |
| + r.pass(ctx, now.Add(2*time.Minute)) |
| + if s.gets != 4 || *role != boxroles.Drain { |
| + t.Fatalf("change %d %s", s.gets, *role) |
| + } |
| +} |
| +func TestRoleReadGateBackstop(t *testing.T) { |
| + r, s, w, role, _ := roleReaderFixture(t) |
| + ctx := context.Background() |
| + now := time.Now() |
| + r.pass(ctx, now) |
| + // Bypass the index writer to model a saved role whose index bump was lost. |
| + raw := release.NewDirStore(s.root) |
| + raw.Put(ctx, "control/box-roles/box.json", []byte(`{"role":"drain"}`), "") |
| + r.pass(ctx, now.Add(29*time.Minute)) |
| + if s.gets != 2 { |
| + t.Fatal(s.gets) |
| + } |
| + r.pass(ctx, now.Add(30*time.Minute)) |
| + if s.gets != 4 || *role != boxroles.Drain { |
| + t.Fatalf("backstop %d %s", s.gets, *role) |
| + } |
| + _, etag, _ := s.DirStore.Get(ctx, "control/box-roles/box.json") |
| + s.Put(ctx, "control/box-roles/box.json", []byte(`{"role":"serve"}`), etag) |
| + w.Poll(ctx) |
| + s.during = func() { |
| + s.Put(ctx, "control/box-roles/@region-ie.json", []byte(`{"role":"platform"}`), "") |
| + w.Poll(ctx) |
| + } |
| + r.pass(ctx, now.Add(31*time.Minute)) |
| + before := s.gets |
| + // Another reader already consumed moved; generation captured before GET is still due. |
| + w.Poll(ctx) |
| + r.pass(ctx, now.Add(31*time.Minute+time.Second)) |
| + if s.gets != before+2 { |
| + t.Fatalf("lost racing change %d -> %d", before, s.gets) |
| + } |
| +} |
| +func TestRoleUnreadableIsClosed(t *testing.T) { |
| + r, s, _, role, known := roleReaderFixture(t) |
| + ctx := context.Background() |
| + now := time.Now() |
| + s.fail = "control/box-roles/box.json" |
| + r.pass(ctx, now) |
| + if *role != boxroles.Booting || *known { |
| + t.Fatal(*role, *known) |
| + } |
| + s.fail = "" |
| + s.Put(ctx, "control/box-roles/box.json", []byte(`{"role":"platform"}`), "") |
| + r.pass(ctx, now.Add(5*time.Second)) |
| + if *role != boxroles.Platform || !*known { |
| + t.Fatal(*role, *known) |
| + } |
| + s.fail = "control/box-roles/@region-ie.json" |
| + r.pass(ctx, now.Add(31*time.Minute)) |
| + if *role != boxroles.Platform || *known { |
| + t.Fatal(*role, *known) |
| + } |
| +} |
| +func TestRoleBackoffBudget(t *testing.T) { |
| + r, s, w, _, known := roleReaderFixture(t) |
| + ctx := context.Background() |
| + now := time.Now() |
| + s.fail = "control/box-roles/@region-ie.json" |
| + var attempts []int |
| + for sec := 0; sec < 3600; sec++ { |
| + before := s.gets |
| + r.pass(ctx, now.Add(time.Duration(sec)*time.Second)) |
| + if s.gets != before { |
| + attempts = append(attempts, sec) |
| + } |
| + } |
| + if s.gets > 128 || len(attempts) < 5 { |
| + t.Fatalf("gets %d attempts %v", s.gets, attempts) |
| + } |
| + for i, want := range []int{0, 5, 15, 35, 75, 135} { |
| + if attempts[i] != want { |
| + t.Fatal(attempts[:6]) |
| + } |
| + } |
| + s.fail = "" |
| + w.Poll(ctx) |
| + r.pass(ctx, now.Add(2*time.Hour)) |
| + if !*known { |
| + t.Fatal("no recovery") |
| + } |
| +} |
| +func TestRoleDisarmed(t *testing.T) { |
| + for _, flag := range []string{"", "reed", "read"} { |
| + reads := 0 |
| + get := func(k string) string { |
| + if k == "CARLOS_GROUP_ADMISSION" { |
| + return "1" |
| + } |
| + if k == "CARLOS_CHANGE_INDEX" { |
| + return flag |
| + } |
| + return "" |
| + } |
| + if r, err := newBoxRoleReader(get, nil, nil, "box", "ie", func(boxroles.Role, bool) error { reads++; return nil }); err == nil || r != nil || reads != 0 { |
| + t.Fatal("disarmed reader", r, err, reads) |
| + } |
| + } |
| + if r, err := newBoxRoleReader(func(string) string { return "" }, nil, nil, "", "", nil); r != nil || err != nil { |
| + t.Fatal("non-P3", r, err) |
| + } |
| +} |
| + |
| +type rolePublication struct { |
| + role boxroles.Role |
| + admitted, drained bool |
| + acks int |
| +} |
| + |
| +func (p *rolePublication) EdgesRole() (boxroles.Role, bool, bool) { |
| + return p.role, p.admitted, p.drained |
| +} |
| +func (p *rolePublication) EdgesPublished() { p.acks++ } |
| + |
| +type roleWriteFail struct { |
| + release.Store |
| + fail bool |
| +} |
| + |
| +func (s *roleWriteFail) Put(ctx context.Context, k string, b []byte, e string) (string, error) { |
| + if s.fail { |
| + return "", errors.New("write failed") |
| + } |
| + return s.Store.Put(ctx, k, b, e) |
| +} |
| +func TestRolePublisherAck(t *testing.T) { |
| + ctx := context.Background() |
| + s := &roleWriteFail{Store: release.NewDirStore(t.TempDir()), fail: true} |
| + reg := edgesTestRegistry(t) |
| + seedRoute(t, reg, "shop.example.com") |
| + p := &rolePublication{role: boxroles.Serve} |
| + ident := edgesFile{Box: "box", RoleSource: p} |
| + var last []byte |
| + if err := edgesFilePass(ctx, s, reg, ident, "203.0.113.1", &last); err == nil || p.acks != 0 { |
| + t.Fatal(err, p.acks) |
| + } |
| + s.fail = false |
| + if err := edgesFilePass(ctx, s, reg, ident, "203.0.113.1", &last); err != nil || p.acks != 1 { |
| + t.Fatal(err, p.acks) |
| + } |
| + edgesFilePass(ctx, s, reg, ident, "203.0.113.1", &last) |
| + if p.acks != 1 { |
| + t.Fatal("unchanged acknowledged") |
| + } |
| + p.admitted = true |
| + edgesFilePass(ctx, s, reg, ident, "203.0.113.1", &last) |
| + if p.acks != 2 { |
| + t.Fatal("role change not published") |
| + } |
| + body, _, _ := s.Get(ctx, edgesFileKey("box")) |
| + var f map[string]json.RawMessage |
| + json.Unmarshal(body, &f) |
| + if string(f["box_role"]) != `"serve"` || string(f["admitted"]) != "true" || string(f["drained"]) != "false" { |
| + t.Fatal(string(body)) |
| + } |
| +} |
| +func TestRoleFieldsAreNotHostRoles(t *testing.T) { |
| + ctx := context.Background() |
| + s := release.NewDirStore(t.TempDir()) |
| + reg := edgesTestRegistry(t) |
| + seedRoute(t, reg, "shop.example.com") |
| + var last []byte |
| + edgesFilePass(ctx, s, reg, edgesFile{Box: "box"}, "203.0.113.1", &last) |
| + body, _, _ := s.Get(ctx, edgesFileKey("box")) |
| + for _, key := range []string{"box_role", "admitted", "drained", "namespace"} { |
| + if strings.Contains(string(body), `"`+key+`"`) { |
| + t.Fatal(string(body)) |
| + } |
| + } |
| + var f edgesFile |
| + json.Unmarshal(body, &f) |
| + if f.Hosts["shop.example.com"].Role != "home" { |
| + t.Fatal(f.Hosts) |
| + } |
| +} |
| + |
| +func TestRoleUnusableWatchAndApplicationBackoff(t *testing.T) { |
| + r, s, w, role, known := roleReaderFixture(t) |
| + ctx := context.Background() |
| + now := time.Now() |
| + r.pass(ctx, now) |
| + // A failed shared index observation does not become an every-pass reader, |
| + // even when both desired-role objects themselves remain readable. |
| + cancelled, cancel := context.WithCancel(ctx) |
| + cancel() |
| + w.Poll(cancelled) |
| + r.pass(ctx, now.Add(time.Second)) |
| + before := s.gets |
| + if *known || *role != boxroles.Serve { |
| + t.Fatal(*role, *known) |
| + } |
| + w.Poll(ctx) |
| + s.Put(ctx, "control/box-roles/box.json", []byte(`{"role":"drain"}`), "") |
| + w.Poll(ctx) |
| + r.pass(ctx, now.Add(2*time.Second)) |
| + if s.gets != before { |
| + t.Fatal("index bypassed backoff") |
| + } |
| + r.apply = func(boxroles.Role, bool) error { return errors.New("application failed") } |
| + r.pass(ctx, now.Add(6*time.Second)) |
| + if r.role != boxroles.Serve { |
| + t.Fatal("cached failed application") |
| + } |
| + r.apply = func(v boxroles.Role, ok bool) error { *role, *known = v, ok; return nil } |
| + r.pass(ctx, now.Add(16*time.Second)) |
| + if *role != boxroles.Drain || !*known { |
| + t.Fatal(*role, *known) |
| + } |
| +} |
| + |
| +func TestAdmissionWithdrawalWindow(t *testing.T) { |
| + ctx := context.Background() |
| + s := release.NewDirStore(t.TempDir()) |
| + reg := edgesTestRegistry(t) |
| + if err := reg.Upsert(registry.Route{Host: "shop.example.com", Kind: "service", Addr: "10.0.0.1:3000", Status: "ready", Platform: true}); err != nil { |
| + t.Fatal(err) |
| + } |
| + other := edgesTestRegistry(t) |
| + if err := other.Upsert(registry.Route{Host: "other.example.com", App: "other", Account: "acct", Kind: "instance", Status: "ready"}); err != nil { |
| + t.Fatal(err) |
| + } |
| + claim := domains.Claim{Schema: 1, Host: "shop.example.com", Account: "acct", App: "other", Route: "other.example.com"} |
| + b, _ := json.Marshal(claim) |
| + if _, err := s.Put(ctx, domains.ClaimKey(claim.Host), b, ""); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := status.WriteBox(ctx, s, status.Box{Label: "box", GeneratedAt: time.Now()}); err != nil { |
| + t.Fatal(err) |
| + } |
| + pub := &rolePublication{role: boxroles.Serve, admitted: true} |
| + ident := edgesFile{Box: "box", RoleSource: pub} |
| + var last []byte |
| + for _, admitted := range []bool{true, false, true} { |
| + pub.admitted = admitted |
| + if err := edgesFilePass(ctx, s, reg, ident, "203.0.113.1", &last); err != nil { |
| + t.Fatal(err) |
| + } |
| + body, _, err := s.Get(ctx, edgesFileKey("box")) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + var f edgesFile |
| + if err = json.Unmarshal(body, &f); err != nil { |
| + t.Fatal(err) |
| + } |
| + if !admitted && (len(f.Hosts) != 0 || !f.Namespace["shop.example.com"].Platform || f.BoxRole != boxroles.Booting || *f.Admitted || *f.Drained) { |
| + t.Fatalf("boot publication %s", body) |
| + } |
| + routes, complete := edgesfile.DeploymentRoutesComplete(ctx, s, time.Now()) |
| + if !complete || !routes["shop.example.com"] { |
| + t.Fatal("namespace withdrawn", routes, complete) |
| + } |
| + if err := domains.ReconcileAliases(ctx, s, other, time.Now, routes, nil); err != nil { |
| + t.Fatal(err) |
| + } |
| + aliases, err := other.ListAliases() |
| + if err != nil || len(aliases) != 0 { |
| + t.Fatal("alias takeover", aliases, err) |
| + } |
| + _, ok, err := edge.FoldedHome(map[string][]byte{edgesFileKey("box"): body}, "observer", "shop.example.com") |
| + if err != nil || ok != admitted { |
| + t.Fatal("home election", ok, admitted, err) |
| + } |
| + snap, err := edgesfile.ReadSnapshot(ctx, s) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + won, _, err := edgesfile.ElectHomesForEveryReader(snap.Files) |
| + if err != nil || (won["shop.example.com"].Box != "") != admitted { |
| + t.Fatal("console election", won, err) |
| + } |
| + } |
| +} |
| + |
| +func TestRoleExistingTick(t *testing.T) { |
| + r, s, w, role, _ := roleReaderFixture(t) |
| + old := armedBoxRoleReader.Swap(r) |
| + t.Cleanup(func() { armedBoxRoleReader.Store(old) }) |
| + f := newFastFixture(t) |
| + d := f.deps(nil) |
| + d.store = s |
| + d.watch = w |
| + now := time.Now() |
| + fastTick(context.Background(), d, now) |
| + if s.gets != 2 || *role != boxroles.Serve { |
| + t.Fatal(s.gets, *role) |
| + } |
| + fastTick(context.Background(), d, now.Add(2*time.Second)) |
| + if s.gets != 2 { |
| + t.Fatal("quiet tick polled roles", s.gets) |
| + } |
| +} |
| +func TestRolePublisherFreshProcess(t *testing.T) { |
| + ctx := context.Background() |
| + s := release.NewDirStore(t.TempDir()) |
| + reg := edgesTestRegistry(t) |
| + pub := &rolePublication{role: boxroles.Booting} |
| + ident := edgesFile{Box: "box", RoleSource: pub} |
| + var last []byte |
| + if err := edgesFilePass(ctx, s, reg, ident, "203.0.113.1", &last); err != nil { |
| + t.Fatal(err) |
| + } |
| + pub.acks = 0 |
| + ident.RolePublishRequired = true |
| + // The previous process's identical booting body is not this one's ack. |
| + if err := edgesFilePass(ctx, s, reg, ident, "203.0.113.1", &last); err != nil || pub.acks != 1 { |
| + t.Fatal(err, pub.acks) |
| + } |
| +} |
| + |
| +func TestRoleWatchRecoversWithoutGenerationChange(t *testing.T) { |
| + r, s, w, _, known := roleReaderFixture(t) |
| + ctx := context.Background() |
| + now := time.Now() |
| + r.pass(ctx, now) |
| + c, cancel := context.WithCancel(ctx) |
| + cancel() |
| + w.Poll(c) |
| + r.pass(ctx, now.Add(time.Second)) |
| + if *known { |
| + t.Fatal("unusable observation left starts open") |
| + } |
| + w.Poll(ctx) |
| + r.pass(ctx, now.Add(6*time.Second)) |
| + if !*known || s.gets != 6 { |
| + t.Fatalf("same-generation recovery stayed closed: known=%v GETs=%d", *known, s.gets) |
| + } |
| +} |
| + |
| +func TestRolePublicationSchedule(t *testing.T) { |
| + now := time.Now() |
| + p := &rolePublication{role: boxroles.Booting} |
| + ident := edgesFile{RoleSource: p, RolePublishRequired: true} |
| + state := &edgesLoopState{sched: newEdgesFileSchedule(now, func() time.Duration { return 5 * time.Minute })} |
| + if !state.dueWithRole(now, "registry", true, false, ident) { |
| + t.Fatal("startup publication waited for minute timer") |
| + } |
| + state.done(now, false) |
| + if state.dueWithRole(now.Add(time.Second), "registry", true, false, ident) { |
| + t.Fatal("startup bypassed retry backoff") |
| + } |
| + if !state.dueWithRole(now.Add(2*time.Second), "registry", true, false, ident) { |
| + t.Fatal("startup not retried") |
| + } |
| + state.done(now.Add(2*time.Second), true) |
| + ident.RolePublishRequired = false |
| + if state.dueWithRole(now.Add(3*time.Second), "registry", true, false, ident) { |
| + t.Fatal("unchanged state republished") |
| + } |
| + p.role, p.admitted = boxroles.Serve, true |
| + if !state.dueWithRole(now.Add(4*time.Second), "registry", true, false, ident) { |
| + t.Fatal("admission did not publish") |
| + } |
| + state.done(now.Add(4*time.Second), true) |
| + if state.dueWithRole(now.Add(5*time.Second), "registry", true, false, ident) { |
| + t.Fatal("admission published twice") |
| + } |
| + legacy := &edgesLoopState{sched: newEdgesFileSchedule(now, func() time.Duration { return 5 * time.Minute })} |
| + if legacy.dueWithRole(now, "registry", true, false, edgesFile{}) { |
| + t.Fatal("changed legacy first-write cadence") |
| + } |
| +} |
| + |
| +func TestRoleWithdrawalKeepsPriorNamespaceClass(t *testing.T) { |
| + ctx := context.Background() |
| + s := release.NewDirStore(t.TempDir()) |
| + reg := edgesTestRegistry(t) |
| + route := registry.Route{Host: "shop.example.com", Kind: "service", Addr: "10.0.0.1:3000", Status: "ready", Platform: true} |
| + if err := reg.Upsert(route); err != nil { |
| + t.Fatal(err) |
| + } |
| + pub := &rolePublication{role: boxroles.Serve, admitted: true} |
| + ident := edgesFile{Box: "box", RoleSource: pub} |
| + var last []byte |
| + if err := edgesFilePass(ctx, s, reg, ident, "203.0.113.1", &last); err != nil { |
| + t.Fatal(err) |
| + } |
| + // A partially reconstructed row cannot remove the old wildcard parent |
| + // while startup is still closed. |
| + route.Platform = false |
| + if err := reg.Upsert(route); err != nil { |
| + t.Fatal(err) |
| + } |
| + pub.admitted = false |
| + if err := edgesFilePass(ctx, s, reg, ident, "203.0.113.1", &last); err != nil { |
| + t.Fatal(err) |
| + } |
| + body, _, _ := s.Get(ctx, edgesFileKey("box")) |
| + var f edgesFile |
| + if err := json.Unmarshal(body, &f); err != nil { |
| + t.Fatal(err) |
| + } |
| + if !f.Namespace[route.Host].Platform { |
| + t.Fatal("booting row erased prior parent class") |
| + } |
| +} |
diff --git a/internal/host/edgesfile.go b/internal/host/edgesfile.go| index 393a659a2..4cf7f2b12 100644 |
| --- a/internal/host/edgesfile.go |
| +++ b/internal/host/edgesfile.go |
| @@ -16,7 +16,9 @@ import ( |
| "time" |
| "github.com/carlosframework/platform/internal/appconfig" |
| + "github.com/carlosframework/platform/internal/boxroles" |
| "github.com/carlosframework/platform/internal/edge" |
| + "github.com/carlosframework/platform/internal/edgesfile" |
| "github.com/carlosframework/platform/internal/instancectl" |
| "github.com/carlosframework/platform/internal/registry" |
| "github.com/carlosframework/platform/internal/release" |
| @@ -256,10 +258,16 @@ func awakeCount(reg *registry.Registry) int { |
| // batch-wide if it ever reached here (plan review catch, 2026-08-23). |
| // edgesFileRegion resolves the real thing. |
| type edgesFile struct { |
| - V int `json:"v"` |
| - Box string `json:"box"` |
| - EIP string `json:"eip"` |
| - Region string `json:"region,omitempty"` |
| + RoleSource edgesRoleSource `json:"-"` |
| + RolePublishRequired bool `json:"-"` |
| + BoxRole boxroles.Role `json:"box_role,omitempty"` |
| + Admitted *bool `json:"admitted,omitempty"` |
| + Drained *bool `json:"drained,omitempty"` |
| + Namespace map[string]edgesfile.NamespaceHost `json:"namespace,omitempty"` |
| + V int `json:"v"` |
| + Box string `json:"box"` |
| + EIP string `json:"eip"` |
| + Region string `json:"region,omitempty"` |
| // PrivateIP is the address an edge in this box's region dials (region |
| // HA spec 2 §6), and PrivateCIDR the region network that holds it, |
| // both validated by edgesfile.PrivateAddress before they are written. |
| @@ -946,6 +954,7 @@ func edgesFileWriteClaims(ctx context.Context, s release.Store, reg *registry.Re |
| f := ident |
| f.V, f.EIP, f.Hosts, f.Generation = 1, eip, hosts, "" |
| + f = withBoxRole(f, *last) |
| f.BurstNotices = true |
| f.PrivateIP, f.PrivateCIDR = private.Private, private.PrivateCIDR |
| // Before the gate copy, so an address change is a reason to write. |
| @@ -968,7 +977,7 @@ func edgesFileWriteClaims(ctx context.Context, s release.Store, reg *registry.Re |
| return fmt.Errorf("edges: marshal: %w", err) |
| } |
| } |
| - if bytes.Equal(cmp, *last) && !(refresh && f.Headroom != nil) { |
| + if bytes.Equal(cmp, *last) && !(refresh && f.Headroom != nil) && !f.RolePublishRequired { |
| if assets != nil { |
| assets.passDone(clocks, settled, false, nil) |
| } |
| @@ -984,6 +993,9 @@ func edgesFileWriteClaims(ctx context.Context, s release.Store, reg *registry.Re |
| return err |
| } |
| *last = gate |
| + if f.RoleSource != nil { |
| + f.RoleSource.EdgesPublished() |
| + } |
| if assets != nil { |
| assets.passDone(clocks, settled, true, f.Hosts) |
| } |
| @@ -1164,8 +1176,12 @@ func edgesFileLoop(reg *registry.Registry, lifetimes bool, assets *assetPolicy) |
| BoxID: box, |
| Capabilities: edgesFileCapabilities(os.Getenv), |
| } |
| - // The box's memory does not change under a running agent, so the |
| - // total is read once here; the disk half is not wanted. |
| + // Admission supplies one snapshot source to the existing publisher. |
| + if p := armedBoxRolePublisher.Load(); p != nil { |
| + ident.RoleSource = p.Source |
| + ident.RolePublishRequired = p.Source != nil |
| + } |
| + // The total is read once at arm; the disk half is not needed. |
| ident.BoxMemTotalMiB, _ = capacityMiB(readMemBytes, func() (uint64, uint64, error) { return 0, 0, errors.ErrUnsupported }) |
| // The flag-derived capabilities; offline-move-1 joins them on each pass |
| // once the moves worker is armed and capable, and db-read-1 joins them |
| @@ -1226,9 +1242,9 @@ func edgesFileLoop(reg *registry.Registry, lifetimes bool, assets *assetPolicy) |
| pub := assets.active() |
| key := fp |
| if pub != nil && err == nil { |
| - key = edgesChangeKey(fp, pub.servingDigest()) |
| + key = edgesChangeKey(key, pub.servingDigest()) |
| } |
| - if !state.dueWith(now, key, err == nil, pub.rewriteDue()) { |
| + if !state.dueWithRole(now, key, err == nil, pub.rewriteDue(), ident) { |
| continue |
| } |
| if state.timed() { |
| @@ -1251,6 +1267,9 @@ func edgesFileLoop(reg *registry.Registry, lifetimes bool, assets *assetPolicy) |
| } else { |
| passErrs = 0 |
| } |
| + if err == nil { |
| + ident.RolePublishRequired = false |
| + } |
| state.done(now, err == nil) |
| } |
| } |
diff --git a/internal/hostenv/boxroles_test.go b/internal/hostenv/boxroles_test.go| new file mode 100644 |
| index 000000000..81ca3d1f3 |
| --- /dev/null |
| +++ b/internal/hostenv/boxroles_test.go |
| @@ -0,0 +1,9 @@ |
| +package hostenv |
| + |
| +import "testing" |
| + |
| +func TestRoleChangeIndexAllowed(t *testing.T) { |
| + if !Allowed("CARLOS_CHANGE_INDEX") { |
| + t.Fatal("change index cannot be delivered") |
| + } |
| +} |
diff --git a/internal/hostenv/hostenv.go b/internal/hostenv/hostenv.go| index 5e12092b9..6829208cc 100644 |
| --- a/internal/hostenv/hostenv.go |
| +++ b/internal/hostenv/hostenv.go |
| @@ -78,6 +78,7 @@ var Optional = []string{ |
| "CARLOS_ALERT_MEM_PCT", |
| "CARLOS_AWS_REGION", |
| "CARLOS_BACKHAUL_MAX_INFLIGHT", |
| + "CARLOS_CHANGE_INDEX", |
| "CARLOS_DEPLOYMENT_SINGLE_TENANT", |
| "CARLOS_DNS_PROVIDER", |
| "CARLOS_EDGE_GZIP", |
diff --git a/internal/provision/testdata/plan14-root-reads-chain.tsv b/internal/provision/testdata/plan14-root-reads-chain.tsv| index b05325a0a..415ef587f 100644 |
| --- a/internal/provision/testdata/plan14-root-reads-chain.tsv |
| +++ b/internal/provision/testdata/plan14-root-reads-chain.tsv |
| @@ -75,4 +75,4 @@ plan14-root-reads-domains-check-country.tsv b0fc198c53bb0dacba33a54c3d8bf8fe5ac0 |
| plan14-root-reads-static-stream-extract.tsv 7fb932b118e67e23b33a374c6a4020b38976667c7ec4cfb855c0f8b598b1756b |
| plan14-root-reads-ls284.tsv 744b16d970f22476b79982e57c326157ca5137fa96ccaee4a7ae10c25248d124 |
| plan14-root-reads-region-ha-p1b3b-t.tsv c68e2453bfc8afaf3794eb4c08850428982fa6954269b6b99bddfda4e6242929 |
| -plan14-root-reads-region-ha-p3a.tsv f2d9c89885a0019f5a30651f8019bb6f0c55bf84b412e045e59e30b66b4bf32e |
| +plan14-root-reads-region-ha-p3a.tsv a27d94a93013e3e0c9f69bacad970ece395fb39d9b0f3c7cac0c47ab55542dbf |
diff --git a/internal/provision/testdata/plan14-root-reads-region-ha-p3a.tsv b/internal/provision/testdata/plan14-root-reads-region-ha-p3a.tsv| index 7e019ff1b..2b6f33f5a 100644 |
| --- a/internal/provision/testdata/plan14-root-reads-region-ha-p3a.tsv |
| +++ b/internal/provision/testdata/plan14-root-reads-region-ha-p3a.tsv |
| @@ -1,6 +1,7 @@ |
| # Census overlay region-ha-p3a, written by census-propose (#369). census-ruling-region-ha-p3a, approved on #280 before the merge; the approval card is docs/superpowers/notes/census-proposal-region-ha-p3a.md. |
| -# 0 body, 0 sites, 5 envelope: each changed unit re-frozen at its existing disposition with its claim appended. |
| -# 10 new dispositions: 0 reads re-frozen at their disposition with the claim, 10 new units frozen accepted-legacy, 0 quiet units retired while they read nothing, 0 other. |
| +# 2 body, 0 sites, 11 envelope: each changed unit re-frozen at its existing disposition with its claim appended. |
| +# 13 new dispositions: 0 reads re-frozen at their disposition with the claim, 13 new units frozen accepted-legacy, 0 quiet units retired while they read nothing, 0 other. |
| +@legacy 835af32ac1034a8c2cf1fb9241753c715eeac79cf63b917d7235d70577cd247e internal/host/agent.go fastTick legacy accepted-legacy accepted-legacy;rev3=J1;basis=root-route;rev3=PROPOSED-s3-change-index;identity=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos);basis=observes the change index before any pass (observeIndex), runs the backstop's requested full pass and a scoped pass for moved app scopes (indexTick), and arms the canary pointer gate on the sweep (canaryPointerGate) only on a tick whose own index observation succeeded; read site unchanged, offset moved;rev3=census-ruling-stateless-replicas-1;basis=Call coordinator Tick on the existing tick before convergence; client renews held terms only at the pinned interval. Existing registry read unchanged. Final review I3: signal the owned renewal worker instead of waiting for its sequential console HTTP calls. Existing convergence and record read unchanged.;rev3=census-ruling-region-ha-p3a;basis=Run the optional desired-role reader on the existing tick after observing the armed change index; no new root path or timer, nil reader is unchanged. registry:Host@4821 487aa39fc1d1a2bb188ab5b71f0ee4bc0b417c53914f74c2b55867001a2ce528 |
| @legacy 377eb01304b9a5473fcef2354ef85dd2ba95785c48ff2ba1a0782778499989ef infra/modules/region-host/ingress/main.tf external legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p3a;basis=Add isolated IPv4 NLB, VPC/zone lookups, validated CIDR egress, protected new EIPs and TCP health-checked target groups; no fixed-resource edits or root runtime reads. file:external@0 103369ef62af3311ee0e01e751e23a03ca3634015841f0a9437ee7e682353d37 |
| @legacy c1636b10d14fd359d718264048fe782d0405dde3102b72a1a8eac270c37b14f6 infra/modules/region-host/ingress/outputs.tf external legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p3a;basis=Expose per-zone addresses and NLB/TG identities for root attachments and Task 4 alarms; no root runtime reads. file:external@0 83d036fd1e80e375df647bfbb84eb9307faa97ad5511672c938a164919f246a9 |
| @legacy 7a49227972307af74b52e450dc5ea86547395d41192f24792c71ca21db3b474d infra/modules/region-host/ingress/tests/fixed-targets/main.tf external legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p3a;basis=Add dev-root fixture attaching literal instance IDs to both target groups with read-only AZ lookups and target-zone precondition; no fixed-module references or root runtime reads. file:external@0 98e19cac1a98259ba7f3c1e9ab95471e25afa2ae77c54bd4c575a2e094fac62e |
| @@ -11,6 +12,11 @@ |
| @legacy 0c7e79156fc210a3460e9cbce1a7e26edbf22f0c799710f3e82e1a09a483d994 infra/modules/region-host/ingress/variables.tf external legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p3a;basis=Add ingress-only inputs and topology/CIDR validation; no root runtime reads. file:external@0 a1599da50d212d5e64f527719ee781e5a0a494185d144f0a958433741f4c9d36 |
| @legacy 134888d1b095e8268cdd1cd04df27087407ae3fee1c4742f0df5a431520783ef infra/modules/region-host/ingress/versions.tf external legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p3a;basis=Declare OpenTofu and AWS provider requirements for the isolated ingress child; no root runtime reads. file:external@0 bb3be812da255c0f031b2bfdfee462e4687de3681c742b529b55693a8875136b |
| @legacy 73e967bb630a74f28c53f50b63c997d086154b025cf7b59074d5b0fe2fc3bea7 infra/modules/region-host/tests/fixed_state_unchanged.tftest.hcl external legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p3a;basis=Add mock regression for the unchanged fixed instance/profile/SG/root-volume wiring and legacy outputs; no root runtime reads. file:external@0 cab0fdd9e01c4497f06a617db6c41aa9887da80bd0518c76fe8eba935be42c85 |
| +@legacy 6c02de7e1e2960b253dafcce566bdcd6ae60cf8751c98b7036ce6dcabc43b1fc internal/boxroles/roles.go Read legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p3a;basis=Two point GETs of validated own and canonical-region desired-role keys; strict bounded parsing, errors never default to serve; no filesystem read or root authority grant. file:Read@5 7a81085231b83e3c7f524640fe5c5d347ac941af24a7ee9f3bd15a3d349aec03 |
| +@legacy 7a9921c9cb3d1fa2aa7fa0bc817c36c9ec379b6e30d03e3f395de4f3ff053a91 internal/host/boxroles.go boxRoleReader.pass legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p3a;basis=Apply desired roles through the startup-injected callback with one existing ReadGate and bounded retry backoff; preserve restrictions and close new starts on unknown evidence; no filesystem read. file:Read@268 832d15595492589b64928bad0831273d08ecd355a0f4cd939774acaa2d0bf821 |
| +@legacy 02d429c92fa49c5ad18109eb1fc99874d6fe43094c02b809029f7da90d2e22d6 internal/host/boxroles_config_linux.go readRoleRegionConfig legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p3a;basis=Read the fixed operator-delivered /etc/carlos/region-config.json through no-symlink openat2, fstat root ownership/regular-file/non-writable checks, single-link check and 4097-byte limited read; validate explicit canonical code and unchanged raw placement, never infer from AWS. file:Fstat@414,file:Openat2@90,file:ReadAll@733 2ab0091c9dad48273774eb0feb4b9289b823b9ed7a76852e6c6d26b34cb6e231 |
| +internal/host/agent.go fastTick legacy accepted-legacy accepted-legacy;rev3=J1;basis=root-route;rev3=PROPOSED-s3-change-index;identity=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos);basis=observes the change index before any pass (observeIndex), runs the backstop's requested full pass and a scoped pass for moved app scopes (indexTick), and arms the canary pointer gate on the sweep (canaryPointerGate) only on a tick whose own index observation succeeded; read site unchanged, offset moved;rev3=census-ruling-stateless-replicas-1;basis=Call coordinator Tick on the existing tick before convergence; client renews held terms only at the pinned interval. Existing registry read unchanged. Final review I3: signal the owned renewal worker instead of waiting for its sequential console HTTP calls. Existing convergence and record read unchanged.;rev3=census-ruling-region-ha-p3a;basis=Run the optional desired-role reader on the existing tick after observing the armed change index; no new root path or timer, nil reader is unchanged. registry:Host@4821 487aa39fc1d1a2bb188ab5b71f0ee4bc0b417c53914f74c2b55867001a2ce528 |
| +internal/host/edgesfile.go edgesFileWriteClaims authority F,J1 rev3=census-ruling-self-serve-moves-1;basis=root-route;kept=F;scope=protected-decision-only; the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): region-ha-2a's body, which with the box's lifetimes switch on also publishes each served row's lifetime pair (registry:Incarnation and registry:ServingSeq, two new sites on the rows it already lists) and an alias's or served catch-all's primary's pair, and names that primary as target_host whatever the switch; a report the edge orders unstamped entries by, not a decision; no record, /data, release or claim read added; F,J1 authority retained; self-serve moves 1 Task 8;rev3=census-ruling-instance-egress-sizes-328-329;basis=#328 plan 2 Task 8: takes a localAddrs reader (instancectl.LocalAddresses in production, which reads /proc/net/fib_trie and /proc/net/if_inet6 in the agent) and publishes its non-loopback entries as the edges file's addrs before the write gate (boxAddrs, no read of its own), so an address change writes once. The same 44 sites, offsets moved; no record, /data, release or claim read added; a report the console's egress grant check reads, not a root decision; F,J1 authority retained.;rev3=census-ruling-edge-asset-cache-3;basis=starts with assets = assets.active(), so a policy whose box has not opened its asset store publishes no assets blocks and reads no manifests, and copies the decision's Primary (the route host the block was decided for, drift D4) into the published assets block; read sites unchanged (44); no read added. Merged onto main's #328 body, which takes the localAddrs reader: the assets.active() line sits after that signature and the loop passes pub and instancectl.LocalAddresses;rev3=census-ruling-region-ha-p1a;basis=the agent as carlos: the claims argument (*edgesClaims) becomes addrs (AddressSource) and the applyEdgesClaims(ctx, claims, routes, hosts) call is deleted with edgesclaims.go, which is the one whole:Route site removed: no host claim is read and every served row publishes as with region HA off; the box-address publication is the same code reading addrs.BoxAddresses() instead of claims.addrs; a report the edge reads, not a root decision; no read added; merge of origin/main d7ae1d76: main's edge asset cache plan 3 body is kept (census-ruling-edge-asset-cache-3): the first line is assets = assets.active(), so a policy whose store has not opened publishes no assets blocks and reads no manifests, and edgesFileLoop passes pub (assets.active() for that tick) in the assets argument; main's claims *edgesClaims argument is this branch's addrs AddressSource, and no edgesClaims, applyEdgesClaims or hostclaim reference remains;rev3=census-ruling-alias-wake-338;basis=#338 follow-up: skips publishing a platform alias edge.PlatformAliasFold refuses (and so anything attached to it); reads the same route listing;rev3=census-ruling-fleet-public-routes;basis=fleet public routes (spec 2026-10-29 rev 4, §4.2 writer rule): Task 6 and its fix rounds: publishes by FleetArmVerdict (via fleetRefusedFor): withheld rows left out; a forward host's path rows left out of its owner; no assets for forward rows; the alias loop replays Reload's alias fold from the served rows so a chained alias carries its root primary's owner; certRefused and parentRefused leave out a refused claim's wildcard parent (+registry:Alias x5, +registry:Host x4, +whole:Route, +whole:RouteAlias x2, +whole:RoutePath x7, +whole:WildcardDomain). Rows already read in the pass; keeps authority F,J1; publishes less, never more.;rev3=census-ruling-probe-burst-limit;basis=sets the constant BurstNotices=true on the box's own edges file (this build's edge answers probe-burst notices, so peers may send them); not from config or any read; the same 65 sites; a report other edges read, not a root decision; F,J1 authority retained; no new root read or write kind;rev3=census-ruling-region-ha-p3a;basis=Publish injected effective role and admission facts, withdraw booting home/alias rows into non-serving namespace reservations, and acknowledge only successful writes; existing registry reads unchanged. registry:Account@15753,registry:Alias@10256,registry:Alias@13226,registry:Alias@13276,registry:Alias@8683,registry:Alias@8702,registry:Alias@8801,registry:Alias@8855,registry:Alias@8890,registry:Alias@8952,registry:Alias@9322,registry:Alias@9479,registry:Alias@9549,registry:Alias@9581,registry:App@15765,registry:DNSStatus@8997,registry:DNSStatus@9488,registry:Host@13129,registry:Host@13149,registry:Host@13414,registry:Host@13494,registry:Host@13529,registry:Host@13578,registry:Host@14040,registry:Host@14075,registry:Host@15183,registry:Host@3889,registry:Host@3935,registry:Host@3994,registry:Host@5109,registry:Host@6079,registry:Host@8728,registry:Host@8776,registry:Incarnation@5069,registry:Platform@4848,registry:Provisioned@4862,registry:Replica@4886,registry:ServingSeq@5084,registry:Status@2677,whole:Route@1026,whole:Route@17223,whole:Route@18041,whole:Route@18216,whole:Route@1841,whole:Route@2047,whole:Route@6164,whole:Route@750,whole:RouteAlias@13180,whole:RouteAlias@17245,whole:RouteAlias@18231,whole:RouteAlias@8566,whole:RouteAlias@8648,whole:RouteAlias@8840,whole:RoutePath@17238,whole:RoutePath@18224,whole:RoutePath@5948,whole:RoutePath@5980,whole:RoutePath@6027,whole:RoutePath@6055,whole:RoutePath@6093,whole:RoutePath@6113,whole:RoutePath@6125,whole:RoutePath@6179,whole:WildcardDomain@13107,whole:WildcardDomain@13483 7e02cc72e5c7d15cbf8a63a333b265a584e8b1775742de0cb148272eea4c25ae |
| infra/modules/region-host/ingress/main.tf external legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p3a;basis=Add isolated IPv4 NLB, VPC/zone lookups, validated CIDR egress, protected new EIPs and TCP health-checked target groups; no fixed-resource edits or root runtime reads. file:external@0 103369ef62af3311ee0e01e751e23a03ca3634015841f0a9437ee7e682353d37 |
| infra/modules/region-host/ingress/outputs.tf external legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p3a;basis=Expose per-zone addresses and NLB/TG identities for root attachments and Task 4 alarms; no root runtime reads. file:external@0 83d036fd1e80e375df647bfbb84eb9307faa97ad5511672c938a164919f246a9 |
| infra/modules/region-host/ingress/tests/fixed-targets/main.tf external legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p3a;basis=Add dev-root fixture attaching literal instance IDs to both target groups with read-only AZ lookups and target-zone precondition; no fixed-module references or root runtime reads. file:external@0 98e19cac1a98259ba7f3c1e9ab95471e25afa2ae77c54bd4c575a2e094fac62e |
| @@ -21,8 +27,17 @@ infra/modules/region-host/ingress/tests/group_ingress.tftest.hcl external legacy |
| infra/modules/region-host/ingress/variables.tf external legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p3a;basis=Add ingress-only inputs and topology/CIDR validation; no root runtime reads. file:external@0 a1599da50d212d5e64f527719ee781e5a0a494185d144f0a958433741f4c9d36 |
| infra/modules/region-host/ingress/versions.tf external legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p3a;basis=Declare OpenTofu and AWS provider requirements for the isolated ingress child; no root runtime reads. file:external@0 bb3be812da255c0f031b2bfdfee462e4687de3681c742b529b55693a8875136b |
| infra/modules/region-host/tests/fixed_state_unchanged.tftest.hcl external legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p3a;basis=Add mock regression for the unchanged fixed instance/profile/SG/root-volume wiring and legacy outputs; no root runtime reads. file:external@0 cab0fdd9e01c4497f06a617db6c41aa9887da80bd0518c76fe8eba935be42c85 |
| +internal/boxroles/roles.go Read legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p3a;basis=Two point GETs of validated own and canonical-region desired-role keys; strict bounded parsing, errors never default to serve; no filesystem read or root authority grant. file:Read@5 7a81085231b83e3c7f524640fe5c5d347ac941af24a7ee9f3bd15a3d349aec03 |
| +internal/host/boxroles.go boxRoleReader.pass legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p3a;basis=Apply desired roles through the startup-injected callback with one existing ReadGate and bounded retry backoff; preserve restrictions and close new starts on unknown evidence; no filesystem read. file:Read@268 832d15595492589b64928bad0831273d08ecd355a0f4cd939774acaa2d0bf821 |
| +internal/host/boxroles_config_linux.go readRoleRegionConfig legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p3a;basis=Read the fixed operator-delivered /etc/carlos/region-config.json through no-symlink openat2, fstat root ownership/regular-file/non-writable checks, single-link check and 4097-byte limited read; validate explicit canonical code and unchanged raw placement, never infer from AWS. file:Fstat@414,file:Openat2@90,file:ReadAll@733 2ab0091c9dad48273774eb0feb4b9289b823b9ed7a76852e6c6d26b34cb6e231 |
| @coverage infra/modules/region-host/ingress 009777ca5464e8e6e0bfda45c00229b8924e0dc55f39d7d3036bca2b2d4f871e |
| @coverage infra/modules/region-host/ingress/tests 2d7e20b48fd461253375a250c0fd01a19160a42873136e33777b588770a0b3d5 |
| @coverage infra/modules/region-host/ingress/tests/fixed-targets f99d9d22e9ad6820b3fcc4e5210dad538a62274005c6fdd7c4a3af292aef91cc |
| @coverage infra/modules/region-host/ingress/tests/fixed-targets/tests 567e4b97ac15cea31cb88aba77dccf739e58382158dba13d6b03e22935995b52 |
| @coverage infra/modules/region-host/tests 18abb8044924e7422d67f4266905e6da7d024426cd7846868fca55932adbb9ae |
| +@coverage internal/boxroles 399e67f4d8a3ec2053b90db89b62ff567a969141890ee3a6285a52dd52502fb8 |
| +@coverage internal/edge 13d248c3e2ee86191250fe902ae22eac348cb71c3c1d4e16157155c5823c4517 |
| +@coverage internal/edgesfile d52ae7f7d22875c95dac7c3ad6f65cf3d427ea6f554919d61bf7fedaab655285 |
| +@coverage internal/host 93ec0640137e3fc920d00bc4c2882ac281bca51b011b100e95c1291d7e643b99 |
| +@coverage internal/hostenv 3e9785f0d91b89f13982f43b643a09671d6b6dc3ac176855ad3b597ac8daf8ae |
| +@coverage internal/release 95051eb07c6f91bdda535e8b8b45154a97c0f6869e92c32572e7f84c32677af4 |
diff --git a/internal/release/boxroles_test.go b/internal/release/boxroles_test.go| new file mode 100644 |
| index 000000000..f9821185a |
| --- /dev/null |
| +++ b/internal/release/boxroles_test.go |
| @@ -0,0 +1,11 @@ |
| +package release |
| + |
| +import "testing" |
| + |
| +func TestRoleScopeBudget(t *testing.T) { |
| + for _, k := range []string{"control/box-roles/box.json", "control/box-roles/@region-ie.json"} { |
| + if scope, ok := ChangeScope(k); !ok || scope != "control/box-roles" { |
| + t.Fatalf("scope %q %v", scope, ok) |
| + } |
| + } |
| +} |
diff --git a/internal/release/changeindex.go b/internal/release/changeindex.go| index 3088ee007..0633687d5 100644 |
| --- a/internal/release/changeindex.go |
| +++ b/internal/release/changeindex.go |
| @@ -69,7 +69,7 @@ func ChangeScope(key string) (scope string, ok bool) { |
| if len(parts) < 3 || parts[2] == "" { |
| return "", false |
| } |
| - if parts[1] == "certs" || parts[1] == "edges" { |
| + if parts[1] == "certs" || parts[1] == "edges" || parts[1] == "box-roles" { |
| return "control/" + parts[1], true |
| } |
| // control/app-policy/<a>/<b>.json is that app's operator policy |