carlos / platform Public

region HA G3-B10: born HA only in a named HA pool, outside home too

In a region whose CONSOLE_HA_CAPACITY_CONFIG entry carries ha_pools,
only creates in those pools are born HA; plain creates stay legacy. The
leftover proof runs against the config-named data bucket, home or not.
Invariant I-B10: unreadable edges files, or files placed in the region
reporting other storage, block scoped HA creates (503). Unscoped regions
(dev IE) and the move/import refusals (N-HA4) are unchanged. Spec
region-ha-without-claims §23; plan 2026-11-05-region-ha-g3-b10. Astra
plan review 3 rounds; Opus create-path and branch reviews; census #280.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Squashed from region-ha-g3-b10 into main.
Co-Authored-By: claude <claude@amadan.net>
claude agent, operated by paul@keymail.dev 1cc99071afd0ea84e25f57cc6ccc73dd5e11e2cf parent bfbdbec
19 files changed, +1,172 −29
  • cmd/console/ha_data_stores_test.go +67 −0
  • cmd/console/main.go +18 −0
  • docs/site/cli.md +3 −1
  • docs/superpowers/plans/2026-11-05-region-ha-g3-b10.md +83 −0
  • docs/superpowers/specs/2026-10-26-region-ha-without-claims-design.md +26 −1
  • internal/console/apiinstances.go +6 −5
  • internal/console/apisidecars.go +3 −2
  • internal/console/createleftovers.go +31 −2
  • internal/console/domainattach.go +1 −1
  • internal/console/ha_pool_scope_test.go +758 −0
  • internal/console/hacapacity.go +94 −4
  • internal/console/hacreate.go +2 −2
  • internal/console/hacreate_test.go +2 −2
  • internal/console/hap2_wiring_test.go +1 −1
  • internal/console/nocapacity.go +19 −6
  • internal/console/seedmove.go +12 −1
  • internal/console/server.go +14 −0
  • internal/provision/plan9_b8_census_test.go +1 −1
  • internal/provision/region_ha_g3_b10_census_test.go +31 −0

CI failed — run details

diff --git a/cmd/console/ha_data_stores_test.go b/cmd/console/ha_data_stores_test.go
new file mode 100644
index 000000000..c11d993e4
--- /dev/null
+++ b/cmd/console/ha_data_stores_test.go
@@ -0,0 +1,67 @@
+package main
+
+import (
+ "context"
+ "errors"
+ "testing"
+
+ awss3 "github.com/aws/aws-sdk-go-v2/service/s3"
+ "github.com/carlosframework/platform/internal/console"
+ "github.com/carlosframework/platform/internal/perf"
+ "github.com/carlosframework/platform/internal/release"
+)
+
+func TestBuildHADataStores(t *testing.T) {
+ for _, mode := range []string{"remote", "home", "failure", "invalid"} {
+ t.Run(mode, func(t *testing.T) {
+ ieScope, usScope := "", `,"ha_pools":["ha"]`
+ if mode == "home" {
+ ieScope, usScope = usScope, ""
+ }
+ cfg := console.Config{HomeRegion: "ie", HARegions: []string{"ie", "us"}, HACapacityConfig: `{"v":1,"regions":{"ie":{"aws_region":"eu-west-1","data_bucket":"ie-data","data_bucket_region":"eu-west-1"` + ieScope + `},"us":{"aws_region":"us-east-1","data_bucket":"us-data","data_bucket_region":"us-east-2"` + usScope + `}},"fixed_boxes":{}}`}
+ if mode == "invalid" {
+ cfg.HACapacityConfig = "invalid"
+ }
+ calls := 0
+ stores := buildHADataStores(context.Background(), cfg, new(perf.Recorder), func(_ context.Context, bucket, region string) (*release.S3Store, error) {
+ calls++
+ wantBucket, wantRegion := "us-data", "us-east-2"
+ if mode == "home" {
+ wantBucket, wantRegion = "ie-data", "eu-west-1"
+ }
+ if bucket != wantBucket || region != wantRegion {
+ t.Fatalf("opened %s %s", bucket, region)
+ }
+ if mode == "failure" {
+ return nil, errors.New("unavailable")
+ }
+ return &release.S3Store{Bucket: bucket, Client: awss3.New(awss3.Options{Region: region})}, nil
+ })
+ if mode == "invalid" {
+ if calls != 0 || len(stores) != 0 {
+ t.Fatal("invalid config opened stores")
+ }
+ return
+ }
+ if calls != 1 {
+ t.Fatalf("opens=%d", calls)
+ }
+ if mode == "failure" {
+ if len(stores) != 0 {
+ t.Fatal("failed store retained")
+ }
+ return
+ }
+ code, other := "us", "ie"
+ if mode == "home" {
+ code, other = other, code
+ }
+ if len(stores) != 1 || stores[code] == nil || stores[other] != nil {
+ t.Fatalf("stores=%v", stores)
+ }
+ if _, ok := stores[code].(release.PageLister); !ok {
+ t.Fatal("wrapper lost bounded listing")
+ }
+ })
+ }
+}
diff --git a/cmd/console/main.go b/cmd/console/main.go
index 013660429..97c495774 100644
--- a/cmd/console/main.go
+++ b/cmd/console/main.go
@@ -632,6 +632,7 @@ func serve() {
cfg.WakeRetryReset = console.NewProductionWakeRetryReset()
}
cfg.Perf = rec
+ cfg.HADataStores = buildHADataStores(context.Background(), cfg, rec, release.NewS3StoreIn)
srv, err := console.NewServer(cfg, st)
if err != nil {
log.Fatal(err)
@@ -2086,3 +2087,20 @@ func startHACapacity(ctx context.Context, srv *console.Server, cfg console.Confi
close(done)
return done
}
+
+func buildHADataStores(ctx context.Context, cfg console.Config, rec *perf.Recorder, open func(context.Context, string, string) (*release.S3Store, error)) map[string]release.Store {
+ regions, err := console.HADataStoreRegions(cfg)
+ if err != nil {
+ return nil
+ }
+ stores := make(map[string]release.Store)
+ for code, coords := range regions {
+ store, err := open(ctx, coords.Bucket, coords.Region)
+ if err != nil {
+ log.Printf("console: HA data store for %s: %v", code, err)
+ continue
+ }
+ stores[code] = console.TimeS3Store(store, rec)
+ }
+ return stores
+}
diff --git a/docs/site/cli.md b/docs/site/cli.md
index 3a87806db..9804272bd 100644
--- a/docs/site/cli.md
+++ b/docs/site/cli.md
@@ -1052,7 +1052,9 @@ working. Use `carlos env set` for a value that is meant to be empty.
In an active high availability region, a non-hibernating binary socket create is refused with status 400 before the instance or its data is created. The refusal does not apply to resident rootfs instances. A binary socket import gets the same refusal before import work begins. A hibernating import keeps the existing status 409 refusal.
-If earlier data remains for the address, the create is refused with status 409. The message names only the fixed class of data found: lock, files, replica or other. Choose another address, or ask an operator to purge the old data. If home data cannot be checked, the create is refused with status 503 before any write. Try again. A non-home or pooled high availability data create is refused with status 409 because that data cannot be checked here. Use the console's home region without a pool.
+If earlier data remains for the address, the create is refused with status 409. The message names the data found: lock, files, replica or other. Choose another address, or ask an operator to purge the old data.
+
+An operator can enable high availability for named pools in a region. Only instances and sidecars for apps placed in those pools use high availability there. Other creates work as usual. High availability creates also work outside the console's home region, using that region's data for the earlier-data check. If the data cannot be checked, the create is refused with status 503 before any write. Try again. If any box uses different data storage from the region, high availability creates are refused with status 503. The message names the box. An operator must reconfigure or retire it. If high availability covers every create in a region, a non-home or pooled high availability create is refused with status 409: "use the console's home region without a pool."
New creates in an HA region need a box with room. A 503 response tells you to retry after 60 seconds. Missing evidence pauses creates. It does not report zero capacity. Existing instances can still wake.
diff --git a/docs/superpowers/plans/2026-11-05-region-ha-g3-b10.md b/docs/superpowers/plans/2026-11-05-region-ha-g3-b10.md
new file mode 100644
index 000000000..60ae20116
--- /dev/null
+++ b/docs/superpowers/plans/2026-11-05-region-ha-g3-b10.md
@@ -0,0 +1,83 @@
+# Region HA G3-B10: born HA only in a named HA pool
+
+Plan, 2026-11-05. Spec: `2026-10-26-region-ha-without-claims-design.md` §23 (addendum B10). Branch `region-ha-g3-b10` from origin/main ddbc0297. Review budget: one Astra review of addendum and plan, at most three rounds; Opus task and branch reviews, at most three rounds (stopping rules). Ledger: `.superpowers/sdd/2026-11-05-region-ha-g3-b10/`.
+
+**Finish line.** A console on this branch, given `CONSOLE_HA_REGIONS=us` and a capacity config whose `us` entry has `"ha_pools":["ha"]`, creates a born-HA instance in app pool `ha` in `us` (proof against the configured US data bucket), creates a plain US instance exactly as with `us` not listed, and still refuses moves and imports touching `us`. Dev's config (no `ha_pools`) behaves as on main. No release, apply or drill.
+
+## Rulings
+
+| # | Ruling |
+|---|---|
+| R1 | Paul 2026-11-05: only named-HA-pool creates are born HA in a scoped region; plain creates stay legacy; no customer notice. |
+| R2 | Controller: the scope lives in `CONSOLE_HA_CAPACITY_CONFIG` (`regions.<code>.ha_pools`), the document that already names the region's data bucket. No new env var. |
+| R3 | Controller: create-path gates move to `haCreate(region, pool)`; transfer gates (moves, seed `--from`, import, placement changes, `haTransferRegion`, `refuseHAImport`, `apiplacements.go`) stay on `haRegion` (N-HA4). |
+| R4 | Controller: a scoped region's proof (home or not) is two bounded LISTs (one key each) of whole prefixes in the config-named bucket, not the LTX level walk: stricter, one path, and the console holds no litestream client for remote buckets (Astra A2). |
+| R8 | Astra r3 (round 3 of 3): A6 still P1 (stale files). 8a3d302's answer (for Paul): fail closed, any age; refusal names region label and the mismatched box; no fourth plan round; Opus reviews check the gate specifically; sidecars stay in. |
+| R7 | Astra r2: A6 (P1, same family as A2) answered by invariant I-B10, enforced in one place (the observation) with a seeded witness; A7 (Retry-After) accepted. Prefix sameness is a card precondition: no box reports its prefix, and box changes are out of scope. |
+| R6 | Astra r1: A1 (prefix needs the activator config), A2 (configured bucket, also at home), A3 (`--from` unchanged), A4 (invalid config is 503, not F5), A5 (F1 by predicate) accepted. |
+| R5 | Controller: new or changed refusal sentences name regions by label (`offlinePlace`), not code. The no-room sentence (`nocapacity.go`) is in a touched file, so its "ie" is fixed too. One Luna pass, applied verbatim. |
+
+## Task 1: config and the predicate
+
+Files: `internal/console/hacapacity.go`, `internal/console/seedmove.go`, `internal/console/server.go`.
+
+- [ ] `haCoordinates` gains `HAPools []string \`json:"ha_pools,omitempty"\``; `haOnlyFields` for a region allows `ha_pools`. Present means: a JSON array, non-empty, each entry matches the pool-name rule the manifest uses for `Pool` (find it; do not invent one), distinct, never the shared pool (`""` or `@shared`). Anything else: `errHACapacity`. Absent: unscoped. `null` is already refused by `haJSON`.
+- [ ] Server start (`New` or where config is first read) parses `cfg.HACapacityConfig` once with `parseHACapacityConfig(raw, cfg.HARegions, cfg.HomeRegion)` and keeps `map[region code]pools` for scoped regions plus a `haScopeInvalid` bool (true when `HARegions` is non-empty and the parse failed or raw is empty). The observer's own parse is unchanged.
+- [ ] `func (s *Server) haCreate(region, pool string) bool`: `haRegion(region)` and (region unscoped or `pool` in its list). The home region `""` is looked up by `cfg.HomeRegion`, as `haRegion` does. With `haScopeInvalid`, every HA region reads as unscoped (today's rule) for `haCreate`; Task 3 turns its HA data creates into 503.
+- [ ] `shouldStampHA` uses `haCreate(rec.Region, rec.Pool)`.
+- [ ] Unit tests: parser accepts/refuses `ha_pools` shapes (absent, `[]`, duplicate, shared, bad name, non-array, case-variant key); `haCreate` matrix (unscoped home, scoped us with `ha`/""/other pool, non-HA region).
+
+## Task 2: create-path gates
+
+Files: `internal/console/apiinstances.go`, `hacreate.go`, `nocapacity.go`, `apisidecars.go`, `domainattach.go`.
+
+- [ ] Switch to `haCreate(region, <pool>)`, pool = `m.Pool` or `rec.Pool` as the line already has: `apiinstances.go` app-derived eligibility (~1839), `checkPlacement`'s `roomIn` skip (~1957), the placement order (~2010, ~2345), the HA duplicate read (~2281); `haCreateShapeRefusal` (F1, uses `rec.Pool`); `requireHACreateCapacity` (its `pool` argument); `apisidecars.go` `rec.HA` (~369) and the duplicate read (~418); `domainattach.go` `haRegion("")` (~228, pool of the record it would write, `""`).
+- [ ] Leave on `haRegion`: `seedmove.go` transfer helpers, `apiinstances.go` seeded block (~2330), `apiplacements.go`, the observer and metrics. Grep every `haRegion(` caller and list each with its class in the ledger.
+- [ ] `noCapacityRefusal` / `noRoom`: user-facing region becomes the label (`offlinePlace`); the alert and log keep the code.
+
+## Task 3: the proof outside home
+
+Files: `internal/console/createleftovers.go`, `internal/console/server.go`, `cmd/console/main.go`.
+
+- [ ] `Config.HADataStores map[string]release.Store` (region code to the config-named data bucket). `cmd/console/main.go` builds one per **scoped** region, home included, from the parsed config (`release.NewS3StoreIn(ctx, data_bucket, data_bucket_region)`, wrapped like `seedData`). Build failure: no store for that region (creates there answer 503). Put the construction in a named function so a test drives it.
+- [ ] `leftoverReplicaRefusal`, HAData branch, after the existing duplicate/read-error answers:
+ - `haScopeInvalid`: 503 with the existing `haCapacityUnknownRefusal` sentence and `Retry-After: 60`, before F5 and before any LIST (A4).
+ - unscoped region: today's code unchanged (F5 for non-home or pooled; home proof).
+ - scoped region (home or not): `cfg.HibernateBucket == ""` is 503 `unsure` (A1: the prefix is unknown). Store = `HADataStores[region code]`; nil or not a `PageLister` is 503 `unsure`. `firstHALeftover(store, HibernatePrefix(cfg.HibernatePrefix, host)+"/")`, then `firstHALeftover(store, "moves/<host>/")` (use `activator.MovesPrefix`). Either error is 503; any key is 409 naming the class (reuse `firstHALeftover`'s class for the first; staging is "replica"). Log errors with the host; never return the bucket name. `SeedData` and `dbReplica` are not used on this path (A2).
+- [ ] I-B10 (A6, R8): `func (o *HACapacityObservation) MixedStorage(region string) (box string, mixed bool)`: true when any non-malformed file, **of any age**, whose placement equals the region's (`""` for home, as `scope` computes it) reports a valid `data_bucket` or `data_bucket_region` differing from the config's coordinates; `box` is that file's box reference (from its key, as the observation names boxes elsewhere). It must not depend on `available(now)` freshness of that file. `requireHACreateCapacity`, for a scoped region's HA create only, refuses 503 with `haCapacityRetryAfter: 60` before `Decide`, with a NEW sentence naming the region label and the box (draft: "%s has a box on a different data bucket (%s). Nothing was created. An operator must fix or retire that box."; the controller's Luna pass sets the final text). Log the edges key too. Unscoped regions are untouched.
+- [ ] A7: both leftover-refusal response sites (`apiinstances.go` ~2314, `apisidecars.go` ~447) call `setNoCapacityRetryAfter(w, ref)` before `jsonError`, so the proof's config-unavailable 503 carries `Retry-After: 60`.
+- [ ] The duplicate read at `apiinstances.go` ~2281 and `apisidecars.go` ~418 must still run for every scoped HAData create before capacity (it does when `leftoverCheckApplies` is false; check the home scoped case too).
+- [ ] Sentences: `unsure` and the F5 sentence name the region by label. F5's text is otherwise unchanged (approved copy).
+
+## Task 4: witnesses (production wiring)
+
+Files: new `internal/console/ha_pool_scope_test.go`; `cmd/console/` test for the store builder.
+
+Through the real handlers (`POST /api/cli/apps/<acct>/<app>/instances`, sidecar create), real `Server` construction, a DirStore or fake-S3 deployment store, and a counting `PageLister` fake for the US store. Config: home `ie`, `CONSOLE_HA_REGIONS=us`, capacity config with `us.ha_pools=["ha"]`, an observation allowing pool `ha` in `us`.
+- [ ] Pool `ha` in `us`: 201, record `ha:true`, region `us`, pool `ha`; the US store saw exactly `<prefix>/<host>/` then `moves/<host>/`, limit 1 each; the home store saw nothing.
+- [ ] Scoped home (`ie` home with `ie.ha_pools=["ha"]`, config bucket B, console `HibernateBucket`/`SeedData` A): leftovers only in B refuse 409; A is never listed (A2).
+- [ ] Activator config not loaded (`HibernateBucket` empty) with a scoped `us`: 503, no LIST, no writes (A1).
+- [ ] Invalid `CONSOLE_HA_CAPACITY_CONFIG` with `CONSOLE_HA_REGIONS=us`: pool `ha` create and plain create both 503 capacity-unknown with `Retry-After: 60`, not F5; an existing record still gets the duplicate 409 first (A4).
+- [ ] Unpooled in `us`: 201, `ha:false`; no HA capacity decision, no US store call; same answer and record as with `CONSOLE_HA_REGIONS` empty (compare the two responses).
+- [ ] Pool `other` in `us`: legacy, as above.
+- [ ] Leftover under `instances/<host>/` and under `moves/<host>/`: 409, zero writes (record, lifetime, store grant, index).
+- [ ] US store missing, list error: 503, zero writes.
+- [ ] F1 (A5): direct `haCreateShapeRefusal` predicate test with `Hibernate=false` for scoped `us` pool `ha` (refused), pool "" (nil), unscoped `ie` (refused). Through HTTP: a sidecar create in pool `ha` on a non-hibernating sidecar manifest is 400 "high availability sidecars must allow hibernation."; unpooled in `us` is not.
+- [ ] Move into `us` and out of `us` of a legacy record, and seed import into `us`: still refused with the existing sentences. Seed `--from` keeps main's behaviour (`TestSeedsRemainLegacyAndSidecarsBornHA` unchanged) (A3).
+- [ ] Dev shape (`ie` home, `CONSOLE_HA_REGIONS=ie`, no `ha_pools`): existing `ha_born_test.go`, `hacreate_test.go`, `hacreatecapacity_test.go`, `sidecar_ha_test.go` pass unmodified; a pooled `ie` HAData create still gets F5.
+- [ ] I-B10 witness: two fresh boxes placed `us`, both serving pool `ha`, one on the configured bucket and one on another bucket (and separately another bucket region): pool `ha` create is 503 with the I-B10 sentence (region label, box) and `Retry-After: 60`, zero writes; an admitted box whose edges file has gone stale (stopped publishing) still blocks; once its file is rewritten matching or deleted, the create succeeds; a plain `us` create is unaffected; unscoped `ie` with a mismatched box behaves as on main.
+- [ ] I-B10 seeded simulation (one test, fixed seeds, ~500 iterations, under 2 s): random sets of edges files (placement, bucket, bucket region, pools, freshness, malformed) for a scoped `us`; assert that whenever `requireHACreateCapacity` returns nil for pool `ha`, every well-formed file placed `us`, of any age, has the configured bucket and bucket region (or does not report them). Mutation check: dropping the MixedStorage call must fail it (record in the ledger, then restore).
+- [ ] A7 witness: the A4 invalid-config 503 through the instance and sidecar handlers carries `Retry-After: 60`.
+- [ ] Store builder test: config with `us` (bucket, region) and `ie` home yields one store for `us`, none for home, with the configured bucket and region.
+
+Run: `nice -n 19 go test ./internal/console -run 'HA|Leftover|Sidecar|Capacity|Rootfs' -count=1` and `go test ./cmd/console -run <builder test> -count=1`. `go vet ./internal/console ./cmd/console`. GOOS=darwin and windows `go build ./...`.
+
+## Task 5: copy, docs, census
+
+- [ ] Extract every new or changed user-facing sentence; one Luna pass; apply verbatim (no em dashes).
+- [ ] `docs/site/cli.md` lines that quote F5 or describe HA creates: update if the behaviour they state changed.
+- [ ] If CI's census fails, `make census-card`, CLAIMS, `make census-propose NAME=region-ha-g3-b10`; Opus approval recorded on #280.
+
+## Out of scope
+
+IAM (G3 card item 3), the release, the console drop-ins (card item 10, which gains `"ha_pools":["ha"]`), dev, moves and imports into HA regions (P4, P5), box-side changes.
diff --git a/docs/superpowers/specs/2026-10-26-region-ha-without-claims-design.md b/docs/superpowers/specs/2026-10-26-region-ha-without-claims-design.md
index a68f73876..922d518c1 100644
--- a/docs/superpowers/specs/2026-10-26-region-ha-without-claims-design.md
+++ b/docs/superpowers/specs/2026-10-26-region-ha-without-claims-design.md
@@ -1,6 +1,6 @@
# Region HA without claims: N-box regions behind a load balancer
-Design, 2026-10-26, **rev 6.2**: rev 6 APPROVED by Paul on 2026-10-26, plus his ruling N-HA7 the same day (a scope ruling, not a redesign: §2.1, §8.4, §13, §19). Astra rounds 1 to 3 are complete, and the review budget is spent (AGENTS.md, stopping rules). Branch `design-region-ha-no-claims`, cut from `origin/main` at ddf3b929. Nothing here is built.
+Design, 2026-10-26, **rev 6.3** (§23 B10 addendum, 2026-11-05): rev 6 APPROVED by Paul on 2026-10-26, plus his ruling N-HA7 the same day (a scope ruling, not a redesign: §2.1, §8.4, §13, §19). Astra rounds 1 to 3 are complete, and the review budget is spent (AGENTS.md, stopping rules). Branch `design-region-ha-no-claims`, cut from `origin/main` at ddf3b929. Nothing here is built.
This spec supersedes every claim-dependent part of "Region HA, spec 2: two-box regions" (`2026-10-15-region-ha-two-box-regions-design.md`, rev 21, cited **S2 §n**) and of spec 1 (`2026-10-04-region-ha-box-placement-design.md`, cited **S1 §n**). §16 lists what it reuses from S2, plan 2a (6834659c) and plan 2b (b1118925), and the removals this series owns. Line citations are to this worktree unless they name a module path.
@@ -781,3 +781,28 @@ One 3,000-seed sweep per revision, run serially at nice 19.
## 22. Open questions for Paul
None.
+
+## 23. Addendum B10: born HA only in a named HA pool (2026-11-05)
+
+**Ruling.** Paul, 2026-11-05 ~18:00Z (G3-B10, via agent manager 8a3d302): in a region whose HA is scoped to named pools, only creates placed in one of those pools are born HA. Every other create in that region stays legacy on the old box and works exactly as it does in a non-HA region. Customers join the pool later, by choice; nobody is placed without consent. Born-HA creation works in a non-home region.
+
+**What it replaces.**
+- N-HA7's stamp rule, for scoped regions only: `CONSOLE_HA_REGIONS` alone no longer stamps every plain instance create there. Unscoped regions (dev IE today) keep N-HA7's rule unchanged.
+- P2a's F5 cut (plan `2026-11-01-region-ha-p2-console.md`, Rulings and P2-4/C3: "non-home and pool HA data creates stay refused for G3, 409"), for scoped regions only. Unscoped regions keep F5.
+
+**The switch.** A region's entry in `CONSOLE_HA_CAPACITY_CONFIG` may carry `"ha_pools": ["<pool>", ...]`: a non-empty list of distinct named pools (not the shared pool). A region with the key is **scoped**; a region without it is **unscoped**. The console parses the document once at start for this. An invalid or missing document is not "unscoped": while `CONSOLE_HA_REGIONS` is set, every create that would be HA data under either reading (an unscoped region's rule or a pool create) answers the existing capacity-unknown 503 (`Retry-After: 60`) before F5 or any proof, after the door's duplicate and read-error answers. Plain creates in that state follow today's unscoped rule.
+
+**The rule, per create door (instance, standalone sidecar, domain-attach first route).** Let `haCreate(region, pool)` be: the region is in `CONSOLE_HA_REGIONS`, and either it is unscoped or `pool` is in its `ha_pools`. Every create-path HA gate asks `haCreate` instead of `haRegion`: the stamp, the binary-socket shape refusal (F1), the HA capacity decision, the HA duplicate read, the placement-check ordering, the app-derived region's eligibility, and the standalone sidecar's HA flag. A create with `haCreate` false is a legacy create, gate for gate.
+
+**The proof in a scoped region (§11's leftover refusal).** A born-HA data create in a scoped region, home or not, proves the host's prefixes empty in **the data bucket the config names for that region** (`data_bucket`, `data_bucket_region`), not in the console's own data bucket, so the proof looks where the region's boxes write:
+- one bounded LIST (max one key) of `<hibernate prefix>/<host>/` and one of `moves/<host>/`, in that bucket. Any object refuses the create (409, names the class). No store for the region, a store without bounded listing, or a failed LIST refuses with 503 before any write;
+- the hibernate prefix is the console's own, from its activator configuration. If that configuration did not load (no `HibernateBucket`), the prefix is unknown and the create answers 503 before any LIST;
+- the console's role needs `s3:ListBucket` on that bucket for prefixes `instances/*` and `moves/*` (G3 card item 3; for a scoped home region, the existing grant on its own bucket). This build adds no IAM.
+
+**Invariant I-B10: the proof and every box that could run the record share one storage location.** The configured bucket is where the console looks; reconcile admits a record on any box of its region and pool. So a scoped HA create is refused (503, `Retry-After: 60`) while any well-formed edges file placed in that region, **whatever its age**, reports a valid `data_bucket` or `data_bucket_region` other than the config's (Astra round 3: a box whose publication has stopped may still reconcile and wake records). The block clears only when that file is rewritten matching, or deleted when the box retires. The refusal names the region by its label and the mismatched box, so an operator can find it. The check lives in one place (the capacity observation, consulted by the create door's capacity step). Plain creates and unscoped regions are untouched (agent manager 8a3d302 for Paul, 2026-11-05). Boxes do not report their hibernate prefix, so the prefix half of I-B10 is an operator precondition: the region's boxes use the console's hibernate prefix, and the G3 card checks it on the US box and in the group config. As in P2a, the proof reserves nothing and first wake still proves an empty prefix. Unscoped regions keep P2a's home proof and F5 unchanged.
+
+**Unchanged (N-HA4).** Offline moves, seed import and placement changes into or out of an HA region stay refused region-wide, scoped or not, for legacy hosts as well as HA ones. Seed `--from` keeps its existing rules (`seedPlacementRefusal`, never stamped), as on main.
+
+**Dev.** Dev's IE entry carries no `ha_pools`, so dev behaves exactly as today: plain home creates are born HA, pooled and non-home HA data creates get F5, and existing records (hapair-a1) keep their immutable flag.
+
+**Review budget.** One Astra review of this addendum with its plan, at most three rounds (stopping rules). Round 1 (A1-A5, NOT READY) is answered in this text: the scoped proof always uses the configured bucket (A2), needs the activator prefix (A1), `--from` is unchanged (A3), and an invalid config is a 503 (A4). Round 2 (A6, A7) adds I-B10's storage gate and the Retry-After header on the proof's 503s.
diff --git a/internal/console/apiinstances.go b/internal/console/apiinstances.go
index 885d4acd3..378db2db3 100644
--- a/internal/console/apiinstances.go
+++ b/internal/console/apiinstances.go
@@ -1836,7 +1836,7 @@ func (s *Server) handleAPIInstanceCreate(w http.ResponseWriter, r *http.Request)
if regionFrom == "app" {
// Active HA eligibility is checked from the shared observation after validation.
var cands []regionCandidate
- if !s.haRegion(region) {
+ if !s.haCreate(region, m.Pool) {
snap, err := s.liveEdges(ctx)
if err != nil {
log.Printf("console: api instances create %s/%s: read edges: %v", acct.Sqid, app, err)
@@ -1954,7 +1954,7 @@ func (s *Server) handleAPIInstanceCreate(w http.ResponseWriter, r *http.Request)
if placed == "" && region != "" {
// Region HA (spec 2 §7, H27): a region with no box that has room is
// the no-room refusal, before this gate answers it as a 400.
- if !s.haRegion(region) {
+ if !s.haCreate(region, m.Pool) {
if err := s.roomIn(ctx, region, m.Pool); err != nil {
writeClaimResponseError(w, err)
return false
@@ -2007,7 +2007,7 @@ func (s *Server) handleAPIInstanceCreate(w http.ResponseWriter, r *http.Request)
}
return true
}
- if !s.haRegion(region) && !checkPlacement() {
+ if !s.haCreate(region, m.Pool) && !checkPlacement() {
return
}
channel := strings.TrimSpace(req.Channel)
@@ -2278,7 +2278,7 @@ func (s *Server) handleAPIInstanceCreate(w http.ResponseWriter, r *http.Request)
}
}
// Capacity must not hide a duplicate outside the leftover rail's scope.
- if s.haRegion(region) && !s.leftoverCheckApplies(region, rec.Pool) && !(s.shouldStampHA(rec) && !seeded && rec.DerivesPaths()) {
+ if s.haCreate(region, rec.Pool) && !s.leftoverCheckApplies(region, rec.Pool) && !(s.shouldStampHA(rec) && !seeded && rec.DerivesPaths()) {
if _, _, err := s.readRecord(ctx, acct.Sqid, app, host); err == nil {
jsonError(w, http.StatusConflict, "instance "+host+" already exists")
return
@@ -2311,6 +2311,7 @@ func (s *Server) handleAPIInstanceCreate(w http.ResponseWriter, r *http.Request)
taken: host + " still holds data from a deleted instance. Choose another address, or ask an operator to purge it.",
unsure: "could not check whether " + host + " is free. Try again.",
}); ref != nil {
+ setNoCapacityRetryAfter(w, ref)
jsonError(w, ref.Status, ref.Msg)
return
}
@@ -2342,7 +2343,7 @@ func (s *Server) handleAPIInstanceCreate(w http.ResponseWriter, r *http.Request)
jsonError(w, ref.Status, ref.Msg)
return
}
- if s.haRegion(region) && !checkPlacement() {
+ if s.haCreate(region, rec.Pool) && !checkPlacement() {
return
}
// Every ordinary check has passed: a seed door takes over from here, and
diff --git a/internal/console/apisidecars.go b/internal/console/apisidecars.go
index 52427fa95..fb035de67 100644
--- a/internal/console/apisidecars.go
+++ b/internal/console/apisidecars.go
@@ -366,7 +366,7 @@ func (s *Server) handleAPISidecarCreate(w http.ResponseWriter, r *http.Request)
// The shape rails, at the door — the same door the box's reconcile pass
// re-checks them at, because neither side trusts the other about what is
// in the bucket. The message is ValidateSidecarShape's own.
- rec.HA = s.haRegion(rec.Region)
+ rec.HA = s.haCreate(rec.Region, rec.Pool)
if rec.HA && !m.HibernateOrDefault() {
jsonError(w, http.StatusBadRequest, "high availability sidecars must allow hibernation.")
return
@@ -415,7 +415,7 @@ func (s *Server) handleAPISidecarCreate(w http.ResponseWriter, r *http.Request)
writeDoorRefusalJSON(w, r, ref)
return
}
- if s.haRegion(region) && !s.leftoverCheckApplies(region, rec.Pool) {
+ if s.haCreate(region, rec.Pool) && !s.leftoverCheckApplies(region, rec.Pool) {
if _, err := provision.GetSidecarRecord(ctx, s.cfg.Releases, acct.Sqid, app, name); err == nil {
jsonError(w, http.StatusConflict, "sidecar "+name+" already exists")
return
@@ -444,6 +444,7 @@ func (s *Server) handleAPISidecarCreate(w http.ResponseWriter, r *http.Request)
taken: "the name " + name + " still holds data from a deleted sidecar. Choose another name, or ask an operator to purge it.",
unsure: "could not check whether the name " + name + " is free. Try again.",
}); ref != nil {
+ setNoCapacityRetryAfter(w, ref)
jsonError(w, ref.Status, ref.Msg)
return
}
diff --git a/internal/console/createleftovers.go b/internal/console/createleftovers.go
index 468e940e7..7e89d3ec3 100644
--- a/internal/console/createleftovers.go
+++ b/internal/console/createleftovers.go
@@ -164,11 +164,17 @@ func (s *Server) leftoverReplicaRefusal(parent context.Context, c leftoverCreate
if c.sidecar {
kind = "sidecar"
}
- name := s.offlineName(c.region)
+ name := s.offlinePlace(c.region)
+ if s.haScopeInvalid {
+ return &doorRefusal{Status: http.StatusServiceUnavailable, Msg: fmt.Sprintf(haCapacityUnknownRefusal, name), haCapacityRetryAfter: 60}
+ }
+ if len(s.haPools[s.homeRegionOut(c.region)]) > 0 {
+ return s.scopedHALeftoverRefusal(ctx, c, kind, name)
+ }
if s.homeRegionIn(c.region) != "" || c.pool != "" {
return &doorRefusal{Status: http.StatusConflict, Msg: fmt.Sprintf("high availability data creation is not available yet in %s. use the console's home region without a pool.", name)}
}
- unsure = fmt.Sprintf("could not check this %s's data in %s. nothing was created. try again. persistent failures may require an operator to check home data access.", kind, name)
+ unsure = fmt.Sprintf("could not check this %s's data in %s. nothing was created. try again. persistent failures may require an operator to check data access for this region.", kind, name)
if s.cfg.SeedData == nil || !s.leftoverCheckApplies(c.region, c.pool) {
return &doorRefusal{Status: http.StatusServiceUnavailable, Msg: unsure}
}
@@ -198,3 +204,26 @@ func (s *Server) leftoverReplicaRefusal(parent context.Context, c leftoverCreate
}
return nil
}
+
+func (s *Server) scopedHALeftoverRefusal(ctx context.Context, c leftoverCreate, kind, name string) *doorRefusal {
+ unsure := &doorRefusal{Status: http.StatusServiceUnavailable,
+ Msg: fmt.Sprintf("could not check this %s's data in %s. nothing was created. try again. persistent failures may require an operator to check data access for this region.", kind, name), haCapacityRetryAfter: 60}
+ store := s.cfg.HADataStores[s.homeRegionOut(c.region)]
+ if s.cfg.HibernateBucket == "" || store == nil {
+ return unsure
+ }
+ for i, prefix := range []string{activator.HibernatePrefix(s.cfg.HibernatePrefix, c.host) + "/", activator.MovesPrefix(c.host)} {
+ class, err := firstHALeftover(ctx, store, prefix)
+ if err != nil {
+ log.Printf("console: %s: HA prefix check for %s: %v", c.logTag, c.host, err)
+ return unsure
+ }
+ if class != "" {
+ if i == 1 {
+ class = "replica"
+ }
+ return &doorRefusal{Status: http.StatusConflict, Msg: fmt.Sprintf("%s still holds %s from a deleted %s. choose another address, or ask an operator to purge it.", c.host, class, kind)}
+ }
+ }
+ return nil
+}
diff --git a/internal/console/domainattach.go b/internal/console/domainattach.go
index 996018853..7ac4b18e5 100644
--- a/internal/console/domainattach.go
+++ b/internal/console/domainattach.go
@@ -225,7 +225,7 @@ func (s *Server) attachDomainAs(ctx context.Context, acct *Account, app, host, k
if ref := s.heldElsewhere(ctx, host, acct.Sqid, app); ref != nil {
return attachResult{}, ref
}
- if s.haRegion("") {
+ if s.haCreate("", "") {
// A standing first-route record is a reattachment, not a new create.
existing, _, readErr := s.readRecord(ctx, acct.Sqid, app, host)
if readErr != nil && !errors.Is(readErr, os.ErrNotExist) {
diff --git a/internal/console/ha_pool_scope_test.go b/internal/console/ha_pool_scope_test.go
new file mode 100644
index 000000000..92370e298
--- /dev/null
+++ b/internal/console/ha_pool_scope_test.go
@@ -0,0 +1,758 @@
+package console
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "math/rand"
+ "net/http"
+ "net/http/httptest"
+ "path/filepath"
+ "reflect"
+ "strings"
+ "testing"
+ "time"
+
+ lsfile "github.com/benbjohnson/litestream/file"
+ "github.com/carlosframework/platform/internal/boxid"
+ "github.com/carlosframework/platform/internal/boxid/boxidtest"
+ "github.com/carlosframework/platform/internal/objstore"
+ "github.com/carlosframework/platform/internal/provision"
+ "github.com/carlosframework/platform/internal/release"
+)
+
+func TestHAPoolConfig(t *testing.T) {
+ for _, tc := range []struct {
+ name, field string
+ valid bool
+ }{
+ {"absent", "", true},
+ {"named", `,"ha_pools":["ha","other"]`, true},
+ {"empty", `,"ha_pools":[]`, false},
+ {"duplicate", `,"ha_pools":["ha","ha"]`, false},
+ {"shared", `,"ha_pools":[""]`, false},
+ {"shared-token", `,"ha_pools":["@shared"]`, false},
+ {"bad-name", `,"ha_pools":["HA"]`, false},
+ {"long-name", `,"ha_pools":["abcdefghijklmnopq"]`, false},
+ {"string", `,"ha_pools":"ha"`, false},
+ {"object", `,"ha_pools":{}`, false},
+ {"number", `,"ha_pools":[1]`, false},
+ {"null", `,"ha_pools":null`, false},
+ {"case", `,"HA_POOLS":["ha"]`, false},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ raw := strings.Replace(haTestConfig, `"aws_region":"eu-west-1"`, `"aws_region":"eu-west-1"`+tc.field, 1)
+ _, err := parseHACapacityConfig(raw, []string{"ie"}, "ie")
+ if (err == nil) != tc.valid {
+ t.Fatalf("parse = %v; valid=%v", err, tc.valid)
+ }
+ })
+ }
+}
+
+func TestHAPoolCreatePredicate(t *testing.T) {
+ raw := strings.ReplaceAll(haTestConfig, `"de"`, `"us"`)
+ raw = strings.Replace(raw, `"aws_region":"eu-central-1"`, `"ha_pools":["ha"],"aws_region":"eu-central-1"`, 1)
+ for _, invalid := range []bool{false, true} {
+ config := raw
+ if invalid {
+ config = ""
+ }
+ fx := newConsoleFixtureWith(t, consoleFixtureOptions{Tweak: func(c *Config) {
+ c.HomeRegion = "ie"
+ c.HARegions = []string{"ie", "us"}
+ c.HACapacityConfig = config
+ }})
+ if fx.srv.haScopeInvalid != invalid {
+ t.Fatalf("scope invalid = %v", fx.srv.haScopeInvalid)
+ }
+ for _, tc := range []struct {
+ region, pool string
+ want bool
+ }{
+ {"", "", true}, {"ie", "other", true}, {"us", "ha", true},
+ {"us", "", invalid}, {"us", "other", invalid}, {"uk", "ha", false},
+ } {
+ if got := fx.srv.haCreate(tc.region, tc.pool); got != tc.want {
+ t.Errorf("haCreate(%q,%q) = %v", tc.region, tc.pool, got)
+ }
+ }
+ }
+}
+
+func haPoolRaw(region string, scoped bool) string {
+ scope := ""
+ if scoped {
+ scope = `,"ha_pools":["ha"]`
+ }
+ ie, us := "", ""
+ if region == "ie" {
+ ie = scope
+ } else {
+ us = scope
+ }
+ return fmt.Sprintf(`{"v":1,"regions":{"ie":{"aws_region":"eu-west-1","data_bucket":"ie-config-data","data_bucket_region":"eu-west-1"%s},"us":{"aws_region":"us-east-1","data_bucket":"us-config-data","data_bucket_region":"us-east-1"%s}},"fixed_boxes":{"leo":{"region_code":%q,"instance_id":"i-0123456789abcdef0"},"mismatch":{"region_code":%q,"instance_id":"i-0123456789abcdef1"}}}`, ie, us, region, region)
+}
+
+type haPoolWorld struct {
+ *consoleFixture
+ token, region, aws, bucket string
+ control, home, data *haCreateStore
+ evidence release.Store
+ observer *haObserver
+ signer *boxidtest.Signer
+}
+
+func haPoolWorldNew(t *testing.T, region, pool string, tweak func(*Config)) *haPoolWorld {
+ t.Helper()
+ var root string
+ var deployment release.Store
+ home := &haCreateStore{Store: release.NewDirStore(t.TempDir())}
+ data := &haCreateStore{Store: release.NewDirStore(t.TempDir())}
+ fx := newConsoleFixtureWith(t, consoleFixtureOptions{
+ Tweak: func(c *Config) {
+ deployment = c.Releases
+ ds := deployment.(*deletableStore)
+ root = ds.root
+ ds.Store.(*release.DirStore).EnableChangeIndex()
+ keys, err := deployment.List(context.Background(), "")
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, key := range keys {
+ if strings.HasPrefix(key, "control/edges/") || strings.HasPrefix(key, "control/boxes/") || strings.HasPrefix(key, "status/boxes/") {
+ if err := deployment.Delete(context.Background(), key); err != nil {
+ t.Fatal(err)
+ }
+ }
+ }
+ c.HomeRegion = "ie"
+ c.HARegions = []string{region}
+ c.HACapacityConfig = haPoolRaw(region, true)
+ c.HACapacityDirectory = root
+ c.HibernateBucket, c.HibernatePrefix = "home-data-a", "custom"
+ c.SeedData = home
+ c.HADataStores = map[string]release.Store{region: data}
+ c.SecretsPub = testKeyPub
+ if tweak != nil {
+ tweak(c)
+ }
+ },
+ })
+ if _, err := fx.st.CreateAppIn(OpsAccountID, "titogo", "paul@keymail.dev", time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ if err := fx.st.AddMember(OpsAccountID, "alice@keymail.dev", RoleMember, time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ m := titoManifest()
+ m.Pool, m.Regions = pool, nil
+ enableInstances(t, fx, "titogo", m)
+ sm := titoSidecarManifest()
+ sm.Pool, sm.Regions = pool, nil
+ enableSidecars(t, fx, "titogo", sm)
+ w := &haPoolWorld{consoleFixture: fx, token: cliToken(t, fx, "alice@keymail.dev", "pool-scope"), region: region, aws: "us-east-1", bucket: "us-config-data", home: home, data: data, evidence: deployment, signer: boxidtest.NewSigner(t)}
+ if region == "ie" {
+ w.aws, w.bucket = "eu-west-1", "ie-config-data"
+ }
+ for i, ref := range []string{"leo", "mismatch"} {
+ id := fmt.Sprintf("i-0123456789abcdef%d", i)
+ record, _ := w.signer.Record(t, ref, moveTestAccount, w.aws, id)
+ if err := boxid.Publish(context.Background(), deployment, record); err != nil {
+ t.Fatal(err)
+ }
+ haPut(t, deployment, "status/boxes/"+ref+".json", []byte(fmt.Sprintf(`{"label":%q,"generated_at":%q,"metrics":{"instance_id":%q}}`, ref, time.Now().UTC().Format(time.RFC3339Nano), id)))
+ }
+ w.edge(t, "leo", nil)
+ config, _ := parseHACapacityConfig(fx.srv.cfg.HACapacityConfig, fx.srv.cfg.HARegions, fx.srv.cfg.HomeRegion)
+ w.observer = newHAObserver(config, newHACapacityStore(deployment.(*deletableStore).Store, root), boxid.Verifier{Account: moveTestAccount, Certs: w.signer.Certs()}, testKeyFP)
+ w.refresh()
+ if config != nil {
+ obs := w.observer.current.Load()
+ if obs.Decide(region, "ha", time.Now()).Kind != HACapacityAllow {
+ t.Fatalf("fixture capacity: unavailable=%q blockers=%+v", obs.unavailable, obs.CreateBlockers(region, "ha", time.Now()))
+ }
+ }
+ fx.srv.haCapacity.Store(w.observer)
+ fx.srv.LoadRegionNames(context.Background())
+ fx.srv.dbReplica = func(context.Context, string) (replicaReader, error) {
+ t.Error("scoped proof opened the home LTX reader")
+ return nil, errors.New("unexpected home read")
+ }
+ w.track()
+ return w
+}
+
+func (w *haPoolWorld) edge(t *testing.T, ref string, edit func(map[string]any)) {
+ t.Helper()
+ body := haEdit(t, haGolden(t), func(m map[string]any) {
+ m["box"], m["box_id"] = ref, ref
+ m["placement"] = w.region
+ if w.region == "ie" {
+ m["placement"] = ""
+ }
+ m["region"], m["data_bucket"], m["data_bucket_region"] = w.aws, w.bucket, w.aws
+ m["generation"] = time.Now().UTC().Format(time.RFC3339Nano)
+ m["secrets_key_fp"] = testKeyFP
+ m["named_pools"], m["served_pools"] = []string{"ha", "other"}, []string{"", "ha", "other"}
+ m["serves_shared_pool"] = true
+ if edit != nil {
+ edit(m)
+ }
+ })
+ haPut(t, w.evidence, "control/edges/"+ref+".json", body)
+}
+func (w *haPoolWorld) refresh() {
+ w.observer.current.Store(w.observer.observe(context.Background(), time.Now()))
+}
+func (w *haPoolWorld) track() {
+ w.control = &haCreateStore{Store: w.evidence}
+ w.srv.cfg.Releases = w.control
+}
+func (w *haPoolWorld) post(t *testing.T, sidecar bool, body string) (int, http.Header, string) {
+ t.Helper()
+ url := instancesURL(w.consoleFixture, "bab", "titogo")
+ if sidecar {
+ url = sidecarsURL(w.consoleFixture, "bab", "titogo")
+ }
+ return rawReq(t, http.MethodPost, url, w.token, body)
+}
+func (w *haPoolWorld) body(sidecar bool) string {
+ if sidecar {
+ return fmt.Sprintf(`{"name":"bot","region":%q}`, w.region)
+ }
+ return fmt.Sprintf(`{"host":"acme.go.tito.io","region":%q}`, w.region)
+}
+func (w *haPoolWorld) noWrites(t *testing.T) {
+ t.Helper()
+ haCreateNoWrites(t, w.control, w.data)
+ if writes, pages := w.home.counts(); writes != 0 || len(pages) != 0 {
+ t.Fatalf("home store touched: %d %v", writes, pages)
+ }
+}
+
+func TestHAPoolScopedBirth(t *testing.T) {
+ for _, sidecar := range []bool{false, true} {
+ t.Run(fmt.Sprint(sidecar), func(t *testing.T) {
+ w := haPoolWorldNew(t, "us", "ha", nil)
+ code, _, out := w.post(t, sidecar, w.body(sidecar))
+ if code != 201 {
+ t.Fatalf("create = %d %s", code, out)
+ }
+ host := "acme.go.tito.io"
+ if sidecar {
+ rec, err := provision.GetSidecarRecord(context.Background(), w.evidence, "bab", "titogo", "bot")
+ if err != nil || !rec.HA || rec.Region != "us" || rec.Pool != "ha" {
+ t.Fatalf("record=%+v err=%v", rec, err)
+ }
+ host = rec.Host
+ } else {
+ rec, err := provision.GetRecord(context.Background(), w.evidence, "bab", "titogo", host)
+ if err != nil || !rec.HA || rec.Region != "us" || rec.Pool != "ha" {
+ t.Fatalf("record=%+v err=%v", rec, err)
+ }
+ }
+ _, pages := w.data.counts()
+ want := []string{"custom/" + host + "/||1", "moves/" + host + "/||1"}
+ if !reflect.DeepEqual(pages, want) {
+ t.Fatalf("LISTs=%v want=%v", pages, want)
+ }
+ if writes, pages := w.home.counts(); writes != 0 || len(pages) != 0 {
+ t.Fatalf("home accessed: %d %v", writes, pages)
+ }
+ })
+ }
+}
+
+func TestHAPoolProofRefusals(t *testing.T) {
+ for _, sidecar := range []bool{false, true} {
+ for _, mode := range []string{"instance-leftover", "moves-leftover", "missing-activator", "missing-store", "unbounded-store", "list-error", "home-bucket-b"} {
+ t.Run(fmt.Sprintf("%t/%s", sidecar, mode), func(t *testing.T) {
+ region := "us"
+ if mode == "home-bucket-b" {
+ region = "ie"
+ }
+ w := haPoolWorldNew(t, region, "ha", func(c *Config) {
+ switch mode {
+ case "missing-activator":
+ c.HibernateBucket = ""
+ case "missing-store":
+ c.HADataStores = nil
+ case "unbounded-store":
+ c.HADataStores[region] = struct{ release.Store }{c.HADataStores[region]}
+ }
+ })
+ host := "acme.go.tito.io"
+ if sidecar {
+ host = botHost
+ }
+ status := 503
+ class := "files"
+ switch mode {
+ case "instance-leftover", "home-bucket-b":
+ haPut(t, w.data.Store, "custom/"+host+"/files/0/manifest", []byte("old"))
+ status = 409
+ case "moves-leftover":
+ haPut(t, w.data.Store, "moves/"+host+"/anything", []byte("old"))
+ status = 409
+ class = "replica"
+ case "list-error":
+ w.data.pageErr = errors.New("secret-bucket failed")
+ }
+ before := bucketState(t, w.evidence)
+ code, hdr, out := w.post(t, sidecar, w.body(sidecar))
+ if code != status {
+ t.Fatalf("create=%d %s want=%d", code, out, status)
+ }
+ if status == 409 && !strings.Contains(errorText(out), "still holds "+class) {
+ t.Fatal(out)
+ }
+ if status == 503 && hdr.Get("Retry-After") != "60" {
+ t.Fatalf("Retry-After=%q", hdr.Get("Retry-After"))
+ }
+ if strings.Contains(out, "secret-bucket") || strings.Contains(out, w.bucket) {
+ t.Fatalf("private bucket in %s", out)
+ }
+ w.noWrites(t)
+ if !reflect.DeepEqual(before, bucketState(t, w.evidence)) {
+ t.Fatal("control bucket changed")
+ }
+ if mode == "missing-activator" {
+ if _, pages := w.data.counts(); len(pages) != 0 {
+ t.Fatalf("LIST without activator: %v", pages)
+ }
+ }
+ })
+ }
+ }
+}
+
+func TestHAPoolInvalidConfig(t *testing.T) {
+ for _, sidecar := range []bool{false, true} {
+ for _, pool := range []string{"ha", ""} {
+ for _, raw := range []string{"", `{"v":1}`} {
+ t.Run(fmt.Sprintf("%t/%s/%s", sidecar, pool, raw), func(t *testing.T) {
+ w := haPoolWorldNew(t, "us", pool, func(c *Config) { c.HACapacityConfig = raw })
+ code, hdr, out := w.post(t, sidecar, w.body(sidecar))
+ want := fmt.Sprintf(haCapacityUnknownRefusal, w.srv.offlinePlace("us"))
+ if code != 503 || errorText(out) != want || hdr.Get("Retry-After") != "60" {
+ t.Fatalf("invalid config=%d %v %s", code, hdr, out)
+ }
+ w.noWrites(t)
+ if _, pages := w.data.counts(); len(pages) != 0 {
+ t.Fatalf("invalid config listed %v", pages)
+ }
+ })
+ }
+ }
+ }
+}
+
+func TestHAPoolDuplicateBeforeInvalidConfig(t *testing.T) {
+ for _, sidecar := range []bool{false, true} {
+ for _, region := range []string{"us", "ie"} {
+ t.Run(fmt.Sprintf("%t/%s", sidecar, region), func(t *testing.T) {
+ w := haPoolWorldNew(t, region, "ha", nil)
+ if code, _, out := w.post(t, sidecar, w.body(sidecar)); code != 201 {
+ t.Fatalf("setup=%d %s", code, out)
+ }
+ cfg := w.srv.cfg
+ cfg.HACapacityConfig = "invalid"
+ srv, err := NewServer(cfg, w.st)
+ if err != nil {
+ t.Fatal(err)
+ }
+ before := bucketState(t, w.evidence)
+ w.track()
+ srv.cfg.Releases = w.control
+ req := httptest.NewRequest(http.MethodPost, "/api/cli/apps/bab/titogo/instances", strings.NewReader(w.body(sidecar)))
+ if sidecar {
+ req = httptest.NewRequest(http.MethodPost, "/api/cli/apps/bab/titogo/sidecars", strings.NewReader(w.body(sidecar)))
+ }
+ req.Header.Set("Authorization", "Bearer "+w.token)
+ req.Header.Set("Content-Type", "application/json")
+ rr := httptest.NewRecorder()
+ srv.ServeHTTP(rr, req)
+ if rr.Code != 409 || !strings.Contains(rr.Body.String(), "already exists") {
+ t.Fatalf("duplicate=%d %s", rr.Code, rr.Body)
+ }
+ if writes, _ := w.control.counts(); writes != 0 {
+ t.Fatal("duplicate wrote control")
+ }
+ if !reflect.DeepEqual(before, bucketState(t, w.evidence)) {
+ t.Fatal("duplicate changed control")
+ }
+ if _, pages := w.data.counts(); len(pages) != 2 {
+ t.Fatalf("duplicate listed: %v", pages)
+ }
+ })
+ }
+ }
+}
+
+func TestHAPoolLegacyMatchesDisabled(t *testing.T) {
+ for _, pool := range []string{"", "other"} {
+ for _, sidecar := range []bool{false, true} {
+ t.Run(fmt.Sprintf("%s/%t", pool, sidecar), func(t *testing.T) {
+ var responses []map[string]any
+ var records []map[string]any
+ for _, enabled := range []bool{true, false} {
+ w := haPoolWorldNew(t, "us", pool, func(c *Config) {
+ if !enabled {
+ c.HARegions = nil
+ }
+ })
+ w.srv.haCapacity.Store(nil)
+ code, _, out := w.post(t, sidecar, w.body(sidecar))
+ if code != 201 {
+ t.Fatalf("legacy=%d %s", code, out)
+ }
+ var response map[string]any
+ if err := json.Unmarshal([]byte(out), &response); err != nil {
+ t.Fatal(err)
+ }
+ delete(response, "created_at")
+ delete(response, "asset_gen")
+ responses = append(responses, response)
+ key := provision.RecordKey("bab", "titogo", "acme.go.tito.io")
+ if sidecar {
+ key = provision.SidecarRecordKey("bab", "titogo", "bot")
+ }
+ raw, _, err := w.evidence.Get(context.Background(), key)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var rec map[string]any
+ if err := json.Unmarshal(raw, &rec); err != nil {
+ t.Fatal(err)
+ }
+ if rec["ha"] == true {
+ t.Fatalf("legacy stamped %s", raw)
+ }
+ delete(rec, "created_at")
+ delete(rec, "asset_gen")
+ records = append(records, rec)
+ if _, pages := w.data.counts(); len(pages) != 0 {
+ t.Fatalf("legacy listed %v", pages)
+ }
+ }
+ if !reflect.DeepEqual(responses[0], responses[1]) || !reflect.DeepEqual(records[0], records[1]) {
+ t.Fatalf("legacy differs: responses=%v records=%v", responses, records)
+ }
+ })
+ }
+ }
+}
+
+func TestHAPoolShapeAndDevScope(t *testing.T) {
+ no := false
+ w := haPoolWorldNew(t, "us", "ha", nil)
+ for _, pool := range []string{"ha", "", "other"} {
+ ref := w.srv.haCreateShapeRefusal(provision.Record{Region: "us", Pool: pool, Hibernate: &no})
+ if (ref != nil) != (pool == "ha") {
+ t.Fatalf("pool %q shape=%+v", pool, ref)
+ }
+ }
+ dev := haPoolWorldNew(t, "ie", "ha", func(c *Config) { c.HACapacityConfig = haPoolRaw("ie", false) })
+ if ref := dev.srv.haCreateShapeRefusal(provision.Record{Pool: "ha", Hibernate: &no}); ref == nil || ref.Status != 400 {
+ t.Fatalf("dev F1=%+v", ref)
+ }
+ code, _, out := dev.post(t, false, dev.body(false))
+ want := fmt.Sprintf("high availability data creation is not available yet in %s. use the console's home region without a pool.", dev.srv.offlinePlace(""))
+ if code != 409 || errorText(out) != want {
+ t.Fatalf("dev F5=%d %s", code, out)
+ }
+ for _, pool := range []string{"ha", ""} {
+ t.Run("sidecar-"+pool, func(t *testing.T) {
+ w := haPoolWorldNew(t, "us", pool, nil)
+ m := titoSidecarManifest()
+ m.Pool, m.Regions, m.Hibernate = pool, nil, &no
+ enableSidecars(t, w.consoleFixture, "titogo", m)
+ w.track()
+ code, _, out := w.post(t, true, w.body(true))
+ if pool == "ha" {
+ if code != 400 || errorText(out) != "high availability sidecars must allow hibernation." {
+ t.Fatalf("F1=%d %s", code, out)
+ }
+ w.noWrites(t)
+ } else if code != 201 {
+ t.Fatalf("legacy nonhibernating sidecar=%d %s", code, out)
+ }
+ })
+ }
+}
+
+func TestHAPoolMixedStorage(t *testing.T) {
+ for _, field := range []string{"data_bucket", "data_bucket_region"} {
+ for _, stale := range []bool{false, true} {
+ for _, remove := range []bool{false, true} {
+ for _, sidecar := range []bool{false, true} {
+ t.Run(fmt.Sprintf("%s/stale=%t/delete=%t/sidecar=%t", field, stale, remove, sidecar), func(t *testing.T) {
+ w := haPoolWorldNew(t, "us", "ha", nil)
+ w.edge(t, "mismatch", func(m map[string]any) {
+ value := "other-data"
+ if field == "data_bucket_region" {
+ value = "eu-west-2"
+ }
+ m[field] = value
+ if stale {
+ m["generation"] = time.Now().Add(-24 * time.Hour).UTC().Format(time.RFC3339Nano)
+ }
+ })
+ w.refresh()
+ obs, available := w.srv.HACapacity()
+ if !available || obs.Decide("us", "ha", time.Now()).Kind != HACapacityAllow {
+ t.Fatal("matching box must independently offer room")
+ }
+ before := bucketState(t, w.evidence)
+ code, hdr, out := w.post(t, sidecar, w.body(sidecar))
+ label := w.srv.offlinePlace("us")
+ if label == "us" {
+ t.Fatal("fixture did not load the region label")
+ }
+ want := fmt.Sprintf("%s has a box using different data storage: %s. Nothing was created. An operator must reconfigure or retire that box.", label, "mismatch")
+ if code != 503 || hdr.Get("Retry-After") != "60" || errorText(out) != want {
+ t.Fatalf("I-B10=%d %v %s", code, hdr, out)
+ }
+ w.noWrites(t)
+ if !reflect.DeepEqual(before, bucketState(t, w.evidence)) {
+ t.Fatal("I-B10 refusal wrote control")
+ }
+ m := titoManifest()
+ m.Pool, m.Regions = "", nil
+ enableInstances(t, w.consoleFixture, "titogo", m)
+ code, _, out = w.post(t, false, `{"host":"plain.go.tito.io","region":"us"}`)
+ if code != 201 {
+ t.Fatalf("plain create blocked by mixed storage=%d %s", code, out)
+ }
+ if remove {
+ if err := w.evidence.Delete(context.Background(), "control/edges/mismatch.json"); err != nil {
+ t.Fatal(err)
+ }
+ } else {
+ w.edge(t, "mismatch", nil)
+ }
+ w.refresh()
+ m.Pool = "ha"
+ enableInstances(t, w.consoleFixture, "titogo", m)
+ code, _, out = w.post(t, sidecar, w.body(sidecar))
+ if code != 201 {
+ t.Fatalf("repaired create=%d %s", code, out)
+ }
+ })
+ }
+ }
+ }
+ }
+ t.Run("unscoped-home", func(t *testing.T) {
+ w := haPoolWorldNew(t, "ie", "", func(c *Config) { c.HACapacityConfig = haPoolRaw("ie", false) })
+ w.edge(t, "mismatch", func(m map[string]any) { m["data_bucket"] = "other-data" })
+ w.refresh()
+ root := t.TempDir()
+ w.srv.dbReplica = func(_ context.Context, p string) (replicaReader, error) {
+ return lsfile.NewReplicaClient(filepath.Join(root, p)), nil
+ }
+ code, _, out := w.post(t, false, w.body(false))
+ if code != 201 {
+ t.Fatalf("unscoped=%d %s", code, out)
+ }
+ if _, pages := w.data.counts(); len(pages) != 0 {
+ t.Fatalf("unscoped used scoped store: %v", pages)
+ }
+ })
+}
+
+func TestHAPoolTransfersRemainRegional(t *testing.T) {
+ for _, from := range []string{"ie", "us"} {
+ t.Run(from, func(t *testing.T) {
+ w := haPoolWorldNew(t, "us", "", nil)
+ root := t.TempDir()
+ w.srv.dbReplica = func(_ context.Context, p string) (replicaReader, error) {
+ return lsfile.NewReplicaClient(filepath.Join(root, p)), nil
+ }
+ if err := w.st.SetOperator("alice@keymail.dev", true); err != nil {
+ t.Fatal(err)
+ }
+ code, _, out := w.post(t, false, fmt.Sprintf(`{"host":"acme.go.tito.io","region":%q}`, from))
+ if code != 201 {
+ t.Fatalf("legacy setup=%d %s", code, out)
+ }
+ rec, err := provision.GetRecord(context.Background(), w.evidence, "bab", "titogo", "acme.go.tito.io")
+ if err != nil || rec.HA {
+ t.Fatalf("not legacy: %+v %v", rec, err)
+ }
+ to := "us"
+ if from == "us" {
+ to = "ie"
+ }
+ w.track()
+ before := bucketState(t, w.evidence)
+ url := instancesURL(w.consoleFixture, "bab", "titogo") + "/acme.go.tito.io/move/offline"
+ code, _, out = rawReq(t, http.MethodPost, url, w.token, fmt.Sprintf(`{"region":%q}`, to))
+ if code != 409 || errorText(out) != haMoveSentence("us") {
+ t.Fatalf("move=%d %s", code, out)
+ }
+ if writes, _ := w.control.counts(); writes != 0 {
+ t.Fatal("move wrote control")
+ }
+ if !reflect.DeepEqual(before, bucketState(t, w.evidence)) {
+ t.Fatal("move changed control")
+ }
+ })
+ }
+ t.Run("import", func(t *testing.T) {
+ w := haPoolWorldNew(t, "us", "", nil)
+ body := fmt.Sprintf(`{"host":"acme.go.tito.io","region":"us","import":{"sha256":%q,"bytes":10,"replaces":"127.0.0.1:8401"}}`, importSHA)
+ code, _, out := w.post(t, false, body)
+ if code != 409 || errorText(out) != haImportSentence("us") {
+ t.Fatalf("import=%d %s", code, out)
+ }
+ w.noWrites(t)
+ })
+}
+
+// TestHAPoolUnprovenStorage: a box whose edges file cannot be read or parsed
+// (the observer marks both malformed), or whose placement is not a valid
+// region, could be on any bucket, so scoped HA creates fail closed (Opus
+// create-path review F1, F2). Plain creates are untouched.
+func TestHAPoolUnprovenStorage(t *testing.T) {
+ for _, mode := range []string{"malformed", "bad-placement"} {
+ t.Run(mode, func(t *testing.T) {
+ w := haPoolWorldNew(t, "us", "ha", nil)
+ if mode == "malformed" {
+ haPut(t, w.evidence, "control/edges/mismatch.json", []byte(`{"v":`))
+ } else {
+ w.edge(t, "mismatch", func(m map[string]any) { m["placement"] = "US" })
+ }
+ w.refresh()
+ code, hdr, out := w.post(t, false, w.body(false))
+ want := fmt.Sprintf(haCapacityUnknownRefusal, w.srv.offlinePlace("us"))
+ if code != 503 || hdr.Get("Retry-After") != "60" || errorText(out) != want {
+ t.Fatalf("unproven=%d %v %s", code, hdr, out)
+ }
+ w.noWrites(t)
+ m := titoManifest()
+ m.Pool, m.Regions = "", nil
+ enableInstances(t, w.consoleFixture, "titogo", m)
+ if code, _, out = w.post(t, false, `{"host":"plain.go.tito.io","region":"us"}`); code != 201 {
+ t.Fatalf("plain create blocked=%d %s", code, out)
+ }
+ })
+ }
+}
+
+func TestHAPoolMixedStorageSeededSimulation(t *testing.T) {
+ w := haPoolWorldNew(t, "us", "ha", nil)
+ golden := haGolden(t)
+ admitted, refused := 0, 0
+ for _, seed := range []int64{1, 10, 23, 2026, 591} {
+ rng := rand.New(rand.NewSource(seed))
+ for iteration := 0; iteration < 100; iteration++ {
+ wantMixed, wantUnproven := false, false
+ for i := 0; i < 4; i++ {
+ placement := []string{"us", "", "uk"}[rng.Intn(3)]
+ bucket := []string{w.bucket, "other-data", "", "bad/bucket"}[rng.Intn(4)]
+ bucketRegion := []string{w.aws, "eu-west-2", "", "bad-region"}[rng.Intn(4)]
+ malformed := rng.Intn(8) == 0
+ if !malformed && placement == "us" && (bucket == "other-data" || bucketRegion == "eu-west-2") {
+ wantMixed = true
+ }
+ if malformed {
+ wantUnproven = true
+ }
+ body := haEdit(t, golden, func(m map[string]any) {
+ m["placement"], m["data_bucket"], m["data_bucket_region"] = placement, bucket, bucketRegion
+ m["named_pools"] = [][]string{{"ha"}, {"other"}, nil}[rng.Intn(3)]
+ m["generation"] = time.Now().Add(-time.Duration(rng.Intn(48)) * time.Hour).UTC().Format(time.RFC3339Nano)
+ if bucket == "" {
+ delete(m, "data_bucket")
+ }
+ if bucketRegion == "" {
+ delete(m, "data_bucket_region")
+ }
+ })
+ if malformed {
+ body = []byte(`{"v":`)
+ }
+ haPut(t, w.evidence, fmt.Sprintf("control/edges/random-%d.json", i), body)
+ }
+ w.refresh()
+ ref := w.srv.requireHACreateCapacity(context.Background(), "us", "ha")
+ if ref == nil {
+ admitted++
+ if wantMixed || wantUnproven {
+ t.Fatalf("I-B10 seed=%d iteration=%d: admitted ha create with mismatched or unproven storage", seed, iteration)
+ }
+ } else {
+ refused++
+ if !(wantMixed || wantUnproven) || ref.Status != 503 || ref.haCapacityRetryAfter != 60 {
+ t.Fatalf("seed=%d iteration=%d mixed=%v unproven=%v refusal=%+v", seed, iteration, wantMixed, wantUnproven, ref)
+ }
+ }
+ }
+ }
+ if admitted == 0 || refused == 0 {
+ t.Fatalf("simulation coverage: admitted=%d refused=%d", admitted, refused)
+ }
+}
+
+func TestHAPoolRefusalsBeforeLifetimeAndStoreGrant(t *testing.T) {
+ for _, lifetimes := range []bool{false, true} {
+ for _, mode := range []string{"instance-leftover", "moves-leftover", "missing-store", "list-error", "mixed-storage"} {
+ t.Run(fmt.Sprintf("lifetimes=%t/%s", lifetimes, mode), func(t *testing.T) {
+ clock := useLifetimesClock(t)
+ w := haPoolWorldNew(t, "us", "ha", func(c *Config) {
+ if mode == "missing-store" {
+ c.HADataStores = nil
+ }
+ })
+ fake := objstore.NewMemProvisioner("us-east-1")
+ w.srv.cfg.StoreProvisioner = fake
+ w.srv.cfg.StoreDeployment = objstore.Deployment{Backend: "mem", Region: "us-east-1", BucketPrefix: "carlos-"}
+ approveStoreAccount(t, w.consoleFixture, "operator@keymail.dev")
+ m := titoManifest()
+ m.Pool, m.Regions, m.PrivateStorage = "ha", nil, true
+ enableInstances(t, w.consoleFixture, "titogo", m)
+ if lifetimes {
+ turnLifetimesOn(t, w.srv, clock)
+ }
+ status := 409
+ switch mode {
+ case "instance-leftover":
+ haPut(t, w.data.Store, "custom/acme.go.tito.io/lock.json", []byte("old"))
+ case "moves-leftover":
+ haPut(t, w.data.Store, "moves/acme.go.tito.io/anything", []byte("old"))
+ case "missing-store":
+ status = 503
+ case "list-error":
+ status = 503
+ w.data.pageErr = errors.New("secret-list-error")
+ case "mixed-storage":
+ status = 503
+ w.edge(t, "mismatch", func(m map[string]any) { m["data_bucket"] = "other-data" })
+ w.refresh()
+ }
+ w.track()
+ before := bucketState(t, w.evidence)
+ code, _, out := w.post(t, false, w.body(false))
+ if code != status {
+ t.Fatalf("private create=%d %s want %d", code, out, status)
+ }
+ if status == 409 && !strings.Contains(out, "still holds") {
+ t.Fatal(out)
+ }
+ if mode == "mixed-storage" && !strings.Contains(out, "different data storage") {
+ t.Fatal(out)
+ }
+ w.noWrites(t)
+ if !reflect.DeepEqual(before, bucketState(t, w.evidence)) {
+ t.Fatal("refusal changed record, lifetime, grant or index")
+ }
+ if len(fake.Buckets) != 0 || len(fake.Users) != 0 {
+ t.Fatal("refusal provisioned storage")
+ }
+ })
+ }
+ }
+}
diff --git a/internal/console/hacapacity.go b/internal/console/hacapacity.go
index 9da297f15..c2fab489a 100644
--- a/internal/console/hacapacity.go
+++ b/internal/console/hacapacity.go
@@ -40,9 +40,10 @@ var (
)
type haCoordinates struct {
- AWSRegion string `json:"aws_region"`
- DataBucket string `json:"data_bucket"`
- DataBucketRegion string `json:"data_bucket_region"`
+ HAPools []string `json:"ha_pools,omitempty"`
+ AWSRegion string `json:"aws_region"`
+ DataBucket string `json:"data_bucket"`
+ DataBucketRegion string `json:"data_bucket_region"`
}
type haFixedBox struct {
RegionCode string `json:"region_code"`
@@ -128,7 +129,20 @@ func parseHACapacityConfig(raw string, regions []string, home string) (*haCapaci
return nil, errHACapacity
}
for _, fields := range regionFields {
- if !haOnlyFields(fields, "aws_region", "data_bucket", "data_bucket_region") {
+ if _, present := fields["ha_pools"]; present {
+ pools, ok := haField[[]string](fields, "ha_pools")
+ if !ok || len(pools) == 0 {
+ return nil, errHACapacity
+ }
+ seen := map[string]bool{}
+ for _, pool := range pools {
+ if pool == "" || !provision.ValidPool(pool) || seen[pool] {
+ return nil, errHACapacity
+ }
+ seen[pool] = true
+ }
+ }
+ if !haOnlyFields(fields, "aws_region", "data_bucket", "data_bucket_region", "ha_pools") {
return nil, errHACapacity
}
}
@@ -172,6 +186,24 @@ func parseHACapacityConfig(raw string, regions []string, home string) (*haCapaci
c.universe = slices.Compact(c.universe)
return &c, nil
}
+
+// HADataStore is a scoped region's configured data bucket.
+type HADataStore struct{ Bucket, Region string }
+
+func HADataStoreRegions(cfg Config) (map[string]HADataStore, error) {
+ c, err := parseHACapacityConfig(cfg.HACapacityConfig, cfg.HARegions, cfg.HomeRegion)
+ if err != nil {
+ return nil, err
+ }
+ regions := make(map[string]HADataStore)
+ for region, coords := range c.Regions {
+ if len(coords.HAPools) > 0 {
+ regions[region] = HADataStore{Bucket: coords.DataBucket, Region: coords.DataBucketRegion}
+ }
+ }
+ return regions, nil
+}
+
func haGroupReference(account, instance string) string {
sum := sha256.Sum256([]byte("carlos-box-ref-v1|" + account + "|" + instance))
return "g-" + hex.EncodeToString(sum[:])[:20]
@@ -270,6 +302,64 @@ type HACapacityDecision struct {
// These storage keys belong only on operator diagnostics, never member pages.
type HACapacityBlocker struct{ Key, Code string }
+func (o *HACapacityObservation) MixedStorage(region string) (box string, mixed bool) {
+ if o == nil || o.config == nil {
+ return "", false
+ }
+ coords, ok := o.config.Regions[region]
+ if !ok {
+ return "", false
+ }
+ wantPlacement := region
+ if region == o.config.home {
+ wantPlacement = ""
+ }
+ for _, f := range o.files {
+ if f.malformed {
+ continue
+ }
+ placement, valid := haField[string](f.fields, "placement")
+ if _, present := f.fields["placement"]; !present {
+ valid = true
+ }
+ if !valid || !provision.ValidRegion(placement) || placement != wantPlacement {
+ // StorageUnproven refuses files whose placement cannot be read.
+ continue
+ }
+ bucket, valid := haField[string](f.fields, "data_bucket")
+ if valid && objstore.ValidBucketName(bucket) && bucket != coords.DataBucket {
+ return f.ref, true
+ }
+ bucketRegion, valid := haField[string](f.fields, "data_bucket_region")
+ if valid && haAWSRegion.MatchString(bucketRegion) && bucketRegion != coords.DataBucketRegion {
+ return f.ref, true
+ }
+ }
+ return "", false
+}
+
+// StorageUnproven names a box whose edges file could not be read or parsed,
+// or whose placement is not a valid region: such a box could be placed in
+// any region on any bucket, so I-B10 cannot be proven for a scoped create.
+func (o *HACapacityObservation) StorageUnproven() (box string, unproven bool) {
+ if o == nil {
+ return "", false
+ }
+ for _, f := range o.files {
+ if f.malformed {
+ return f.ref, true
+ }
+ placement, valid := haField[string](f.fields, "placement")
+ if _, present := f.fields["placement"]; !present {
+ continue
+ }
+ if !valid || !provision.ValidRegion(placement) {
+ return f.ref, true
+ }
+ }
+ return "", false
+}
+
func (o *HACapacityObservation) Regional(region string, now time.Time) HACapacityRegional {
n, complete, _ := o.project(region, "", false, now)
return HACapacityRegional{n, complete}
diff --git a/internal/console/hacreate.go b/internal/console/hacreate.go
index 5307e77e4..7d61d1d23 100644
--- a/internal/console/hacreate.go
+++ b/internal/console/hacreate.go
@@ -17,8 +17,8 @@ func (s *Server) haCreateShapeRefusal(rec provision.Record) *doorRefusal {
if rec.Demo != nil {
return demoDataRefusal()
}
- if s.haRegion(rec.Region) && rec.KindOrDefault() == "instance" && len(rec.AddrsOrDefault()) == 0 && rec.Runtime == "" && !rec.HibernateOrDefault() {
- return &doorRefusal{Status: http.StatusBadRequest, Msg: fmt.Sprintf("%s has high availability turned on. binary socket instances must allow hibernation. resident rootfs instances are still allowed.", s.offlineName(rec.Region))}
+ if s.haCreate(rec.Region, rec.Pool) && rec.KindOrDefault() == "instance" && len(rec.AddrsOrDefault()) == 0 && rec.Runtime == "" && !rec.HibernateOrDefault() {
+ return &doorRefusal{Status: http.StatusBadRequest, Msg: fmt.Sprintf("%s has high availability turned on. binary socket instances must allow hibernation. resident rootfs instances are still allowed.", s.offlinePlace(rec.Region))}
}
return nil
}
diff --git a/internal/console/hacreate_test.go b/internal/console/hacreate_test.go
index cbdf4c8a4..add41de19 100644
--- a/internal/console/hacreate_test.go
+++ b/internal/console/hacreate_test.go
@@ -205,7 +205,7 @@ func TestHACreateUninspectableRefusesBeforeWrites(t *testing.T) {
}
code, headers, out := haCreatePost(t, fx, body)
status := 503
- want := "could not check this instance's data in ie. nothing was created. try again. persistent failures may require an operator to check home data access."
+ want := "could not check this instance's data in ie. nothing was created. try again. persistent failures may require an operator to check data access for this region."
if mode == "remote" || mode == "pool" {
status = 409
region := "ie"
@@ -461,7 +461,7 @@ func TestHACreateMoveStagingBudget(t *testing.T) {
}
control, data := haCreateTrack(fx)
code, _, out := haCreatePost(t, fx, leftoverDoors[0].body)
- if code != 503 || errorText(out) != "could not check this instance's data in ie. nothing was created. try again. persistent failures may require an operator to check home data access." {
+ if code != 503 || errorText(out) != "could not check this instance's data in ie. nothing was created. try again. persistent failures may require an operator to check data access for this region." {
t.Fatalf("staging error=%d %s", code, out)
}
haCreateNoWrites(t, control, data)
diff --git a/internal/console/hap2_wiring_test.go b/internal/console/hap2_wiring_test.go
index b38496ab2..6b0f352ef 100644
--- a/internal/console/hap2_wiring_test.go
+++ b/internal/console/hap2_wiring_test.go
@@ -309,7 +309,7 @@ func TestHAP2ProductionDoors(t *testing.T) {
tr.setData("instances/" + fromHost + "/secret-key")
case "unreadable", "missing-home-wiring":
status = 503
- want = "could not check this instance's data in ie. nothing was created. try again. persistent failures may require an operator to check home data access."
+ want = "could not check this instance's data in ie. nothing was created. try again. persistent failures may require an operator to check data access for this region."
if mode == "unreadable" {
tr.setFailure(func(a hap2Attempt) bool { return a.bucket == "data-test" })
} else {
diff --git a/internal/console/nocapacity.go b/internal/console/nocapacity.go
index 3c6869719..c9580837a 100644
--- a/internal/console/nocapacity.go
+++ b/internal/console/nocapacity.go
@@ -12,6 +12,7 @@ import (
"time"
"github.com/carlosframework/platform/internal/alerting"
+ "github.com/carlosframework/platform/internal/edgesfile"
"github.com/carlosframework/platform/internal/hostclaim"
"github.com/carlosframework/platform/internal/hostops"
)
@@ -46,13 +47,25 @@ const haCapacityPoolRefusal = "Capacity for pool %s in %s could not be checked.
// requireHACreateCapacity reads the shared observation before a new create's
// first mutation. It selects no executor and grants no runtime authority.
func (s *Server) requireHACreateCapacity(ctx context.Context, region, pool string, sidecarPlacement ...string) *doorRefusal {
- if !s.haRegion(region) {
+ if !s.haCreate(region, pool) {
return nil
}
name := s.homeRegionOut(region)
decision := HACapacityDecision{Kind: HACapacityUnknown}
- if obs, available := s.HACapacity(); available {
- decision = obs.Decide(name, pool, s.haCapacity.Load().clock.Now(), sidecarPlacement...)
+ if obs, available := s.HACapacity(); obs != nil {
+ if len(s.haPools[name]) > 0 {
+ if box, mixed := obs.MixedStorage(name); mixed {
+ log.Printf("console: HA create in %s: mixed storage in %s", name, edgesfile.Prefix+box+".json")
+ return &doorRefusal{Status: http.StatusServiceUnavailable, Msg: fmt.Sprintf("%s has a box using different data storage: %s. Nothing was created. An operator must reconfigure or retire that box.", s.offlinePlace(region), box), haCapacityRetryAfter: 60}
+ }
+ if box, unproven := obs.StorageUnproven(); unproven {
+ log.Printf("console: HA create in %s: storage unproven: %s", name, edgesfile.Prefix+box+".json")
+ return &doorRefusal{Status: http.StatusServiceUnavailable, Msg: fmt.Sprintf(haCapacityUnknownRefusal, s.offlinePlace(region)), haCapacityRetryAfter: 60}
+ }
+ }
+ if available {
+ decision = obs.Decide(name, pool, s.haCapacity.Load().clock.Now(), sidecarPlacement...)
+ }
}
switch decision.Kind {
case HACapacityAllow:
@@ -62,9 +75,9 @@ func (s *Server) requireHACreateCapacity(ctx context.Context, region, pool strin
ref.haCapacityRetryAfter = 60
return ref
default:
- msg := fmt.Sprintf(haCapacityUnknownRefusal, name)
+ msg := fmt.Sprintf(haCapacityUnknownRefusal, s.offlinePlace(region))
if decision.MissingNamedPoolsOnly {
- msg = fmt.Sprintf(haCapacityPoolRefusal, pool, name)
+ msg = fmt.Sprintf(haCapacityPoolRefusal, pool, s.offlinePlace(region))
}
return &doorRefusal{Status: http.StatusServiceUnavailable, Msg: msg, haCapacityRetryAfter: 60}
}
@@ -169,7 +182,7 @@ func (s *Server) noRoom(ctx context.Context, region string) error {
}
}()
}
- return &noCapacityError{Region: name}
+ return &noCapacityError{Region: s.offlinePlace(region)}
}
// placementChooser is the create door's chooser scoped as
diff --git a/internal/console/seedmove.go b/internal/console/seedmove.go
index 64c81429f..fd2a1c52c 100644
--- a/internal/console/seedmove.go
+++ b/internal/console/seedmove.go
@@ -37,6 +37,17 @@ func (s *Server) haRegion(region string) bool {
return region != "" && slices.Contains(s.cfg.HARegions, region)
}
+func (s *Server) haCreate(region, pool string) bool {
+ if !s.haRegion(region) {
+ return false
+ }
+ if region == "" {
+ region = s.cfg.HomeRegion
+ }
+ pools := s.haPools[region]
+ return s.haScopeInvalid || len(pools) == 0 || slices.Contains(pools, pool)
+}
+
// shouldStampHA is the one place a create decides a record is born HA: an
// instance-kind record with no role, in an HA region. Static records and
// replicas are never stamped: boxes ignore non-instance kinds, and a
@@ -45,7 +56,7 @@ func (s *Server) haRegion(region string) bool {
// runs on one box (spec C7), even on a single-tenant deployment whose region
// is in CONSOLE_HA_REGIONS.
func (s *Server) shouldStampHA(rec provision.Record) bool {
- return rec.KindOrDefault() == "instance" && rec.Role == "" && rec.Runtime == "" && s.haRegion(rec.Region)
+ return rec.KindOrDefault() == "instance" && rec.Role == "" && rec.Runtime == "" && s.haCreate(rec.Region, rec.Pool)
}
// haMoveSentence is RHA-P1a-C1 (approved): name is the host's region.
diff --git a/internal/console/server.go b/internal/console/server.go
index 734a3bba9..14a9054da 100644
--- a/internal/console/server.go
+++ b/internal/console/server.go
@@ -558,6 +558,8 @@ type Config struct {
// import spools. Start-up removes the pool's own leftovers from it.
// Empty: the seed doors answer 507.
SeedScratchDir string
+ HADataStores map[string]release.Store
+
// SeedData is the home region's data bucket, where seeds/ lives (the
// bucket HibernateBucket names, at its root). nil: the seed doors
// answer 503.
@@ -995,6 +997,8 @@ type Config struct {
// Server is the console's http.Handler.
type Server struct {
+ haPools map[string][]string
+ haScopeInvalid bool
capacityStart sync.Once
capacityDone chan struct{}
haCapacityStart sync.Once
@@ -1845,6 +1849,16 @@ func NewServer(cfg Config, st *Store) (*Server, error) {
billing: newBillingRuntime(cfg.Billing),
seen: map[string]time.Time{},
}
+ if capacity, err := parseHACapacityConfig(cfg.HACapacityConfig, cfg.HARegions, cfg.HomeRegion); err != nil {
+ s.haScopeInvalid = len(cfg.HARegions) > 0
+ } else {
+ s.haPools = make(map[string][]string)
+ for region, coords := range capacity.Regions {
+ if len(coords.HAPools) > 0 {
+ s.haPools[region] = coords.HAPools
+ }
+ }
+ }
if cfg.Demo.Enabled {
// Seed the same cache requests use. Transient state refuses admission,
// never console boot; repairs are picked up after the cache expires.
diff --git a/internal/provision/plan9_b8_census_test.go b/internal/provision/plan9_b8_census_test.go
index 48aad3a63..ebcf4407e 100644
--- a/internal/provision/plan9_b8_census_test.go
+++ b/internal/provision/plan9_b8_census_test.go
@@ -366,7 +366,7 @@ func TestPlan9B8RecordWriteCensus(t *testing.T) {
if len(got) < 100 {
t.Fatalf("census found only %d units under %s; the walk is broken", len(got), root)
}
- inventory := regionHASidecarsWriteCensusInventory()
+ inventory := regionHAG3B10WriteCensusInventory()
problems := append(censusDiff(inventory, got), censusPolicy(inventory)...)
if len(problems) > 0 {
t.Fatalf("record-write census rejected %d site(s); update the explicit inventory only after reviewing the source:\n %s", len(problems), strings.Join(problems, "\n "))
diff --git a/internal/provision/region_ha_g3_b10_census_test.go b/internal/provision/region_ha_g3_b10_census_test.go
new file mode 100644
index 000000000..076cab32c
--- /dev/null
+++ b/internal/provision/region_ha_g3_b10_census_test.go
@@ -0,0 +1,31 @@
+package provision
+
+// Record-write census entry for region-ha-g3-b10 (spec §23: born HA only in
+// a named HA pool), layered on regionHASidecarsWriteCensusInventory (main's
+// newest at ddbc0297). No record write is added, moved or reclassified:
+// - Server.attachDomainAs keeps its one CreateRecord. Its HA capacity
+// check now asks haCreate("", "") instead of haRegion(""), so a home
+// region scoped to named pools treats a first route as legacy. The
+// record it writes is unchanged (static, never stamped).
+// - NewServer keeps its key site. It now parses CONSOLE_HA_CAPACITY_CONFIG
+// once into the server's read-only haPools / haScopeInvalid fields. It
+// writes nothing.
+func regionHAG3B10WriteCensusInventory() []censusEntry {
+ entries := append([]censusEntry(nil), regionHASidecarsWriteCensusInventory()...)
+ replacements := []censusEntry{
+ {"internal/console/domainattach.go", "Server.attachDomainAs", "record-writer", "key:CreateRecord", "70d8b7582b91887b6bffbcc969dff5229ca58b97c76d2328f7efcbe46906960c"},
+ {"internal/console/server.go", "NewServer", "key-site", "lit:instances", "584fd507f4fdd6ccf54c78e5b830b58e893597ab4881555b9930a75965d29597"},
+ }
+ for _, r := range replacements {
+ found := false
+ for i, e := range entries {
+ if e.File == r.File && e.Unit == r.Unit {
+ entries[i], found = r, true
+ }
+ }
+ if !found {
+ panic("region-ha-g3-b10 replacement of an unlisted unit " + r.File + ":" + r.Unit)
+ }
+ }
+ return entries
+}