carlos / platform Public

ha: gate new creates on shared capacity evidence

claude agent, operated by paul@keymail.dev b3aeab3274434cc968238d9b8b3043f8b780f9b1 parent 1c509c8
10 files changed, +1,148 −87
  • internal/console/apiinstances.go +125 −83
  • internal/console/apisidecars.go +14 −0
  • internal/console/domainattach.go +12 −0
  • internal/console/ha_born_test.go +2 −0
  • internal/console/hacreate_test.go +3 −0
  • internal/console/hacreatecapacity_test.go +955 −0
  • internal/console/hap2_wiring_test.go +2 −0
  • internal/console/nocapacity.go +31 −3
  • internal/console/rootfs_test.go +1 −0
  • internal/console/testdata/claim-authority-sites.txt +3 −1

CI failed — run details

Intent

Human

<task-notification> <task-id>bchtzf7jn</task-id> <tool-use-id>toolu_019edBvzv6jL8X6ADq1hhxkN</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/de069047-3c6a-40e7-ae66-85194f066976/tasks/bchtzf7jn.output</output-file> <status>completed</status> <summary>Background command "Wait for T2 implementer" completed (exit code 0)</summary> </task-notification>

Attributed to this commit: 13.8 g CO₂e (1,621,753 tokens). This is an attribution, not a measurement — usage counted from this commit's own marker forward to the next one on region-ha-p2b-build, 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/internal/console/apiinstances.go b/internal/console/apiinstances.go
index 8b2910860..117556a22 100644
--- a/internal/console/apiinstances.go
+++ b/internal/console/apiinstances.go
@@ -1834,50 +1834,54 @@ func (s *Server) handleAPIInstanceCreate(w http.ResponseWriter, r *http.Request)
// An APP-DERIVED region needs positive eligibility — the secrets key
// included (R9) — and never rides the dormant gate (codex R2-2).
if regionFrom == "app" {
- snap, err := s.liveEdges(ctx)
- if err != nil {
- log.Printf("console: api instances create %s/%s: read edges: %v", acct.Sqid, app, err)
- jsonError(w, http.StatusServiceUnavailable, msgAppRegionUnconfirmed(s.homeRegionOut(region)))
- return
- }
- // Incomplete evidence for a non-home region is "could not confirm"
- // (C28, the same answer as a failed listing), not C16: the region
- // may well be fine, and a box that could not be read is the one
- // that may not be (re-review r1). The home needs no evidence.
- if region != "" && !snap.EvidenceComplete() {
- log.Printf("console: api instances create %s/%s: incomplete edges or snapshot read, region %s unconfirmed", acct.Sqid, app, region)
- jsonError(w, http.StatusServiceUnavailable, msgAppRegionUnconfirmed(s.homeRegionOut(region)))
- return
- }
- cands := s.regionCands(snap)
- reason := "absent"
- if c, ok := findCandidate(cands, region); ok {
- reason = c.unavailableReason()
- }
- // Region HA (spec 2 §7, H27): the region is judged by the eligible
- // set the create door's chooser will choose from, never by every
- // sibling's own answer, and an empty set is the door's no-room
- // refusal, alert included.
- if x := s.placementChooser(""); x != nil {
- switch boxes, err := x.PlaceableBoxes(ctx, s.cfg.claimPlacementRegion(region)); {
- case errors.Is(err, hostops.ErrContract):
- reason = "absent"
- case err != nil:
- log.Printf("console: api instances create %s/%s: region %s placeable boxes: %v", acct.Sqid, app, region, err)
+ // Active HA eligibility is checked from the shared observation after validation.
+ var cands []regionCandidate
+ if !s.haRegion(region) {
+ snap, err := s.liveEdges(ctx)
+ if err != nil {
+ log.Printf("console: api instances create %s/%s: read edges: %v", acct.Sqid, app, err)
jsonError(w, http.StatusServiceUnavailable, msgAppRegionUnconfirmed(s.homeRegionOut(region)))
return
- case len(boxes) == 0:
- writeClaimResponseError(w, s.noRoom(ctx, region))
+ }
+ // Incomplete evidence for a non-home region is "could not confirm"
+ // (C28, the same answer as a failed listing), not C16: the region
+ // may well be fine, and a box that could not be read is the one
+ // that may not be (re-review r1). The home needs no evidence.
+ if region != "" && !snap.EvidenceComplete() {
+ log.Printf("console: api instances create %s/%s: incomplete edges or snapshot read, region %s unconfirmed", acct.Sqid, app, region)
+ jsonError(w, http.StatusServiceUnavailable, msgAppRegionUnconfirmed(s.homeRegionOut(region)))
+ return
+ }
+ cands = s.regionCands(snap)
+ reason := "absent"
+ if c, ok := findCandidate(cands, region); ok {
+ reason = c.unavailableReason()
+ }
+ // Region HA (spec 2 §7, H27): the region is judged by the eligible
+ // set the create door's chooser will choose from, never by every
+ // sibling's own answer, and an empty set is the door's no-room
+ // refusal, alert included.
+ if x := s.placementChooser(""); x != nil {
+ switch boxes, err := x.PlaceableBoxes(ctx, s.cfg.claimPlacementRegion(region)); {
+ case errors.Is(err, hostops.ErrContract):
+ reason = "absent"
+ case err != nil:
+ log.Printf("console: api instances create %s/%s: region %s placeable boxes: %v", acct.Sqid, app, region, err)
+ jsonError(w, http.StatusServiceUnavailable, msgAppRegionUnconfirmed(s.homeRegionOut(region)))
+ return
+ case len(boxes) == 0:
+ writeClaimResponseError(w, s.noRoom(ctx, region))
+ return
+ default:
+ reason = ""
+ }
+ }
+ // Each list names only what an explicit request for this same
+ // instance would pass (codex plan-R4 2): instanceChoices.
+ if reason != "" {
+ jsonError(w, http.StatusBadRequest, msgAppRegionUnavailable(s.homeRegionOut(region), reason, s.instanceChoices(ctx, m.Regions, cands, region)))
return
- default:
- reason = ""
}
- }
- // Each list names only what an explicit request for this same
- // instance would pass (codex plan-R4 2): instanceChoices.
- if reason != "" {
- jsonError(w, http.StatusBadRequest, msgAppRegionUnavailable(s.homeRegionOut(region), reason, s.instanceChoices(ctx, m.Regions, cands, region)))
- return
}
if !instanceRegionAllowed(m.Regions, region) {
jsonError(w, http.StatusBadRequest, msgAppRegionNotAllowed(s.homeRegionOut(region), s.instanceChoices(ctx, m.Regions, cands, region)))
@@ -1944,57 +1948,67 @@ func (s *Server) handleAPIInstanceCreate(w http.ResponseWriter, r *http.Request)
// hibernation bucket it would never have used. The predicate is
// provision.Record's own (DerivesPaths), asked of a probe record rather
// than restated here, so it cannot drift from what reconcile will mint.
- 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 err := s.roomIn(ctx, region, m.Pool); err != nil {
- writeClaimResponseError(w, err)
- return
- }
- probe := provision.Record{Kind: strings.TrimSpace(req.Kind), Addrs: req.Addrs, Role: probeRec.Role}
- caps, published := s.placementsIn(ctx)
- // The replica placement rides the same gate as the record's own
- // region (#162): a replica named into a placement no box announces
- // is a mirror nothing will ever provision — an order ledger in a
- // region that does not exist. Dormant with the rest of the gate
- // until a box publishes a placement code.
- if published && probe.Role == "replica" {
+ // HA capacity precedes this placement refusal, after the input and permanent rails.
+ // Other regions keep this check at its original position.
+ checkPlacement := func() bool {
+ 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 err := s.roomIn(ctx, region, m.Pool); err != nil {
+ writeClaimResponseError(w, err)
+ return false
+ }
+ }
+ probe := provision.Record{Kind: strings.TrimSpace(req.Kind), Addrs: req.Addrs, Role: probeRec.Role}
+ caps, published := s.placementsIn(ctx)
+ // The replica placement rides the same gate as the record's own
+ // region (#162): a replica named into a placement no box announces
+ // is a mirror nothing will ever provision — an order ledger in a
+ // region that does not exist. Dormant with the rest of the gate
+ // until a box publishes a placement code.
+ if published && probe.Role == "replica" {
+ switch {
+ case !caps[region].Reachable:
+ jsonError(w, http.StatusBadRequest,
+ "replica placement "+region+" is not armed in this deployment — armed: "+armedCodes(reachableSet(caps)))
+ return false
+ case !caps[region].Hosting:
+ jsonError(w, http.StatusBadRequest,
+ "replica placement "+region+" is reachable but cannot host an instance — no box there has its hibernation activator configured. Regions that can: "+armedCodes(hostingSet(caps)))
+ return false
+ }
+ }
switch {
+ case !published:
+ // Dormant: the fleet predates the placement field.
case !caps[region].Reachable:
jsonError(w, http.StatusBadRequest,
- "replica placement "+region+" is not armed in this deployment — armed: "+armedCodes(reachableSet(caps)))
- return
- case !caps[region].Hosting:
+ "region "+region+" is not armed in this deployment — armed: "+armedCodes(reachableSet(caps)))
+ return false
+ case probe.DerivesPaths() && !caps[region].Hosting:
jsonError(w, http.StatusBadRequest,
- "replica placement "+region+" is reachable but cannot host an instance — no box there has its hibernation activator configured. Regions that can: "+armedCodes(hostingSet(caps)))
- return
+ "region "+region+" is reachable but cannot host an instance — no box there has its hibernation activator configured. Regions that can: "+armedCodes(hostingSet(caps)))
+ return false
}
- }
- switch {
- case !published:
- // Dormant: the fleet predates the placement field.
- case !caps[region].Reachable:
- jsonError(w, http.StatusBadRequest,
- "region "+region+" is not armed in this deployment — armed: "+armedCodes(reachableSet(caps)))
- return
- case probe.DerivesPaths() && !caps[region].Hosting:
- jsonError(w, http.StatusBadRequest,
- "region "+region+" is reachable but cannot host an instance — no box there has its hibernation activator configured. Regions that can: "+armedCodes(hostingSet(caps)))
- return
- }
- // R9: a socket-backed instance or a replica needs its config,
- // secrets and store binding rendered on the box, which only a box
- // holding the deployment's secrets key can do. Refused only when a
- // CURRENT writer proves the region keyless; unknown keeps today's
- // behaviour, so roll order never refuses a working region.
- if probe.DerivesPaths() || probe.Role == "replica" {
- if snap, err := s.liveEdges(ctx); err == nil {
- if c, ok := findCandidate(s.regionCands(snap), region); ok && c.NoKeyProven {
- jsonError(w, http.StatusBadRequest, msgNoSecretsKey(s.homeRegionOut(region)))
- return
+ // R9: a socket-backed instance or a replica needs its config,
+ // secrets and store binding rendered on the box, which only a box
+ // holding the deployment's secrets key can do. Refused only when a
+ // CURRENT writer proves the region keyless; unknown keeps today's
+ // behaviour, so roll order never refuses a working region.
+ if probe.DerivesPaths() || probe.Role == "replica" {
+ if snap, err := s.liveEdges(ctx); err == nil {
+ if c, ok := findCandidate(s.regionCands(snap), region); ok && c.NoKeyProven {
+ jsonError(w, http.StatusBadRequest, msgNoSecretsKey(s.homeRegionOut(region)))
+ return false
+ }
}
}
}
+ return true
+ }
+ if !s.haRegion(region) && !checkPlacement() {
+ return
}
channel := strings.TrimSpace(req.Channel)
if channel == "" {
@@ -2263,6 +2277,16 @@ func (s *Server) handleAPIInstanceCreate(w http.ResponseWriter, r *http.Request)
return
}
}
+ // 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 _, _, err := s.readRecord(ctx, acct.Sqid, app, host); err == nil {
+ jsonError(w, http.StatusConflict, "instance "+host+" already exists")
+ return
+ } else if !errors.Is(err, os.ErrNotExist) {
+ jsonError(w, http.StatusBadGateway, "could not create the instance — try again")
+ return
+ }
+ }
// The leftover-replica rail (#199, createleftovers.go): a host still
// holding a deleted instance's replica or move staging is refused, so
// the new record cannot inherit that database. Last of the checks, after
@@ -2303,6 +2327,24 @@ func (s *Server) handleAPIInstanceCreate(w http.ResponseWriter, r *http.Request)
jsonError(w, http.StatusBadGateway, "could not create the instance — try again")
return
}
+ if seeded && s.haRegion(region) {
+ c := seedCreate{rec: rec, placed: placed, m: m, app: app}
+ if ref := seedPlacementRefusal(c); ref != nil {
+ jsonError(w, ref.Status, ref.Msg)
+ return
+ }
+ if req.Import != nil && s.refuseHAImport(w, &rec) {
+ return
+ }
+ }
+ if ref := s.requireHACreateCapacity(ctx, region, rec.Pool); ref != nil {
+ setNoCapacityRetryAfter(w, ref)
+ jsonError(w, ref.Status, ref.Msg)
+ return
+ }
+ if s.haRegion(region) && !checkPlacement() {
+ return
+ }
// Every ordinary check has passed: a seed door takes over from here, and
// writes its own record (apiinstanceseed.go). A seeded or imported record
// is not labelled, and the fleet's lock is let go first, so a long copy
diff --git a/internal/console/apisidecars.go b/internal/console/apisidecars.go
index 427b36c0c..37b351c2f 100644
--- a/internal/console/apisidecars.go
+++ b/internal/console/apisidecars.go
@@ -388,6 +388,15 @@ 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 _, err := provision.GetSidecarRecord(ctx, s.cfg.Releases, acct.Sqid, app, name); err == nil {
+ jsonError(w, http.StatusConflict, "sidecar "+name+" already exists")
+ return
+ } else if !errors.Is(err, os.ErrNotExist) {
+ jsonError(w, http.StatusBadGateway, "could not create the sidecar — try again")
+ return
+ }
+ }
// The leftover-replica rail (#199, createleftovers.go): a sidecar's host
// is derived from its name, so a name reused after a delete lands on the
// deleted sidecar's replica. Refused, after every validation above.
@@ -410,6 +419,11 @@ func (s *Server) handleAPISidecarCreate(w http.ResponseWriter, r *http.Request)
jsonError(w, ref.Status, ref.Msg)
return
}
+ if ref := s.requireHACreateCapacity(ctx, region, rec.Pool); ref != nil {
+ setNoCapacityRetryAfter(w, ref)
+ jsonError(w, ref.Status, ref.Msg)
+ return
+ }
// A fresh budget for the write: validation and the rail's listings may
// have spent most of the original one.
cancel()
diff --git a/internal/console/domainattach.go b/internal/console/domainattach.go
index c436a149f..e12073184 100644
--- a/internal/console/domainattach.go
+++ b/internal/console/domainattach.go
@@ -224,6 +224,18 @@ 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("") {
+ // 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) {
+ return attachResult{}, &doorRefusal{http.StatusBadGateway, "could not create the instance — try again"}
+ }
+ if existing == nil {
+ if ref := s.requireHACreateCapacity(ctx, "", ""); ref != nil {
+ return attachResult{}, ref
+ }
+ }
+ }
if s.cfg.HostClaim {
return s.attachClaimFirstRoute(ctx, acct, app, host, channel, principal)
}
diff --git a/internal/console/ha_born_test.go b/internal/console/ha_born_test.go
index 4dad9729b..733b0d77c 100644
--- a/internal/console/ha_born_test.go
+++ b/internal/console/ha_born_test.go
@@ -89,6 +89,7 @@ func TestSeedsAndSidecarsAreNeverStampedHA(t *testing.T) {
f := newFromFixture(t, 1)
f.fx.srv.cfg.HomeRegion = "ie"
f.fx.srv.cfg.HARegions = []string{"ie"}
+ createCapacityEvidence(t, f.fx.srv, "allow", nil)
rec := f.copy(t, fromBody)
if rec.HA {
t.Fatal("a --from copy was stamped HA")
@@ -104,6 +105,7 @@ func TestSeedsAndSidecarsAreNeverStampedHA(t *testing.T) {
fx, token := instanceFixture(t, "code-ha-sidecar")
fx.srv.cfg.HomeRegion = "ie"
fx.srv.cfg.HARegions = []string{"ie"}
+ createCapacityEvidence(t, fx.srv, "allow", func(m map[string]any) { m["named_pools"] = []string{"tito"} })
m := titoSidecarManifest()
m.Regions = nil
enableSidecars(t, fx, "titogo", m)
diff --git a/internal/console/hacreate_test.go b/internal/console/hacreate_test.go
index 3a1de6bad..5a8ea18e1 100644
--- a/internal/console/hacreate_test.go
+++ b/internal/console/hacreate_test.go
@@ -72,6 +72,7 @@ func haCreateHome(t *testing.T) *leftoverFx {
fx.srv.cfg.HomeRegion = "ie"
fx.srv.cfg.Region = ""
fx.srv.cfg.HARegions = []string{"ie"}
+ createCapacityEvidence(t, fx.srv, "allow", nil)
fx.srv.cfg.SeedData = release.NewDirStore(t.TempDir())
m := titoManifest()
m.Pool = ""
@@ -309,6 +310,7 @@ func TestHACreateAddressBackedSkipsHADataProof(t *testing.T) {
if mode == "remote" {
region = "uk"
}
+ createCapacityEvidence(t, fx.srv, "allow", func(m map[string]any) { m["named_pools"] = []string{"tito"} }, region)
data := &haCreateStore{Store: fx.srv.cfg.SeedData, pageErr: errors.New("must not inspect HA prefix")}
fx.srv.cfg.SeedData = data
code, _, out := haCreatePost(t, fx, fmt.Sprintf(`{"host":"acme.go.tito.io","region":%q,"addrs":["127.0.0.1:8401"]}`, region))
@@ -528,6 +530,7 @@ func TestHACreateLifetimesPrivateStorageRefusal(t *testing.T) {
func haEmptyHomeData(t *testing.T, s *Server) {
t.Helper()
s.cfg.HomeRegion = "ie"
+ createCapacityEvidence(t, s, "allow", nil)
s.cfg.Region = ""
s.cfg.HibernateBucket = "data-test"
s.cfg.SeedData = release.NewDirStore(t.TempDir())
diff --git a/internal/console/hacreatecapacity_test.go b/internal/console/hacreatecapacity_test.go
new file mode 100644
index 000000000..07386f7dd
--- /dev/null
+++ b/internal/console/hacreatecapacity_test.go
@@ -0,0 +1,955 @@
+package console
+
+import (
+ "context"
+ "database/sql"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "html"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "net/url"
+ "path/filepath"
+ "reflect"
+ "strings"
+ "sync"
+ "sync/atomic"
+ "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/hostops"
+ "github.com/carlosframework/platform/internal/provision"
+ "github.com/carlosframework/platform/internal/release"
+)
+
+const capacityUnknownIE = "Capacity evidence for ie is incomplete. Nothing was created. Try again in 60 seconds."
+const capacityPoolIE = "Capacity for pool %s in ie could not be checked. No box confirmed room, and at least one box does not report which pools it serves. Nothing was created. A box serving this pool must report its pool membership before this create can proceed."
+
+// Use the publisher's golden body, real signed identity and status parsers.
+func createCapacityEvidence(t *testing.T, s *Server, evidence string, edit func(map[string]any), regions ...string) *haObserver {
+ t.Helper()
+ o, store, _ := haFixture(t)
+ target := "ie"
+ if len(regions) > 0 {
+ target = regions[0]
+ raw := strings.ReplaceAll(haTestConfig, `"ie"`, fmt.Sprintf("%q", target))
+ c, err := parseHACapacityConfig(raw, []string{target, "de"}, "ie")
+ if err != nil {
+ t.Fatal(err)
+ }
+ o.config = c
+ }
+ now := time.Now().UTC()
+ haPut(t, store, "control/edges/leo.json", haEdit(t, haGolden(t), func(m map[string]any) {
+ m["generation"] = now.Format(time.RFC3339Nano)
+ m["serves_shared_pool"] = true
+ if target != "ie" {
+ m["placement"] = target
+ }
+ if evidence == "zero" {
+ m["admitted"] = false
+ }
+ if evidence == "unknown" {
+ delete(m, "admitted")
+ }
+ if edit != nil {
+ edit(m)
+ }
+ }))
+ haPut(t, store, "status/boxes/leo.json", []byte(fmt.Sprintf(`{"label":"leo","generated_at":%q,"metrics":{"instance_id":"i-0123456789abcdef0"}}`, now.Format(time.RFC3339Nano))))
+ o.current.Store(o.observe(context.Background(), now))
+ s.haCapacity.Store(o)
+ return o
+}
+
+type capacityDoorFixture struct {
+ fx *consoleFixture
+ token string
+ browser *http.Client
+ csrf string
+ claims *claimCase
+}
+
+func capacityFixture(t *testing.T, mode string) capacityDoorFixture {
+ t.Helper()
+ var clock *lifetimesClock
+ if mode == "lifetimes" {
+ clock = useLifetimesClock(t)
+ }
+ var f capacityDoorFixture
+ if mode == "claims" {
+ cx := newClaimCaseWith(t, func(c *Config) { c.HomeRegion = "ie" })
+ f = capacityDoorFixture{cx.consoleFixture, cx.bearer, cx.browser, cx.csrf, cx}
+ } else {
+ fx := newConsoleFixture(t)
+ if _, err := fx.st.CreateAppIn(OpsAccountID, "titogo", "paul@keymail.dev", time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ browser := newBrowser(t)
+ signUp(t, fx, browser, "capacity-"+claimSafeName(t.Name()))
+ f = capacityDoorFixture{fx: fx, token: cliToken(t, fx, "paul@keymail.dev", "capacity-token"), browser: browser, csrf: sessionToken(t, fx, browser)}
+ if mode == "lifetimes" {
+ turnLifetimesOn(t, fx.srv, clock)
+ }
+ }
+ if err := f.fx.st.SetOperator("paul@keymail.dev", true); err != nil {
+ t.Fatal(err)
+ }
+ f.fx.srv.cfg.HomeRegion = "ie"
+ f.fx.srv.cfg.HARegions = []string{"ie"}
+ f.fx.srv.cfg.SeedData = release.NewDirStore(t.TempDir())
+ f.fx.srv.cfg.HibernateBucket = "test-data"
+ root := t.TempDir()
+ f.fx.srv.dbReplica = func(_ context.Context, prefix string) (replicaReader, error) {
+ return lsfile.NewReplicaClient(filepath.Join(root, prefix)), nil
+ }
+ m := titoManifest()
+ m.Pool = ""
+ m.Regions = nil
+ enableInstances(t, f.fx, "titogo", m)
+ sm := titoSidecarManifest()
+ sm.Pool = ""
+ sm.Regions = nil
+ enableSidecars(t, f.fx, "titogo", sm)
+ shipVersion(t, f.fx, "titogo", "v1")
+ seedChannel(t, f.fx, "titogo", "edge", "v1")
+ return f
+}
+
+func (f capacityDoorFixture) request(t *testing.T, door string) (int, http.Header, string) {
+ t.Helper()
+ path, body := "/api/cli/apps/bab/titogo/instances", `{"host":"capacity.go.tito.io","kind":"static"}`
+ switch door {
+ case "binary":
+ body = `{"host":"capacity.go.tito.io"}`
+ case "address":
+ body = `{"host":"capacity.go.tito.io","addrs":["127.0.0.1:8080"]}`
+ case "sidecar":
+ path, body = "/api/cli/apps/bab/titogo/sidecars", `{"name":"capacity"}`
+ case "domain", "browser":
+ path, body = "/api/cli/apps/bab/titogo/domains", `{"host":"capacity.example.com","kind":"static","channel":"edge"}`
+ }
+ if door != "browser" {
+ return rawReq(t, http.MethodPost, f.fx.ts.URL+path, f.token, body)
+ }
+ req, err := http.NewRequest(http.MethodPost, f.fx.ts.URL+"/a/bab/apps/titogo/domains/attach", strings.NewReader(url.Values{"csrf": {f.csrf}, "host": {"capacity.example.com"}, "kind": {"static"}, "channel": {"edge"}}.Encode()))
+ if err != nil {
+ t.Fatal(err)
+ }
+ req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+ resp, err := f.browser.Do(req)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer resp.Body.Close()
+ b, err := io.ReadAll(resp.Body)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return resp.StatusCode, resp.Header, html.UnescapeString(string(b))
+}
+
+func TestHACreateCapacityDoors(t *testing.T) {
+ for _, mode := range []string{"plain", "lifetimes", "claims"} {
+ for _, door := range []string{"instance", "binary", "address", "sidecar", "domain", "browser"} {
+ for _, evidence := range []string{"allow", "zero", "unknown"} {
+ t.Run(mode+"/"+door+"/"+evidence, func(t *testing.T) {
+ pages := pagesTo(t)
+ f := capacityFixture(t, mode)
+ createCapacityEvidence(t, f.fx.srv, evidence, nil)
+ control := &haCreateStore{Store: f.fx.srv.cfg.Releases}
+ data := &haCreateStore{Store: f.fx.srv.cfg.SeedData}
+ f.fx.srv.cfg.Releases, f.fx.srv.cfg.SeedData = control, data
+ local := capacityLocalWrites(t, f.fx)
+ mark := 0
+ if f.claims != nil {
+ mark = f.claims.rec.mark()
+ }
+ before := bucketState(t, f.fx.rel)
+ code, hdr, body := f.request(t, door)
+ if evidence == "allow" {
+ if code < 200 || code >= 400 {
+ t.Fatalf("allow: %d %s", code, body)
+ }
+ if door == "sidecar" {
+ rec, err := provision.GetSidecarRecord(context.Background(), f.fx.rel, "bab", "titogo", "capacity")
+ if err != nil {
+ t.Fatal(err)
+ }
+ b, _ := json.Marshal(rec)
+ if strings.Contains(string(b), `"ha":true`) {
+ t.Fatal("sidecar stamped HA")
+ }
+ }
+ return
+ }
+ want := capacityUnknownIE
+ if evidence == "zero" {
+ want = noCapacityRefusal("ie")
+ }
+ if code != 503 || hdr.Get("Retry-After") != "60" || !strings.Contains(body, want) {
+ t.Fatalf("%d Retry-After=%q %s; want %q", code, hdr.Get("Retry-After"), body, want)
+ }
+ haCreateNoWrites(t, control, data)
+ if f.claims != nil {
+ wroteNothing(t, f.claims, mark)
+ }
+ local()
+ if after := bucketState(t, f.fx.rel); !reflect.DeepEqual(before, after) {
+ t.Fatal("refusal changed bucket")
+ }
+ if evidence == "zero" {
+ expectPages(t, pages, noRoomSubject("ie"))
+ } else {
+ expectPages(t, pages)
+ }
+ })
+ }
+ }
+ }
+}
+
+// SQLite triggers count attempts even if a later statement restores the row.
+// Authentication bookkeeping is outside the protected create state.
+func capacityLocalWrites(t *testing.T, fx *consoleFixture) func() {
+ t.Helper()
+ install := func(db sqlHandle, tables []string) func() int {
+ if _, err := db.Exec(`CREATE TABLE capacity_write_probe (event TEXT)`); err != nil {
+ t.Fatal(err)
+ }
+ for _, table := range tables {
+ for _, verb := range []string{"INSERT", "UPDATE", "DELETE"} {
+ q := fmt.Sprintf(`CREATE TRIGGER "capacity_%s_%s" AFTER %s ON "%s" BEGIN INSERT INTO capacity_write_probe VALUES ('%s %s'); END`, table, verb, verb, table, verb, table)
+ if _, err := db.Exec(q); err != nil {
+ t.Fatal(err)
+ }
+ }
+ }
+ return func() int {
+ var n int
+ if err := db.QueryRow(`SELECT COUNT(*) FROM capacity_write_probe`).Scan(&n); err != nil {
+ t.Fatal(err)
+ }
+ return n
+ }
+ }
+ localDB := fx.st.rawPool
+ if fx.st.gate != nil {
+ var err error
+ localDB, err = sql.Open("sqlite", fx.st.gate.path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { localDB.Close() })
+ }
+ local := install(localDB, []string{"audit", "apps", "host_allocations", "record_retirements", "record_migrations"})
+ reg, err := sql.Open("sqlite", fx.regPath)
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { reg.Close() })
+ rows, err := reg.Query(`SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'`)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var tables []string
+ for rows.Next() {
+ var name string
+ if err := rows.Scan(&name); err != nil {
+ t.Fatal(err)
+ }
+ tables = append(tables, name)
+ }
+ if err := rows.Close(); err != nil {
+ t.Fatal(err)
+ }
+ registry := install(reg, tables)
+ return func() {
+ t.Helper()
+ if a, b := local(), registry(); a != 0 || b != 0 {
+ t.Fatalf("local writes: console=%d registry=%d", a, b)
+ }
+ }
+}
+
+func TestHACreateCapacityNamedPools(t *testing.T) {
+ for _, door := range []string{"instance", "sidecar"} {
+ for _, pool := range []string{"hapair", "cohort1"} {
+ for _, scenario := range []string{"new", "old", "null", "mixed-positive", "mixed-missing", "absent-membership", "closed-inbound", "malformed"} {
+ t.Run(door+"/"+pool+"/"+scenario, func(t *testing.T) {
+ pages := pagesTo(t)
+ f := capacityFixture(t, "plain")
+ m := titoManifest()
+ m.Pool = pool
+ m.Regions = nil
+ enableInstances(t, f.fx, "titogo", m)
+ sm := titoSidecarManifest()
+ sm.Pool = pool
+ sm.Regions = nil
+ enableSidecars(t, f.fx, "titogo", sm)
+ o := createCapacityEvidence(t, f.fx.srv, "allow", func(m map[string]any) {
+ switch scenario {
+ case "old":
+ delete(m, "named_pools")
+ case "mixed-missing":
+ m["named_pools"] = []string{"other"}
+ case "null":
+ m["named_pools"] = nil
+ case "absent-membership":
+ m["named_pools"] = []string{"other"}
+ case "closed-inbound":
+ m["accepts_inbound"] = false
+ case "malformed":
+ m["named_pools"] = 17
+ }
+ })
+ if strings.HasPrefix(scenario, "mixed-") {
+ // An otherwise eligible older publisher shares the same trust checks.
+ c := *o.config
+ c.FixedBoxes = make(map[string]haFixedBox)
+ for k, v := range o.config.FixedBoxes {
+ c.FixedBoxes[k] = v
+ }
+ c.FixedBoxes["sophie"] = haFixedBox{RegionCode: "ie", InstanceID: "i-0123456789abcdef1"}
+ o.config = &c
+ signer := boxidtest.NewSigner(t)
+ o.verifier.Certs = signer.Certs()
+ for _, pair := range []struct{ ref, iid string }{{"leo", "i-0123456789abcdef0"}, {"sophie", "i-0123456789abcdef1"}} {
+ rec, _ := signer.Record(t, pair.ref, moveTestAccount, "eu-west-1", pair.iid)
+ b, _ := json.Marshal(rec)
+ haPut(t, o.store.(*haCapacityStore).Store, boxid.Key(pair.ref), b)
+ }
+ now := time.Now().UTC()
+ haPut(t, o.store, "control/edges/sophie.json", haEdit(t, haGolden(t), func(m map[string]any) {
+ m["box"] = "sophie"
+ m["box_id"] = "sophie"
+ m["generation"] = now.Format(time.RFC3339Nano)
+ delete(m, "named_pools")
+ }))
+ haPut(t, o.store, "status/boxes/sophie.json", []byte(fmt.Sprintf(`{"label":"sophie","generated_at":%q,"metrics":{"instance_id":"i-0123456789abcdef1"}}`, now.Format(time.RFC3339Nano))))
+ o.current.Store(o.observe(context.Background(), now))
+ }
+ control := &haCreateStore{Store: f.fx.srv.cfg.Releases}
+ f.fx.srv.cfg.Releases = control
+ local := capacityLocalWrites(t, f.fx)
+ code, hdr, body := f.request(t, door)
+ switch scenario {
+ case "new", "mixed-positive":
+ if code != 201 {
+ t.Fatalf("positive: %d %s", code, body)
+ }
+ default:
+ want := noCapacityRefusal("ie")
+ if scenario == "old" || scenario == "null" || scenario == "mixed-missing" {
+ want = fmt.Sprintf(capacityPoolIE, pool)
+ }
+ if scenario == "malformed" {
+ want = capacityUnknownIE
+ }
+ if code != 503 || hdr.Get("Retry-After") != "60" || errorText(body) != want {
+ t.Fatalf("%d %s %s", code, hdr.Get("Retry-After"), body)
+ }
+ if n, _ := control.counts(); n != 0 {
+ t.Fatalf("writes=%d", n)
+ }
+ local()
+ if scenario == "absent-membership" || scenario == "closed-inbound" {
+ expectPages(t, pages, noRoomSubject("ie"))
+ } else {
+ expectPages(t, pages)
+ }
+ }
+ pub := &capacityRecorder{}
+ _ = f.fx.srv.publishCapacity(context.Background(), pub)
+ for _, v := range pub.got {
+ if v.Placement == "ie" && v.Eligible == 0 {
+ t.Fatal("pool evidence produced regional zero")
+ }
+ }
+ })
+ }
+ }
+ }
+}
+
+func TestHACreateCapacityBeforeSeedAndPrivateStorage(t *testing.T) {
+ for _, lifetimes := range []bool{false, true} {
+ for _, seeded := range []bool{false, true} {
+ for _, evidence := range []string{"allow", "zero", "unknown"} {
+ t.Run(fmt.Sprintf("lifetimes=%v/from=%v/%s", lifetimes, seeded, evidence), func(t *testing.T) {
+ pages := pagesTo(t)
+ clock := useLifetimesClock(t)
+ f := newFromFixture(t, 1)
+ if lifetimes {
+ turnLifetimesOn(t, f.fx.srv, clock)
+ }
+ f.fx.srv.cfg.HomeRegion = "ie"
+ f.fx.srv.cfg.HARegions = []string{"ie"}
+ enableInstances(t, f.fx, "shop", fromManifest(true))
+ createCapacityEvidence(t, f.fx.srv, evidence, nil)
+ var adapterCalls atomic.Int64
+ adapter, err := NewStoreProvisionerBoundary(f.fake, func(context.Context, hostops.MutationTarget) error { adapterCalls.Add(1); return nil })
+ if err != nil {
+ t.Fatal(err)
+ }
+ f.fx.srv.cfg.StoreProvisioner = adapter
+ control := &haCreateStore{Store: f.fx.srv.cfg.Releases}
+ data := &haCreateStore{Store: f.fx.srv.cfg.SeedData}
+ f.fx.srv.cfg.Releases, f.fx.srv.cfg.SeedData = control, data
+ local := capacityLocalWrites(t, f.fx)
+ before := bucketState(t, f.fx.rel)
+ body := `{"host":"` + fromHost + `"}`
+ if seeded {
+ body = `{"host":"` + fromHost + `","from":{"host":"` + fromSource + `"}}`
+ }
+ code, hdr, out := rawReq(t, http.MethodPost, f.url, f.token, body)
+ f.fx.srv.seedCopies.Wait()
+ if evidence == "allow" {
+ want := 201
+ if seeded {
+ want = 202
+ }
+ if code != want {
+ t.Fatalf("allow=%d %s", code, out)
+ }
+ if adapterCalls.Load() == 0 {
+ t.Fatal("positive control never reached storage adapter")
+ }
+ return
+ }
+ want := capacityUnknownIE
+ if evidence == "zero" {
+ want = noCapacityRefusal("ie")
+ }
+ if code != 503 || hdr.Get("Retry-After") != "60" || errorText(out) != want {
+ t.Fatalf("%d %v %s", code, hdr, out)
+ }
+ haCreateNoWrites(t, control, data)
+ local()
+ if adapterCalls.Load() != 0 {
+ t.Fatal("refusal reached storage adapter")
+ }
+ if !reflect.DeepEqual(before, bucketState(t, f.fx.rel)) {
+ t.Fatal("refusal changed stored state")
+ }
+ if evidence == "zero" {
+ expectPages(t, pages, noRoomSubject("ie"))
+ } else {
+ expectPages(t, pages)
+ }
+ })
+ }
+ }
+ }
+}
+
+func TestHACreateCapacityResidentRootfs(t *testing.T) {
+ for _, evidence := range []string{"allow", "zero", "unknown"} {
+ t.Run(evidence, func(t *testing.T) {
+ pages := pagesTo(t)
+ fx, token := unplacedRootfsApp(t)
+ fx.srv.cfg.DeploymentSingleTenant = true
+ fx.srv.cfg.HomeRegion = "ie"
+ fx.srv.cfg.HARegions = []string{"ie"}
+ writeFleetBox(t, fx, "", "box-1", "ie", true, time.Now())
+ createCapacityEvidence(t, fx.srv, evidence, nil)
+ control := &haCreateStore{Store: fx.srv.cfg.Releases}
+ fx.srv.cfg.Releases = control
+ local := capacityLocalWrites(t, fx)
+ code, hdr, out := rawReq(t, http.MethodPost, instancesURL(fx, fx.sqid, "shop"), token, `{"host":"shop.example.com"}`)
+ if evidence == "allow" {
+ if code != 201 {
+ t.Fatalf("%d %s", code, out)
+ }
+ rec, _ := storedShop(t, fx, rootfsShopHost)
+ if rec.Runtime != provision.RuntimeRootfsV1 || rec.HA {
+ t.Fatalf("record=%+v", rec)
+ }
+ return
+ }
+ want := capacityUnknownIE
+ if evidence == "zero" {
+ want = noCapacityRefusal("ie")
+ }
+ if code != 503 || hdr.Get("Retry-After") != "60" || errorText(out) != want {
+ t.Fatalf("%d %v %s", code, hdr, out)
+ }
+ if n, _ := control.counts(); n != 0 {
+ t.Fatalf("writes=%d", n)
+ }
+ local()
+ if evidence == "zero" {
+ expectPages(t, pages, noRoomSubject("ie"))
+ } else {
+ expectPages(t, pages)
+ }
+ })
+ }
+}
+
+type createCapacityReads struct {
+ release.Store
+ metadata haMetadataLister
+ reads atomic.Int64
+}
+
+func (s *createCapacityReads) Get(ctx context.Context, k string) ([]byte, string, error) {
+ s.reads.Add(1)
+ return s.Store.Get(ctx, k)
+}
+func (s *createCapacityReads) ListPage(ctx context.Context, p, a string, n int) ([]string, error) {
+ s.reads.Add(1)
+ return s.Store.(release.PageLister).ListPage(ctx, p, a, n)
+}
+func (s *createCapacityReads) haListStatus(ctx context.Context) ([]haObject, bool, error) {
+ s.reads.Add(1)
+ return s.metadata.haListStatus(ctx)
+}
+
+func TestHACreateCapacitySharesObservation(t *testing.T) {
+ pages := pagesTo(t)
+ f := capacityFixture(t, "plain")
+ o, st, _ := haFixture(t)
+ haPut(t, st, "control/edges/leo.json", haEdit(t, haGolden(t), func(m map[string]any) { m["admitted"] = false }))
+ counted := &createCapacityReads{Store: o.store, metadata: o.store.(haMetadataLister)}
+ o.store = counted
+ o.clock = newHATestClock()
+ f.fx.srv.haCapacity.Store(o)
+ ctx, cancel := context.WithCancel(context.Background())
+ done := o.start(ctx)
+ defer func() { cancel(); haAwait(t, done) }()
+ haAwait(t, o.ready)
+ before := counted.reads.Load()
+ obs, _ := f.fx.srv.HACapacity()
+ if before != 5 {
+ t.Fatalf("observation reads=%d, want 2 LIST + 3 GET", before)
+ }
+ transport := hap2S3(t, f.fx)
+ var wg sync.WaitGroup
+ for _, door := range []string{"instance", "sidecar", "domain"} {
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ code, hdr, body := f.request(t, door)
+ if code != 503 || hdr.Get("Retry-After") != "60" || errorText(body) != noCapacityRefusal("ie") {
+ t.Errorf("%s: %d %s", door, code, body)
+ }
+ }()
+ }
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ pub := &capacityRecorder{}
+ if err := f.fx.srv.publishCapacity(context.Background(), pub); err != nil {
+ t.Error(err)
+ }
+ }()
+ wg.Wait()
+ after, _ := f.fx.srv.HACapacity()
+ if counted.reads.Load() != before || after != obs {
+ t.Fatal("requests refreshed the shared observation")
+ }
+ // Existing validation across these doors lists edges and status twice.
+ // Capacity adds no reads through either the observation or request client.
+ evidenceLists := map[string]int{}
+ for _, attempt := range transport.all() {
+ for _, prefix := range []string{"control/edges/", "control/boxes/", "status/boxes/"} {
+ if attempt.query.Get("prefix") == prefix {
+ evidenceLists[prefix]++
+ }
+ if strings.HasPrefix(attempt.key, prefix) {
+ t.Errorf("request loaded capacity evidence body: %+v", attempt)
+ }
+ }
+ }
+ if !reflect.DeepEqual(evidenceLists, map[string]int{"control/edges/": 2, "status/boxes/": 2}) {
+ t.Fatalf("evidence LISTs=%v, want existing validation's two per prefix", evidenceLists)
+ }
+ transport.noWrites(t)
+ expectPages(t, pages, noRoomSubject("ie"))
+}
+
+func TestHACreateCapacityPageThrottle(t *testing.T) {
+ f := capacityFixture(t, "plain")
+ createCapacityEvidence(t, f.fx.srv, "zero", nil)
+ old := pageNoCapacity
+ var calls atomic.Int64
+ entered := make(chan struct{}, 4)
+ releaseSend := make(chan struct{})
+ var releaseOnce sync.Once
+ release := func() { releaseOnce.Do(func() { close(releaseSend) }) }
+ defer release()
+ pageNoCapacity = func(context.Context, string, string, string) error {
+ n := calls.Add(1)
+ entered <- struct{}{}
+ if n == 1 {
+ <-releaseSend
+ return errors.New("test send failure")
+ }
+ return nil
+ }
+ defer func() { pageNoCapacity = old }()
+ request := func() {
+ code, _, body := f.request(t, "instance")
+ if code != 503 {
+ t.Errorf("%d %s", code, body)
+ }
+ }
+ request()
+ haAwait(t, entered)
+ var wg sync.WaitGroup
+ for range 8 {
+ wg.Add(1)
+ go func() { defer wg.Done(); request() }()
+ }
+ wg.Wait()
+ if calls.Load() != 1 {
+ t.Fatal("concurrent refusals sent extra pages")
+ }
+ release()
+ haWait(t, func() bool {
+ f.fx.srv.noCapacity.mu.Lock()
+ defer f.fx.srv.noCapacity.mu.Unlock()
+ return len(f.fx.srv.noCapacity.last) == 0
+ })
+ request()
+ haAwait(t, entered)
+ for range 3 {
+ request()
+ }
+ if calls.Load() != 2 {
+ t.Fatal("successful send did not suppress repeats")
+ }
+ // A fresh server is a process restart: the hourly reservation is in memory.
+ restarted, err := NewServer(f.fx.srv.cfg, f.fx.st)
+ if err != nil {
+ t.Fatal(err)
+ }
+ restarted.dbReplica = f.fx.srv.dbReplica
+ restarted.haCapacity.Store(f.fx.srv.haCapacity.Load())
+ req := httptest.NewRequest(http.MethodPost, "/api/cli/apps/bab/titogo/instances", strings.NewReader(`{"host":"capacity.go.tito.io","kind":"static"}`))
+ req.Header.Set("Authorization", "Bearer "+f.token)
+ req.Header.Set("Content-Type", "application/json")
+ w := httptest.NewRecorder()
+ restarted.ServeHTTP(w, req)
+ if w.Code != 503 {
+ t.Fatalf("restart: %d %s", w.Code, w.Body)
+ }
+ haAwait(t, entered)
+ if calls.Load() != 3 {
+ t.Fatalf("restart sends=%d", calls.Load())
+ }
+}
+
+func TestHACapacityDoesNotGateExistingWake(t *testing.T) {
+ for _, evidence := range []string{"zero", "unknown"} {
+ t.Run(evidence, func(t *testing.T) {
+ pages := pagesTo(t)
+ fx := newConsoleFixture(t)
+ const host = "web.kass.carlosapp.dev"
+ sibling(t, fx, "kass", host, "edge")
+ markHA(t, fx.rel, "bab", "kass", host)
+ token := cliToken(t, fx, "paul@keymail.dev", "capacity-existing")
+ fx.srv.cfg.AppsDomain = "carlosapp.dev"
+ fx.srv.cfg.HomeRegion = "ie"
+ fx.srv.cfg.HARegions = []string{"ie"}
+ createCapacityEvidence(t, fx.srv, evidence, nil)
+ writeHeldBox(t, fx, host, "kass", "v2")
+ for _, door := range []struct{ name, method, path, body string }{
+ {"enable", http.MethodPut, "/instances-manifest", `{}`},
+ {"restart", http.MethodPost, "/restart", `{}`},
+ {"deploy promote", http.MethodPost, "/promote", `{"channel":"edge","version":"v2","hotfix":true}`},
+ {"retry", http.MethodPost, "/instances/" + host + "/retry", `{}`},
+ {"alias", http.MethodPost, "/domains", `{"host":"capacity-alias.example.com"}`},
+ } {
+ code, _, out := rawReq(t, door.method, fx.ts.URL+"/api/cli/apps/bab/kass"+door.path, token, door.body)
+ if code < 200 || code >= 300 {
+ t.Fatalf("%s: %d %s", door.name, code, out)
+ }
+ }
+ expectPages(t, pages)
+ })
+ }
+}
+
+func TestHACreateCapacityPrecedence(t *testing.T) {
+ for _, evidence := range []string{"zero", "unknown"} {
+ for _, scenario := range []string{"auth", "duplicate-instance", "duplicate-sidecar", "shape", "invalid-channel", "import", "pooled-data", "nonhome-data", "nonhome-static", "app-home", "explicit-home", "outside-ha"} {
+ t.Run(evidence+"/"+scenario, func(t *testing.T) {
+ pages := pagesTo(t)
+ f := capacityFixture(t, "plain")
+ createCapacityEvidence(t, f.fx.srv, evidence, nil)
+ f.fx.srv.cfg.HARegions = []string{"ie", "de"}
+ path, body, token := "/api/cli/apps/bab/titogo/instances", `{"host":"capacity.go.tito.io","kind":"static"}`, f.token
+ want := 503
+ switch scenario {
+ case "auth":
+ token = cliToken(t, f.fx, "stranger@example.com", "capacity-stranger")
+ want = 404
+ case "duplicate-instance":
+ haPut(t, f.fx.rel, provision.RecordKey("bab", "titogo", "capacity.go.tito.io"), []byte(`{"schema":1,"host":"capacity.go.tito.io","app":"titogo","account":"bab","channel":"stable","kind":"static","created_at":"2026-11-01T00:00:00Z"}`))
+ want = 409
+ case "duplicate-sidecar":
+ rec := provision.SidecarRecord{Schema: 1, Name: "capacity", Host: provision.SidecarHost("capacity", "titogo", "bab"), Account: "bab", App: "titogo", Channel: "stable", CreatedAt: time.Now().UTC()}
+ if err := provision.CreateSidecarRecord(context.Background(), f.fx.rel, rec); err != nil {
+ t.Fatal(err)
+ }
+ path, body = "/api/cli/apps/bab/titogo/sidecars", `{"name":"capacity"}`
+ want = 409
+ case "shape":
+ body = `{"host":"capacity.go.tito.io","region":"de","kind":"not-a-kind"}`
+ want = 400
+ case "invalid-channel":
+ body = `{"host":"capacity.go.tito.io","region":"de","kind":"static","channel":"!"}`
+ want = 400
+ case "import":
+ body = `{"host":"capacity.go.tito.io","import":{}}`
+ want = 409
+ case "pooled-data":
+ m := titoManifest()
+ m.Pool = "hapair"
+ m.Regions = nil
+ enableInstances(t, f.fx, "titogo", m)
+ body = `{"host":"capacity.go.tito.io"}`
+ want = 409
+ case "nonhome-data":
+ body = `{"host":"capacity.go.tito.io","region":"de"}`
+ want = 409
+ case "nonhome-static":
+ body = `{"host":"capacity.go.tito.io","region":"de","kind":"static"}`
+ case "app-home":
+ body = `{"host":"capacity.go.tito.io"}`
+ f.fx.srv.appRegionOf = func(int64, string) (string, string, error) { return "ie", "app", nil }
+ case "explicit-home":
+ body = `{"host":"capacity.go.tito.io","region":"ie","kind":"static"}`
+ case "outside-ha":
+ f.fx.srv.cfg.HARegions = []string{"de"}
+ want = 201
+ }
+ control := &haCreateStore{Store: f.fx.srv.cfg.Releases}
+ data := &haCreateStore{Store: f.fx.srv.cfg.SeedData}
+ f.fx.srv.cfg.Releases, f.fx.srv.cfg.SeedData = control, data
+ local := capacityLocalWrites(t, f.fx)
+ code, hdr, out := rawReq(t, http.MethodPost, f.fx.ts.URL+path, token, body)
+ if code != want {
+ t.Fatalf("%d %s, want %d", code, out, want)
+ }
+ if code == 201 {
+ return
+ }
+ haCreateNoWrites(t, control, data)
+ local()
+ if want != 503 {
+ if hdr.Get("Retry-After") != "" || strings.Contains(out, "Nothing was created.") {
+ t.Fatalf("capacity masked validation: %v %s", hdr, out)
+ }
+ expectPages(t, pages)
+ return
+ }
+ region := "ie"
+ if scenario == "nonhome-static" {
+ region = "de"
+ }
+ // The configured de region has a complete empty census.
+ zero := evidence == "zero" || region == "de"
+ msg := fmt.Sprintf(haCapacityUnknownRefusal, region)
+ if zero {
+ msg = noCapacityRefusal(region)
+ }
+ if hdr.Get("Retry-After") != "60" || errorText(out) != msg {
+ t.Fatalf("%v %s", hdr, out)
+ }
+ if zero {
+ expectPages(t, pages, noRoomSubject(region))
+ } else {
+ expectPages(t, pages)
+ }
+ })
+ }
+ }
+}
+
+func TestHACreateCapacityPendingProof(t *testing.T) {
+ for _, mode := range []string{"plain", "lifetimes", "claims"} {
+ for _, door := range []string{"domain", "browser"} {
+ for _, evidence := range []string{"allow", "zero", "unknown"} {
+ t.Run(mode+"/"+door+"/"+evidence, func(t *testing.T) {
+ pages := pagesTo(t)
+ f := capacityFixture(t, mode)
+ f.fx.srv.cfg.DomainProof = true
+ f.fx.srv.lookupTXT = func(context.Context, string) ([]string, error) { return nil, errors.New("no proof") }
+ createCapacityEvidence(t, f.fx.srv, evidence, nil)
+ control := &haCreateStore{Store: f.fx.srv.cfg.Releases}
+ f.fx.srv.cfg.Releases = control
+ local := capacityLocalWrites(t, f.fx)
+ mark := 0
+ if f.claims != nil {
+ mark = f.claims.rec.mark()
+ }
+ code, hdr, out := f.request(t, door)
+ if evidence == "allow" {
+ // Claims requires proof up front; the legacy arms can store pending proof.
+ if mode == "claims" {
+ if code != 409 || !strings.Contains(out, "prove you control this hostname") {
+ t.Fatalf("proof refusal: %d %s", code, out)
+ }
+ } else if code < 200 || code >= 400 {
+ t.Fatalf("pending: %d %s", code, out)
+ }
+ return
+ }
+ want := capacityUnknownIE
+ if evidence == "zero" {
+ want = noCapacityRefusal("ie")
+ }
+ if code != 503 || hdr.Get("Retry-After") != "60" || !strings.Contains(out, want) {
+ t.Fatalf("%d %v %s", code, hdr, out)
+ }
+ if n, _ := control.counts(); n != 0 {
+ t.Fatalf("pending proof writes=%d", n)
+ }
+ if f.claims != nil {
+ wroteNothing(t, f.claims, mark)
+ }
+ local()
+ if evidence == "zero" {
+ expectPages(t, pages, noRoomSubject("ie"))
+ } else {
+ expectPages(t, pages)
+ }
+ })
+ }
+ }
+ }
+}
+
+func TestHACreateCapacityBeforeEnvironmentBinding(t *testing.T) {
+ for _, evidence := range []string{"allow", "zero", "unknown"} {
+ t.Run(evidence, func(t *testing.T) {
+ pages := pagesTo(t)
+ f := capacityFixture(t, "plain")
+ key, before := putSeedStore(t, &claimCase{consoleFixture: f.fx})
+ createCapacityEvidence(t, f.fx.srv, evidence, nil)
+ control := &haCreateStore{Store: f.fx.srv.cfg.Releases}
+ f.fx.srv.cfg.Releases = control
+ local := capacityLocalWrites(t, f.fx)
+ code, _, out := rawReq(t, http.MethodPost, instancesURL(f.fx, "bab", "titogo"), f.token, `{"host":"capacity.go.tito.io","environment":"canary"}`)
+ after, _, err := f.fx.rel.Get(context.Background(), key)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if evidence == "allow" {
+ if code != 201 || string(before) == string(after) {
+ t.Fatalf("binding not exercised: %d %s", code, out)
+ }
+ return
+ }
+ if code != 503 || string(before) != string(after) {
+ t.Fatalf("refusal bound environment: %d %s", code, out)
+ }
+ if n, _ := control.counts(); n != 0 {
+ t.Fatalf("writes=%d", n)
+ }
+ local()
+ if evidence == "zero" {
+ expectPages(t, pages, noRoomSubject("ie"))
+ } else {
+ expectPages(t, pages)
+ }
+ })
+ }
+}
+
+func TestHACreateCapacityUnavailableObservation(t *testing.T) {
+ for _, scenario := range []string{"not-started", "expired", "failed"} {
+ t.Run(scenario, func(t *testing.T) {
+ pages := pagesTo(t)
+ f := capacityFixture(t, "plain")
+ if scenario != "not-started" {
+ o := createCapacityEvidence(t, f.fx.srv, "allow", nil)
+ if scenario == "expired" {
+ o.current.Store(o.observe(context.Background(), time.Now().Add(-120*time.Second)))
+ } else {
+ o.store = &haControlledStore{Store: o.store, metadata: o.store.(haMetadataLister), failAt: 1}
+ o.current.Store(o.observe(context.Background(), time.Now()))
+ }
+ }
+ code, hdr, out := f.request(t, "instance")
+ if code != 503 || hdr.Get("Retry-After") != "60" || errorText(out) != capacityUnknownIE {
+ t.Fatalf("%d %v %s", code, hdr, out)
+ }
+ expectPages(t, pages)
+ })
+ }
+}
+
+func TestHACreateCapacityClaimsPrivate(t *testing.T) {
+ for _, evidence := range []string{"allow", "zero", "unknown"} {
+ t.Run(evidence, func(t *testing.T) {
+ pages := pagesTo(t)
+ f := capacityFixture(t, "claims")
+ approveStoreAccount(t, f.fx, "operator@keymail.dev")
+ m := titoManifest()
+ m.Regions = nil
+ m.Pool = ""
+ m.PrivateStorage = true
+ enableInstances(t, f.fx, "titogo", m)
+ createCapacityEvidence(t, f.fx.srv, evidence, nil)
+ control := &haCreateStore{Store: f.fx.srv.cfg.Releases}
+ f.fx.srv.cfg.Releases = control
+ local := capacityLocalWrites(t, f.fx)
+ mark := f.claims.rec.mark()
+ code, _, out := f.request(t, "binary")
+ if evidence == "allow" {
+ if code != 201 && code != 202 {
+ t.Fatalf("%d %s", code, out)
+ }
+ return
+ }
+ if code != 503 {
+ t.Fatalf("%d %s", code, out)
+ }
+ if n, _ := control.counts(); n != 0 {
+ t.Fatalf("writes=%d", n)
+ }
+ local()
+ wroteNothing(t, f.claims, mark)
+ if evidence == "zero" {
+ expectPages(t, pages, noRoomSubject("ie"))
+ } else {
+ expectPages(t, pages)
+ }
+ })
+ }
+}
+
+func TestHACreateCapacityReattachExistingFirstRoute(t *testing.T) {
+ for _, evidence := range []string{"zero", "unknown"} {
+ t.Run(evidence, func(t *testing.T) {
+ pages := pagesTo(t)
+ f := capacityFixture(t, "plain")
+ createCapacityEvidence(t, f.fx.srv, "allow", nil)
+ if code, _, out := f.request(t, "domain"); code != 200 && code != 201 {
+ t.Fatalf("initial: %d %s", code, out)
+ }
+ before, _, err := f.fx.rel.Get(context.Background(), provision.RecordKey("bab", "titogo", "capacity.example.com"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ createCapacityEvidence(t, f.fx.srv, evidence, nil)
+ if code, _, out := f.request(t, "domain"); code != 200 && code != 201 {
+ t.Fatalf("reattach: %d %s", code, out)
+ }
+ after, _, err := f.fx.rel.Get(context.Background(), provision.RecordKey("bab", "titogo", "capacity.example.com"))
+ if err != nil || string(before) != string(after) {
+ t.Fatalf("reattach changed record: %v", err)
+ }
+ expectPages(t, pages)
+ })
+ }
+}
diff --git a/internal/console/hap2_wiring_test.go b/internal/console/hap2_wiring_test.go
index 0702e3fd4..3c315c1ef 100644
--- a/internal/console/hap2_wiring_test.go
+++ b/internal/console/hap2_wiring_test.go
@@ -460,6 +460,7 @@ func TestHAP2ProductionDoors(t *testing.T) {
fx, token := unplacedRootfsApp(t)
fx.srv.cfg.DeploymentSingleTenant = true
fx.srv.cfg.HomeRegion, fx.srv.cfg.HARegions = "ie", []string{"ie"}
+ createCapacityEvidence(t, fx.srv, "allow", nil)
writeFleetBox(t, fx, "", "box-1", "ie", true, time.Now())
tr := hap2S3(t, fx)
code, out := createShop(t, fx, token, `{"host":"shop.example.com"}`)
@@ -481,6 +482,7 @@ func TestHAP2ProductionDoors(t *testing.T) {
shipVersion(t, fx, "titogo", "v1")
seedChannel(t, fx, "titogo", "canary/live", "v1")
fx.srv.cfg.HomeRegion, fx.srv.cfg.HARegions = "ie", []string{"ie"}
+ createCapacityEvidence(t, fx.srv, "allow", nil)
tr := hap2S3(t, fx)
code, _, out := rawReq(t, http.MethodPost, domainsURL(fx, fx.sqid, "titogo"), token, `{"host":"site.example.com","kind":"static"}`)
if code != 200 && code != 201 {
diff --git a/internal/console/nocapacity.go b/internal/console/nocapacity.go
index e17912324..0a3379b54 100644
--- a/internal/console/nocapacity.go
+++ b/internal/console/nocapacity.go
@@ -39,6 +39,34 @@ func noCapacityRefusal(region string) string {
return fmt.Sprintf("No box in %s has room right now. Try again in a few minutes.", region)
}
+const haCapacityUnknownRefusal = "Capacity evidence for %s is incomplete. Nothing was created. Try again in 60 seconds."
+const haCapacityPoolRefusal = "Capacity for pool %s in %s could not be checked. No box confirmed room, and at least one box does not report which pools it serves. Nothing was created. A box serving this pool must report its pool membership before this create can proceed."
+
+// 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) *doorRefusal {
+ if !s.haRegion(region) {
+ 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())
+ }
+ switch decision.Kind {
+ case HACapacityAllow:
+ return nil
+ case HACapacityCompleteZero:
+ return claimResponseRefusal(s.noRoom(ctx, region))
+ default:
+ msg := fmt.Sprintf(haCapacityUnknownRefusal, name)
+ if decision.MissingNamedPoolsOnly {
+ msg = fmt.Sprintf(haCapacityPoolRefusal, pool, name)
+ }
+ return &doorRefusal{http.StatusServiceUnavailable, msg}
+ }
+}
+
func noCapacityAlert(region string) (subject, body string) {
return fmt.Sprintf("No box in %s has room", region),
fmt.Sprintf("A request in %s was refused because no box there can take it. Every box is full, stale or excluded by its role. Add a box, or free memory or disk on one, and check the eligible-capacity alarm for %s.", region, region)
@@ -111,10 +139,10 @@ func isNoCapacityRefusal(ref *doorRefusal) bool {
}
// setNoCapacityRetryAfter stamps noCapacityRetryAfter on w when ref is the
-// no-room refusal, and leaves every other refusal's headers as its door
-// writes them.
+// no-room or HA evidence refusal. Other refusals keep their existing headers.
func setNoCapacityRetryAfter(w http.ResponseWriter, ref *doorRefusal) {
- if isNoCapacityRefusal(ref) {
+ if isNoCapacityRefusal(ref) || (ref != nil && ref.Status == http.StatusServiceUnavailable &&
+ (strings.HasPrefix(ref.Msg, "Capacity evidence for ") || strings.HasPrefix(ref.Msg, "Capacity for pool "))) {
w.Header().Set("Retry-After", noCapacityRetryAfter)
}
}
diff --git a/internal/console/rootfs_test.go b/internal/console/rootfs_test.go
index c16c1e5c5..5275a8653 100644
--- a/internal/console/rootfs_test.go
+++ b/internal/console/rootfs_test.go
@@ -590,6 +590,7 @@ func TestRootfsCreateIsNeverBornHA(t *testing.T) {
fx.srv.cfg.DeploymentSingleTenant = true
fx.srv.cfg.HomeRegion = "ie"
fx.srv.cfg.HARegions = []string{"ie"}
+ createCapacityEvidence(t, fx.srv, "allow", nil)
writeFleetBox(t, fx, "", "box-1", "ie", true, time.Now())
if code, out := createShop(t, fx, token, `{"host":"shop.example.com"}`); code != http.StatusCreated {
t.Fatalf("create = %d %s", code, out)
diff --git a/internal/console/testdata/claim-authority-sites.txt b/internal/console/testdata/claim-authority-sites.txt
index cae60265a..ee25b6e1f 100644
--- a/internal/console/testdata/claim-authority-sites.txt
+++ b/internal/console/testdata/claim-authority-sites.txt
@@ -150,9 +150,11 @@ store_gate.go|OpenGated|s.db.Exec(`UPDATE claim_loss_pages SET first_attempted_a
claim_loss_pages.go|pageClaimLossesAt|s.store.db.ExecContext(ctx, `INSERT INTO claim_loss_pages (rule, first_attempted_at, attempted_at, last_key) VALUES ('scan', 0, 0, ?) ON CONFLICT(rule) DO UPDATE SET last_key = excluded.last_key`, key)
claim_loss_pages.go|pageClaimLossesAt|s.store.db.QueryRowContext(ctx, `SELECT last_key FROM claim_loss_pages WHERE rule = 'scan'`)
store_gate.go|OpenGated|s.db.Exec(`ALTER TABLE claim_loss_pages ADD COLUMN last_key TEXT NOT NULL DEFAULT ''`)
-awsregionmetric.go|capacityPublisherFromEnv|cloudwatch.NewFromConfig(cfg, func(o *cloudwatch.Options) { o.Region = awsRegion })
+awsregionmetric.go|newCloudWatchCapacity|cloudwatch.NewFromConfig(cfg, func(o *cloudwatch.Options) { o.Region = awsRegion o.Retryer = aws.NopRetryer{} o.RetryMaxAttempts = 1 })
../../cmd/console/hostsused.go|runHostsUsed|os.Open(*listingsPath)
demo_spool.go|acceptDemoResult|os.Open(s.store.demoSpoolDir)
demo_spool.go|demoSpoolDigest|os.Open(path)
managedhistory.go|managedCredentialsHeld|seal.Open(sealed)
managedhistory.go|openManagedEnrolCredentials|seal.Open(sealed)
+hacapacity_observe.go|Get|os.Open(filepath.Join(s.directory, filepath.FromSlash(key)))
+hacapacity_observe.go|dirPage|os.Open(filepath.Join(s.directory, filepath.FromSlash(prefix)))