Task 7: enforcement once the history is active; Astra findings Task 5 r2 and Task 6 r1 (unedited)
Task 7 (#404): lifetime recovery marks a data-kind allocation's hostname create-only before publishing it, and once active publishes only when the mark exists; an absent mark invalidates the history (D3 page) and leaves the allocation pending. The door's own allocation skips the step (it marked before BeginAllocation). appRegionsOn needs the history active (D1 logged once at start otherwise). Once active, a data-kind create on a region or fleet complete did not examine, or on a closed fleet, gets S4, as does an app created with --place on one; unexamined regions drop out of the automatic choices. Not yet reviewed: Task 5 round 2 found a P1 in round 1's fault family (drain completeness), so stopping rule 2 applies; reported to the coordinator. Task 6 round 1 found three P1s and two P2s, to fix next.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
18 files changed,
+557
−10
docs/superpowers/notes/reviews/ASTRA-FINDINGS-nearest-region-b-task5-r2.md+23 −0docs/superpowers/notes/reviews/ASTRA-FINDINGS-nearest-region-b-task6-r1.md+55 −0internal/console/apicli.go+8 −0internal/console/apiinstances.go+5 −0internal/console/apisidecars.go+5 −0internal/console/hostsused.go+128 −2internal/console/hostsused_active_test.go+276 −0internal/console/hostsused_window.go+1 −0internal/console/hostsused_writers_test.go+7 −1internal/console/lifetimes_create.go+20 −2internal/console/lifetimes_recovery.go+2 −2internal/console/regioncandidates.go+11 −1internal/console/regionclaim_test.go+1 −0internal/console/regionconfig.go+4 −2internal/console/regionconfig_test.go+1 −0internal/console/regiondefault_test.go+1 −0internal/console/regionlabels_test.go+1 −0internal/provision/nearest_region_b_census_test.go+8 −0
CI cancelled — superseded by a newer push — run details
diff --git a/docs/superpowers/notes/reviews/ASTRA-FINDINGS-nearest-region-b-task5-r2.md b/docs/superpowers/notes/reviews/ASTRA-FINDINGS-nearest-region-b-task5-r2.md| new file mode 100644 |
| index 000000000..51a74a1a3 |
| --- /dev/null |
| +++ b/docs/superpowers/notes/reviews/ASTRA-FINDINGS-nearest-region-b-task5-r2.md |
| @@ -0,0 +1,23 @@ |
| +Round 1 dispositions: |
| + |
| +- **P1 1 — Partly resolved:** unfinished seed records are counted, but abort can hide a running upload. |
| +- **P1 2 — Resolved:** `hostsTransition` clears cached state and ETag on every failed write. |
| +- **P2 — Resolved:** begin, cancel and close-fleet return their transition result without the status scan. |
| + |
| +**P1 — Terminal seed state does not prove the detached worker has finished (Task 5, §3a.2).** |
| + |
| +**Fault family:** drain completeness — zero must mean no admitted creation or movement remains. |
| + |
| +`seedEnded` excludes aborted and rolled-back seeds from the drain at [hostsused_window.go:129](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/nearest-region-b-review/internal/console/hostsused_window.go:129). However, the import abort handler writes `aborted` without waiting for the upload at [apiinstanceimport.go:875](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/nearest-region-b-review/internal/console/apiinstanceimport.go:875). |
| + |
| +**Failure scenario:** an upload passes its record recheck and pauses inside `putSnapshot` at [apiinstanceimport.go:615](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/nearest-region-b-review/internal/console/apiinstanceimport.go:615). Abort succeeds; then `begin` opens the window. With the create handler finished, its allocation settled and the seed now excluded, all drain counts can be zero. Scanning can start while the detached upload can still write its snapshot. The subsequent record transition may fail, but that happens after the data write. `complete` uses these same insufficient counts at [hostsused_inventory.go:411](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/nearest-region-b-review/internal/console/hostsused_inventory.go:411). |
| + |
| +The new witness inserts seed states directly; it never runs an upload concurrently with abort, so it misses this case ([hostsused_window_test.go:237](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/nearest-region-b-review/internal/console/hostsused_window_test.go:237)). |
| + |
| +**Concrete fix:** retain drain accounting for detached workers through their last write, independently of record state, while preserving record-based accounting across restarts. Add a real-door witness that blocks the snapshot PUT, aborts, opens the window, and verifies that drain and completion remain blocked. |
| + |
| +This repeats round 1’s P1 fault family, so the review stops under the brief and stopping rule 2. Before another fix, choose between refusing window entry while detached work remains, cutting detached seed/import support from this slice, or enforcing worker-lifetime accounting centrally with a guard test. I recommend the central accounting approach. |
| + |
| +The three named regression tests could not start: the read-only sandbox prevented Go from creating its work directory. `GOCACHE` was unset. No files changed, no subagents spawned, and no full suites ran. The remaining review scope was not completed after the mandatory stop. |
| + |
| +**NOT READY** |
| \ No newline at end of file |
diff --git a/docs/superpowers/notes/reviews/ASTRA-FINDINGS-nearest-region-b-task6-r1.md b/docs/superpowers/notes/reviews/ASTRA-FINDINGS-nearest-region-b-task6-r1.md| new file mode 100644 |
| index 000000000..299584e99 |
| --- /dev/null |
| +++ b/docs/superpowers/notes/reviews/ASTRA-FINDINGS-nearest-region-b-task6-r1.md |
| @@ -0,0 +1,55 @@ |
| +Reviewed Task 6, round 1, at `45dbce1b4b75f890eca1988eea4dd47c28c882aa`. |
| + |
| +1. **P1 — Closing a fleet can exempt a region’s bucket.** Spec §3; Task 6. |
| + |
| + [`closedTargets`](</home/paulca/amadan.net/carlos/platform/.claude/worktrees/nearest-region-b-review/internal/console/hostsused_inventory.go:114>) excuses every bucket named by any closed fleet. [`complete`](</home/paulca/amadan.net/carlos/platform/.claude/worktrees/nearest-region-b-review/internal/console/hostsused_inventory.go:433>) skips those targets, including their imported hostnames at line 476. Fleet creation accepts a bucket name without checking exclusive ownership ([fleets.go:198](</home/paulca/amadan.net/carlos/platform/.claude/worktrees/nearest-region-b-review/internal/console/fleets.go:198>)). |
| + |
| + **Failure:** A fleet names `data-ie`, also used by region `ie`. Closing that fleet allows completion without scanning `data-ie`; a hostname with only bucket leftovers remains unmarked and reusable in `ie`. |
| + |
| + **Fix:** Track every target’s consumers. Excuse a target only when all consumers are closed fleets; region/pool consumers must always require inventory. Add shared-bucket witnesses. |
| + |
| + **Fault family:** Fleet closure must not waive inventory for an open placement target. |
| + |
| +2. **P1 — An old completion can activate a newly opened window.** Spec §3a; Task 6. |
| + |
| + [`complete`](</home/paulca/amadan.net/carlos/platform/.claude/worktrees/nearest-region-b-review/internal/console/hostsused_inventory.go:406>) checks drain and listings before its final transition. That transition checks only `cur.Mode == activating` ([line 514](</home/paulca/amadan.net/carlos/platform/.claude/worktrees/nearest-region-b-review/internal/console/hostsused_inventory.go:514>)); it does not verify that this is the same window. `hostsTransition` uses the latest cached ETag, so CAS does not reject this sequence. |
| + |
| + **Failure:** Pause completion after its checks, cancel, admit a lifetime allocation, then begin again. Resuming the old completion activates the new window despite its pending allocation and cleared listings. The allocation can subsequently publish over earlier data. |
| + |
| + **Fix:** Bind completion and imported listings to a persistent window identity, and reject stale operations atomically. Serialize conflicting window operations or enforce equivalent generation checks. Add a barrier-based cancel/rebegin witness. |
| + |
| + **Fault family:** Activation must use the drain and inventory of one uninterrupted maintenance window. |
| + |
| +3. **P1 — The mapper breaks an existing guard test.** Task 6. |
| + |
| + The new literal at [hostsused_map.go:100](</home/paulca/amadan.net/carlos/platform/.claude/worktrees/nearest-region-b-review/internal/provision/hostsused_map.go:100>) matches the prohibition in [`TestRawInstancesDirectoryIsNamedOnlyHere`](</home/paulca/amadan.net/carlos/platform/.claude/worktrees/nearest-region-b-review/internal/layout/rawdir_test.go:49>). Reproducing that test’s file selection and regular expression read-only identifies this exact line. |
| + |
| + **Failure:** The layout test fails when CI runs it. This is separate from the pending root-read census decisions. |
| + |
| + **Fix:** Provide an appropriate layout-owned parsing interface, or narrowly amend the guard to permit this pure listing parser while preserving its prohibition on filesystem access elsewhere. |
| + |
| + **Fault family:** Raw instance-directory ownership and the existing regression gate. |
| + |
| +4. **P2 — Malformed flat filenames disappear instead of being reported unmapped.** Review Focus 5; Task 6. |
| + |
| + [`flatNameHosts`](</home/paulca/amadan.net/carlos/platform/.claude/worktrees/nearest-region-b-review/internal/provision/hostsused_map.go:154>) returns nothing for `Shop.example.com.db` or `shop.example.com..db`. Its [caller](</home/paulca/amadan.net/carlos/platform/.claude/worktrees/nearest-region-b-review/internal/provision/hostsused_map.go:129>) never adds these entries to `unmapped`. |
| + |
| + **Failure:** An otherwise clean import containing these malformed host-shaped files permits completion instead of C9. The normalization witness covers nested/offline paths but omits flat files. |
| + |
| + **Fix:** Distinguish malformed host-shaped entries from the agreed platform-file exclusions, report them unmapped, and extend both mapper and completion witnesses. |
| + |
| + **Fault family:** Invalid inventory names must fail closed without normalization. |
| + |
| +5. **P2 — Pools are inferred from records instead of fixed in the roster.** Spec §3; Task 6. |
| + |
| + [`hostsRosterNow`](</home/paulca/amadan.net/carlos/platform/.claude/worktrees/nearest-region-b-review/internal/console/hostsused_inventory.go:73>) adds boxes, regions, buckets and fleets, but no pools. [`complete`](</home/paulca/amadan.net/carlos/platform/.claude/worktrees/nearest-region-b-review/internal/console/hostsused_inventory.go:510>) instead takes examined pools from current instance bodies. |
| + |
| + **Failure:** A configured pool with no current instance record is omitted despite successful box inventory. Pool membership changes also escape the roster comparison, while a record alone can introduce an “examined” pool. |
| + |
| + **Fix:** Capture configured pool membership and its serving targets at `begin`, compare that membership at completion, and derive examined pools from successfully inventoried roster entries. |
| + |
| + **Fault family:** Examined placement targets must come from the frozen inventory roster. |
| + |
| +No files changed; `GOCACHE` remained unset. The targeted Go test could not start because the read-only sandbox blocked work-directory creation. No full suites ran. |
| + |
| +**NOT READY** |
| \ No newline at end of file |
diff --git a/internal/console/apicli.go b/internal/console/apicli.go| index 6746db73b..99091e896 100644 |
| --- a/internal/console/apicli.go |
| +++ b/internal/console/apicli.go |
| @@ -451,6 +451,14 @@ func (s *Server) handleAPICreateApp(w http.ResponseWriter, r *http.Request) { |
| return |
| } |
| } |
| + // Once the hostname history is active, no app is placed on a fleet |
| + // complete did not examine, or closed (S4). |
| + if place != "" { |
| + if ref := s.hostsTargetRefusal(r.Context(), place); ref != nil { |
| + writeDoorRefusalJSON(w, r, ref) |
| + return |
| + } |
| + } |
| rq, ref := s.newAppRegionReq(r, req.Region, req.Timezone) |
| if ref != nil { |
| jsonError(w, ref.Status, ref.Msg) |
diff --git a/internal/console/apiinstances.go b/internal/console/apiinstances.go| index 3adbd89a7..b1d5d2472 100644 |
| --- a/internal/console/apiinstances.go |
| +++ b/internal/console/apiinstances.go |
| @@ -1711,6 +1711,11 @@ func (s *Server) handleAPIInstanceCreate(w http.ResponseWriter, r *http.Request) |
| return |
| } |
| defer done() |
| + // Once active, only a region or fleet complete examined (S4). |
| + if ref := s.hostsTargetRefusal(r.Context(), rec.Region); ref != nil { |
| + writeDoorRefusalJSON(w, r, ref) |
| + return |
| + } |
| } |
| // THE STORE IS PROVISIONED BEFORE THE RECORD IS WRITTEN, and a failure |
| // here means no record at all (issue #412, spec §7). This ordering is |
diff --git a/internal/console/apisidecars.go b/internal/console/apisidecars.go| index 915dd9605..21b94983a 100644 |
| --- a/internal/console/apisidecars.go |
| +++ b/internal/console/apisidecars.go |
| @@ -354,6 +354,11 @@ func (s *Server) handleAPISidecarCreate(w http.ResponseWriter, r *http.Request) |
| return |
| } |
| defer done() |
| + // Once active, only a region or fleet complete examined (S4). |
| + if ref := s.hostsTargetRefusal(r.Context(), rec.Region); ref != nil { |
| + writeDoorRefusalJSON(w, r, ref) |
| + 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. |
diff --git a/internal/console/hostsused.go b/internal/console/hostsused.go| index 6ee983e24..eeba8dd0d 100644 |
| --- a/internal/console/hostsused.go |
| +++ b/internal/console/hostsused.go |
| @@ -6,10 +6,13 @@ import ( |
| "log" |
| "net/http" |
| "os" |
| + "slices" |
| "sync" |
| "time" |
| + "github.com/carlosframework/platform/internal/alerting" |
| "github.com/carlosframework/platform/internal/provision" |
| + "github.com/carlosframework/platform/internal/registry" |
| "github.com/carlosframework/platform/internal/release" |
| ) |
| @@ -41,6 +44,23 @@ const ( |
| msgHostsMovesPaused = "Moves and placement are paused for maintenance. Try again later." // S7 |
| ) |
| +// msgHostsTargetUnexamined is S4: target is a region's place name, or |
| +// "fleet <name>". |
| +func msgHostsTargetUnexamined(target string) string { |
| + return "New instances can't be created on " + target + " yet. Choose another region." |
| +} |
| + |
| +// D1-D3, the operator log line and the pages (approved, nearest-region-never-reuse-b.md). |
| +const msgAppRegionsWaitForHistory = "app regions are off until the hostname history is complete" |
| + |
| +func msgHostsPageUncovered(key string) string { |
| + return "the hostname history is invalidated: " + key + " is a record the history does not cover" |
| +} |
| + |
| +func msgHostsPagePendingCreate(host string) string { |
| + return "the hostname history is invalidated: a pending create for " + host + " would publish a record the history does not cover" |
| +} |
| + |
| // hostsHistory is the process's copy of control/hosts-used/@mode. One |
| // console process serves a deployment (spec §3a): the state is read once, |
| // before the first door needs it, and changed only by this process's own |
| @@ -100,11 +120,117 @@ func (s *Server) hostsState(ctx context.Context) (provision.HostsState, error) { |
| // LoadHostsMode reads the history's state at console start, before the |
| // console serves (spec §3a). A failure is logged and left for the first door |
| -// to read again, which refuses until it can. |
| +// to read again, which refuses until it can. With app regions switched on |
| +// and the history not active, it says once that they stay off (spec §4). |
| func (s *Server) LoadHostsMode(ctx context.Context) { |
| - if _, err := s.hostsMode(ctx); err != nil { |
| + mode, err := s.hostsMode(ctx) |
| + if err != nil { |
| log.Printf("console: hosts used: read the mode at start: %v (the first door that needs it reads it again)", err) |
| } |
| + if s.cfg.AppRegions && s.cfg.HomeRegion != "" && mode != provision.HostsModeActive { |
| + log.Printf("console: %s", msgAppRegionsWaitForHistory) |
| + } |
| +} |
| + |
| +// hostsCached is the held state, without a read: Mode is "" until some |
| +// door or the start has read it. For callers with no request to fail |
| +// (appRegionsOn, the region candidates), which read unknown as not active. |
| +func (s *Server) hostsCached() provision.HostsState { |
| + s.hosts.mu.Lock() |
| + defer s.hosts.mu.Unlock() |
| + return s.hosts.state |
| +} |
| + |
| +// hostsActive reports whether the held mode is active. |
| +func (s *Server) hostsActive() bool { return s.hostsCached().Mode == provision.HostsModeActive } |
| + |
| +// regionExamined reports whether a data-kind create may be placed in the |
| +// record-vocabulary region code once active: the home ("") always, any |
| +// other region only if complete examined it. |
| +func regionExamined(st provision.HostsState, code string) bool { |
| + return code == "" || slices.Contains(st.Examined, "region:"+code) |
| +} |
| + |
| +// hostsTargetRefusal is S4 (spec §3): once the history is active, a |
| +// data-kind create placed on a region or fleet complete did not examine, |
| +// or on a closed fleet, is refused. Pools are not a separate target: their |
| +// boxes are scanned under their regions' codes. Before activation, and for |
| +// exempt kinds (the caller's check), nothing is refused. |
| +func (s *Server) hostsTargetRefusal(ctx context.Context, region string) *doorRefusal { |
| + st, err := s.hostsState(ctx) |
| + if err != nil || st.Mode != provision.HostsModeActive { |
| + return nil // an unreadable mode is the admission's and the mark's to refuse |
| + } |
| + if fleet, ok := registry.FleetPlacement(region); ok { |
| + if slices.Contains(st.Closed, "fleet:"+fleet) || !slices.Contains(st.Examined, "fleet:"+fleet) { |
| + return &doorRefusal{http.StatusConflict, msgHostsTargetUnexamined("fleet " + fleet)} |
| + } |
| + return nil |
| + } |
| + if !regionExamined(st, region) { |
| + return &doorRefusal{http.StatusConflict, msgHostsTargetUnexamined(s.placeOf(region, s.candsOrHome(ctx)))} |
| + } |
| + return nil |
| +} |
| + |
| +// invalidateHosts moves an active history to invalidated (spec §4), in the |
| +// store and the process, and pages with subject. Every data-kind create is |
| +// refused (S5) until a fresh inventory completes. |
| +func (s *Server) invalidateHosts(ctx context.Context, reason string) error { |
| + _, ref, err := s.hostsTransition(ctx, func(cur provision.HostsState) (provision.HostsState, *doorRefusal) { |
| + if cur.Mode != provision.HostsModeActive { |
| + return cur, &doorRefusal{http.StatusConflict, msgHostsNotActive} |
| + } |
| + return provision.HostsState{Mode: provision.HostsModeInvalidated, Reason: reason, Closed: cur.Closed}, nil |
| + }) |
| + if err != nil { |
| + return err |
| + } |
| + if ref != nil { |
| + return errors.New(ref.Msg) |
| + } |
| + log.Printf("console: %s", reason) |
| + if err := alerting.Page(ctx, alerting.LevelIncident, reason, reason); err != nil { |
| + log.Printf("console: hosts used: page the invalidation: %v", err) |
| + } |
| + return nil |
| +} |
| + |
| +// recoveryMark is lifetime recovery's mark step (spec §2), before it |
| +// publishes an allocation: once the history is active (or invalidated) the |
| +// hostname must already be marked, and an absent mark invalidates the |
| +// history and leaves the allocation pending; before that it marks |
| +// create-only, a mark already there passing. It answers whether the |
| +// allocation may publish. |
| +func (s *Server) recoveryMark(ctx context.Context, a Allocation) bool { |
| + mode, err := s.hostsMode(ctx) |
| + if err != nil { |
| + log.Printf("console: lifetimes: allocation %s of %s: read the hostname history's mode: %v (pending)", a.OpID, a.Host, err) |
| + return false |
| + } |
| + switch mode { |
| + case provision.HostsModeActive, provision.HostsModeInvalidated: |
| + used, err := provision.HostIsUsed(ctx, s.cfg.Releases, a.Host) |
| + if err != nil { |
| + log.Printf("console: lifetimes: allocation %s of %s: read its mark: %v (pending)", a.OpID, a.Host, err) |
| + return false |
| + } |
| + if used { |
| + return true |
| + } |
| + if mode == provision.HostsModeActive { |
| + if err := s.invalidateHosts(ctx, msgHostsPagePendingCreate(a.Host)); err != nil { |
| + log.Printf("console: lifetimes: allocation %s of %s: invalidate the hostname history: %v", a.OpID, a.Host, err) |
| + } |
| + } |
| + return false |
| + } |
| + if _, err := provision.MarkHostUsed(ctx, s.cfg.Releases, provision.HostUse{Host: a.Host, Account: a.Account, App: a.App, |
| + Kind: "instance", Source: "recovery", At: time.Now().UTC()}); err != nil { |
| + log.Printf("console: lifetimes: allocation %s of %s: mark its hostname: %v (pending)", a.OpID, a.Host, err) |
| + return false |
| + } |
| + return true |
| } |
| // hostsTransition changes the state under the lock: next sees the current |
diff --git a/internal/console/hostsused_active_test.go b/internal/console/hostsused_active_test.go| new file mode 100644 |
| index 000000000..64db1ebf5 |
| --- /dev/null |
| +++ b/internal/console/hostsused_active_test.go |
| @@ -0,0 +1,276 @@ |
| +package console |
| + |
| +// Enforcement once the history is active (nearest-region never-reuse plan, |
| +// Task 7; spec §2-§4): recovery publishes only marked allocations, two |
| +// creates of one new hostname end with one publication, the nearest-region |
| +// switch needs active, and a create on a target complete did not examine, |
| +// or on a closed fleet, is refused (S4). |
| + |
| +import ( |
| + "context" |
| + "net/http" |
| + "sync" |
| + "sync/atomic" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/provision" |
| + "github.com/carlosframework/platform/internal/registry" |
| + "github.com/carlosframework/platform/internal/release" |
| +) |
| + |
| +// forceHostsState writes st and has srv read it, as a console start would. |
| +func forceHostsState(t *testing.T, srv *Server, st provision.HostsState) { |
| + t.Helper() |
| + ctx := context.Background() |
| + _, etag, err := provision.ReadHostsState(ctx, srv.cfg.Releases) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := provision.WriteHostsState(ctx, srv.cfg.Releases, st, etag); err != nil { |
| + t.Fatal(err) |
| + } |
| + srv.hosts.reset() |
| + if got, err := srv.hostsMode(ctx); err != nil || got != st.Mode { |
| + t.Fatalf("mode = %q %v, want %q", got, err, st.Mode) |
| + } |
| +} |
| + |
| +func dropMark(t *testing.T, st release.Store, host string) { |
| + t.Helper() |
| + if err := st.Delete(context.Background(), provision.HostsUsedKey(host)); err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
| + |
| +// TestRecoveryRefusesUnmarkedPublication: once active, recovery publishes |
| +// an allocation's record only when its hostname is marked. An allocation |
| +// begun by a console from before the history (no mark) is left pending, |
| +// and the history is invalidated. Both replay branches: the record absent, |
| +// and a stale body under the key. |
| +func TestRecoveryRefusesUnmarkedPublication(t *testing.T) { |
| + for _, step := range []string{"record", "stale"} { |
| + t.Run(step, func(t *testing.T) { |
| + l := newLtOn(t) |
| + if step == "stale" { |
| + retiredSlot(t, l.fx.rel, ltOne) |
| + legacyBody(t, l.fx.rel, ltApp, ltOne, "edge") |
| + } |
| + a := l.pendingCreate(t, ltOne, step) |
| + dropMark(t, l.fx.rel, ltOne) // as an older console's allocation would be |
| + forceHostsState(t, l.fx.srv, provision.HostsState{Mode: provision.HostsModeActive}) |
| + recoverOn(t, l.fx.srv) |
| + oneAlloc(t, l.fx.st, ltOne, lifetimePending) |
| + if raw, _ := rawOf(t, l.fx.rel, ltApp, ltOne); raw != nil { |
| + if rec := decodeRec(t, raw); int64(rec.Incarnation) == a.Incarnation { |
| + t.Fatalf("the unmarked allocation published: %s", raw) |
| + } |
| + } |
| + st, _, err := provision.ReadHostsState(context.Background(), l.fx.rel) |
| + if err != nil || st.Mode != provision.HostsModeInvalidated { |
| + t.Fatalf("state = %+v %v, want invalidated", st, err) |
| + } |
| + // Marked again (by a re-inventory), recovery publishes it. |
| + if _, err := provision.MarkHostUsed(context.Background(), l.fx.rel, provision.HostUse{Host: ltOne, Source: "test"}); err != nil { |
| + t.Fatal(err) |
| + } |
| + forceHostsState(t, l.fx.srv, provision.HostsState{Mode: provision.HostsModeActive}) |
| + recoverOn(t, l.fx.srv) |
| + oneAlloc(t, l.fx.st, ltOne, lifetimeCommitted) |
| + }) |
| + } |
| +} |
| + |
| +// TestRecoveryMarksBeforeActivation: before the history is active, a |
| +// replayed allocation marks its hostname create-only and publishes. |
| +func TestRecoveryMarksBeforeActivation(t *testing.T) { |
| + l := newLtOn(t) |
| + l.pendingCreate(t, ltOne, "record") |
| + dropMark(t, l.fx.rel, ltOne) |
| + recoverOn(t, l.fx.srv) |
| + oneAlloc(t, l.fx.st, ltOne, lifetimeCommitted) |
| + if !marked(t, l.fx.rel, ltOne) { |
| + t.Fatal("recovery published without marking") |
| + } |
| +} |
| + |
| +// TestConcurrentCreatesOneWins: two apps create one new hostname at once, |
| +// both past every other check: exactly one publishes, the other is refused. |
| +func TestConcurrentCreatesOneWins(t *testing.T) { |
| + lifetimesFor(t, func(t *testing.T, on func(*testing.T, markCase)) { |
| + fx, member, domain := canaryDoorFixture(t, "code-race", "bar") |
| + bucket := wrapBucket(fx) |
| + on(t, markCase{fx: fx, bucket: bucket}) |
| + forceHostsState(t, fx.srv, provision.HostsState{Mode: provision.HostsModeActive}) |
| + host := "shared." + domain |
| + // The first create to reach its mark waits there (up to a second) |
| + // for the second: with lifetimes on the hostname lock serialises |
| + // them, and the barrier gives up. |
| + arrived := make(chan struct{}, 2) |
| + var n atomic.Int32 |
| + bucket.setHook(func(op, key string) error { |
| + if op == "put" && key == provision.HostsUsedKey(host) { |
| + arrived <- struct{}{} |
| + if n.Add(1) == 1 { |
| + select { |
| + case <-time.After(time.Second): |
| + case <-waitSecond(arrived): |
| + } |
| + } |
| + } |
| + return nil |
| + }) |
| + var wg sync.WaitGroup |
| + codes := make([]int, 2) |
| + for i, app := range []string{"titogo", "bar"} { |
| + wg.Add(1) |
| + go func(i int, app string) { |
| + defer wg.Done() |
| + codes[i], _, _ = rawReq(t, http.MethodPost, instancesURL(fx, "bab", app), member, `{"host":"`+host+`"}`) |
| + }(i, app) |
| + } |
| + wg.Wait() |
| + bucket.setHook(nil) |
| + published := 0 |
| + for _, app := range []string{"titogo", "bar"} { |
| + if _, err := provision.GetRecord(context.Background(), fx.rel, "bab", app, host); err == nil { |
| + published++ |
| + } |
| + } |
| + created := 0 |
| + for _, c := range codes { |
| + if c == http.StatusCreated { |
| + created++ |
| + } |
| + } |
| + if published != 1 || created != 1 { |
| + t.Fatalf("codes %v, %d published; want one created and one refused", codes, published) |
| + } |
| + }) |
| +} |
| + |
| +// waitSecond is a channel that closes when a second arrival is queued. |
| +func waitSecond(arrived chan struct{}) <-chan struct{} { |
| + done := make(chan struct{}) |
| + go func() { |
| + for len(arrived) < 2 { |
| + time.Sleep(5 * time.Millisecond) |
| + } |
| + close(done) |
| + }() |
| + return done |
| +} |
| + |
| +// TestAppRegionsNeedActive: the nearest-region switch has no effect until |
| +// the history is active. |
| +func TestAppRegionsNeedActive(t *testing.T) { |
| + fx, _, _ := fillFixture(t, "uk") |
| + fx.srv.cfg.AppRegions = true |
| + for _, c := range []struct { |
| + mode string |
| + want bool |
| + }{ |
| + {provision.HostsModeIncomplete, false}, |
| + {provision.HostsModeActivating, false}, |
| + {provision.HostsModeInvalidated, false}, |
| + {provision.HostsModeActive, true}, |
| + } { |
| + forceHostsState(t, fx.srv, provision.HostsState{Mode: c.mode}) |
| + if got := fx.srv.appRegionsOn(); got != c.want { |
| + t.Errorf("appRegionsOn in %s = %v, want %v", c.mode, got, c.want) |
| + } |
| + } |
| +} |
| + |
| +// TestStoredNonHomeRegionBeforeComplete: before the history is active an |
| +// app with a stored non-home region creates there as today. |
| +func TestStoredNonHomeRegionBeforeComplete(t *testing.T) { |
| + fx, token, u := fillFixture(t, "uk") |
| + fx.srv.cfg.AppRegions = true |
| + if rec := mustCreate(t, u, token, `{"host":"a.go.tito.io"}`); rec.Region != "uk" || rec.RegionFrom != "app" { |
| + t.Fatalf("create = %+v, want the stored region", rec) |
| + } |
| +} |
| + |
| +// TestNearestRegionAfterComplete: once active, with uk examined, the |
| +// stored region is used and the picker offers uk. |
| +func TestNearestRegionAfterComplete(t *testing.T) { |
| + fx, token, u := fillFixture(t, "uk") |
| + fx.srv.cfg.AppRegions = true |
| + forceHostsState(t, fx.srv, provision.HostsState{Mode: provision.HostsModeActive, Examined: []string{"region:ie", "region:uk"}}) |
| + if rec := mustCreate(t, u, token, `{"host":"a.go.tito.io"}`); rec.Region != "uk" { |
| + t.Fatalf("create = %+v, want uk", rec) |
| + } |
| + snap, err := fx.srv.liveEdges(context.Background()) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if c, ok := findCandidate(fx.srv.regionCands(snap), "uk"); !ok || !c.Eligible { |
| + t.Fatalf("uk candidate = %+v %v, want eligible", c, ok) |
| + } |
| +} |
| + |
| +// TestUnexaminedTargetRefused: once active, a region complete did not |
| +// examine takes no data-kind create (S4), and the automatic choices skip it. |
| +func TestUnexaminedTargetRefused(t *testing.T) { |
| + fx, token, u := fillFixture(t, "ie") |
| + fx.srv.cfg.AppRegions = true |
| + forceHostsState(t, fx.srv, provision.HostsState{Mode: provision.HostsModeActive, Examined: []string{"region:ie"}}) |
| + code, _, out := rawReq(t, http.MethodPost, u, token, `{"host":"b.go.tito.io","region":"uk"}`) |
| + if code != http.StatusConflict || ltErr(out) != msgHostsTargetUnexamined(fx.srv.placeOf("uk", fx.srv.candsOrHome(context.Background()))) { |
| + t.Fatalf("create in an unexamined region = %d %s, want 409 S4", code, out) |
| + } |
| + // Exempt kinds are not refused. |
| + if code, _, out := rawReq(t, http.MethodPost, u, token, `{"host":"c.go.tito.io","region":"uk","kind":"static"}`); code != http.StatusCreated { |
| + t.Fatalf("static create in an unexamined region = %d %s, want 201", code, out) |
| + } |
| + snap, err := fx.srv.liveEdges(context.Background()) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if c, ok := findCandidate(fx.srv.regionCands(snap), "uk"); !ok || c.Eligible { |
| + t.Fatalf("uk candidate = %+v %v, want it skipped", c, ok) |
| + } |
| + // The home is always examined. |
| + if code, _, out := rawReq(t, http.MethodPost, u, token, `{"host":"d.go.tito.io"}`); code != http.StatusCreated { |
| + t.Fatalf("create at home = %d %s, want 201", code, out) |
| + } |
| +} |
| + |
| +// TestClosedFleetRefused: a closed fleet takes no data-kind create, and no |
| +// app is created placed on it (S4). |
| +func TestClosedFleetRefused(t *testing.T) { |
| + fx, token := instanceFixture(t, "code-closed-fleet") |
| + reg := openTestReg(t, fx) |
| + if _, err := reg.CreateFleet(registry.Fleet{Name: "fx", Account: "bab", Bucket: "fx-data"}); err != nil { |
| + t.Fatal(err) |
| + } |
| + forceHostsState(t, fx.srv, provision.HostsState{Mode: provision.HostsModeActive, Closed: []string{"fleet:fx"}, Examined: []string{"fleet:fx"}}) |
| + status, _, out := rawReq(t, http.MethodPost, fx.ts.URL+"/api/cli/apps/bab/new", token, `{"name":"placed","place":"fleet/fx"}`) |
| + if status != http.StatusConflict || ltErr(out) != msgHostsTargetUnexamined("fleet fx") { |
| + t.Fatalf("app create on a closed fleet = %d %s, want 409 S4", status, out) |
| + } |
| + if ref := fx.srv.hostsTargetRefusal(context.Background(), "fleet/fx"); ref == nil || ref.Msg != msgHostsTargetUnexamined("fleet fx") { |
| + t.Fatalf("a data-kind create on a closed fleet = %+v, want S4", ref) |
| + } |
| + // Not examined at all: the same refusal. |
| + forceHostsState(t, fx.srv, provision.HostsState{Mode: provision.HostsModeActive}) |
| + if ref := fx.srv.hostsTargetRefusal(context.Background(), "fleet/fx"); ref == nil { |
| + t.Fatal("a data-kind create on an unexamined fleet was admitted") |
| + } |
| + // Before the history is active, nothing is refused. |
| + forceHostsState(t, fx.srv, provision.HostsState{Mode: provision.HostsModeIncomplete, Closed: []string{"fleet:fx"}}) |
| + if ref := fx.srv.hostsTargetRefusal(context.Background(), "fleet/fx"); ref != nil { |
| + t.Fatalf("incomplete refused: %+v", ref) |
| + } |
| +} |
| + |
| +// historyActive holds an active hostname history in srv's process, with |
| +// every region the region fixtures use examined: app regions switch on only |
| +// once the history is active (nearest-region never-reuse, Task 7). |
| +func historyActive(srv *Server) { |
| + srv.hosts.mu.Lock() |
| + defer srv.hosts.mu.Unlock() |
| + srv.hosts.state = provision.HostsState{Mode: provision.HostsModeActive, |
| + Examined: []string{"region:ie", "region:uk", "region:au", "region:us", "region:jp", "region:de", "region:ca"}} |
| +} |
diff --git a/internal/console/hostsused_window.go b/internal/console/hostsused_window.go| index 8e82f9fbc..6276b8993 100644 |
| --- a/internal/console/hostsused_window.go |
| +++ b/internal/console/hostsused_window.go |
| @@ -24,6 +24,7 @@ const ( |
| msgHostsAlreadyComplete = "The hostname history is already complete." // C1 |
| msgHostsWindowOpen = "A maintenance window is already open." // C2 |
| msgHostsNoWindow = "No maintenance window is open. Start one with carlos system hosts-used begin." // C3 |
| + msgHostsNotActive = "The hostname history is not active, so there is nothing to invalidate." // C12 |
| msgHostsClaimsOn = "This console runs host claims or live moves, so the hostname history can't be completed." // C11 |
| ) |
diff --git a/internal/console/hostsused_writers_test.go b/internal/console/hostsused_writers_test.go| index 9ad0a684e..c33588c71 100644 |
| --- a/internal/console/hostsused_writers_test.go |
| +++ b/internal/console/hostsused_writers_test.go |
| @@ -173,7 +173,13 @@ func forceHostsMode(t *testing.T, srv *Server, mode string) { |
| if err != nil { |
| t.Fatal(err) |
| } |
| - if _, err := provision.WriteHostsMode(ctx, srv.cfg.Releases, mode, etag); err != nil { |
| + // Active with every fixture region examined (merge B's S4 refuses an |
| + // unexamined one; its own tests are in hostsused_active_test.go). |
| + st := provision.HostsState{Mode: mode} |
| + if mode == provision.HostsModeActive { |
| + st.Examined = []string{"region:ie", "region:uk"} |
| + } |
| + if _, err := provision.WriteHostsState(ctx, srv.cfg.Releases, st, etag); err != nil { |
| t.Fatal(err) |
| } |
| srv.hosts.reset() |
diff --git a/internal/console/lifetimes_create.go b/internal/console/lifetimes_create.go| index b7921bb0b..8db99c91a 100644 |
| --- a/internal/console/lifetimes_create.go |
| +++ b/internal/console/lifetimes_create.go |
| @@ -125,7 +125,7 @@ func (s *Server) createRecordWithLifetimeLocked(ctx context.Context, rec provisi |
| if err := s.allocCleanLocked(ctx, a, a.StaleETag, plan); err != nil { |
| return nil, err |
| } |
| - return s.allocRecordLocked(ctx, a) |
| + return s.allocRecordLocked(ctx, a, true) |
| } |
| // lifetimeAppCheck is step 0: the account, then the apps row and the store's |
| @@ -376,10 +376,28 @@ func (s *Server) allocPrevOwnerCleanLocked(ctx context.Context, a Allocation) er |
| return nil |
| } |
| +// allocationDataKind reports whether an allocation's record is a data kind. |
| +// A body that does not decode is treated as one: marking is the safe side. |
| +func allocationDataKind(a Allocation) bool { |
| + var rec provision.Record |
| + if err := json.Unmarshal(a.Body, &rec); err != nil { |
| + return true |
| + } |
| + return rec.DataKind() |
| +} |
| + |
| // allocRecordLocked is steps 6 and 7: the record create-only, with its |
| // record_seq introduced, then the intent committed. |
| -func (s *Server) allocRecordLocked(ctx context.Context, a Allocation) (*provision.Record, error) { |
| +// |
| +// doorMarked is the create door's own call, which marked the hostname (or |
| +// was refused) before BeginAllocation. Recovery's replays pass false: an |
| +// allocation begun by an older console has no mark, so a data kind's |
| +// hostname is marked, or required marked once active, first (hostsused.go). |
| +func (s *Server) allocRecordLocked(ctx context.Context, a Allocation, doorMarked bool) (*provision.Record, error) { |
| key := provision.RecordKey(a.Account, a.App, a.Host) |
| + if !doorMarked && allocationDataKind(a) && !s.recoveryMark(ctx, a) { |
| + return nil, errLifetimePending |
| + } |
| _, seq, err := provision.WriteRecord(provision.WithRecordSequence(ctx), s.cfg.Releases, key, []byte(`{}`), a.Body, "") |
| if err != nil { |
| if !errors.Is(err, release.ErrCASConflict) { |
diff --git a/internal/console/lifetimes_recovery.go b/internal/console/lifetimes_recovery.go| index c3d9aed5e..9cfbdeb0f 100644 |
| --- a/internal/console/lifetimes_recovery.go |
| +++ b/internal/console/lifetimes_recovery.go |
| @@ -199,13 +199,13 @@ func (s *Server) recoverAllocationLocked(ctx context.Context, a Allocation) { |
| if err := s.allocPrevOwnerCleanLocked(ctx, a); err != nil { |
| return |
| } |
| - _, _ = s.allocRecordLocked(ctx, a) |
| + _, _ = s.allocRecordLocked(ctx, a, false) |
| return |
| case ours: |
| if err := s.allocPrevOwnerCleanLocked(ctx, a); err != nil { |
| return |
| } |
| - _, _ = s.allocRecordLocked(ctx, a) |
| + _, _ = s.allocRecordLocked(ctx, a, false) |
| return |
| case (slot == nil && a.PredecessorETag == "") || (slot != nil && obs.SlotETag == a.PredecessorETag): |
| if err := s.allocSlotLocked(ctx, a); err != nil { |
diff --git a/internal/console/regioncandidates.go b/internal/console/regioncandidates.go| index 4eec3cad0..cb50d8099 100644 |
| --- a/internal/console/regioncandidates.go |
| +++ b/internal/console/regioncandidates.go |
| @@ -195,7 +195,17 @@ func regionCandidates(snap edgesSnapshot, homeName, expectedFP string) []regionC |
| // readEdgesSnapshot marks no box fresh, so every coded region would read |
| // as absent. |
| func (s *Server) regionCands(snap edgesSnapshot) []regionCandidate { |
| - return regionCandidates(snap, s.cfg.HomeRegion, s.expectedSecretsFP()) |
| + cands := regionCandidates(snap, s.cfg.HomeRegion, s.expectedSecretsFP()) |
| + // Once the hostname history is active, a region complete did not |
| + // examine is no automatic choice (nearest-region never-reuse spec §3). |
| + if st := s.hostsCached(); st.Mode == provision.HostsModeActive { |
| + for i := range cands { |
| + if !cands[i].Home && !regionExamined(st, cands[i].Code) { |
| + cands[i].Eligible = false |
| + } |
| + } |
| + } |
| + return cands |
| } |
| // liveEdges is the one read every automatic-eligibility caller makes: the |
diff --git a/internal/console/regionclaim_test.go b/internal/console/regionclaim_test.go| index a54c7ae95..771eaf72a 100644 |
| --- a/internal/console/regionclaim_test.go |
| +++ b/internal/console/regionclaim_test.go |
| @@ -20,6 +20,7 @@ func regionFixture(t *testing.T) (*consoleFixture, string) { |
| t.Helper() |
| fx := newConsoleFixture(t) |
| fx.srv.cfg.AppRegions, fx.srv.cfg.HomeRegion, fx.srv.cfg.SecretsPub = true, "ie", testKeyPub |
| + historyActive(fx.srv) |
| setEdges(t, fx, map[string]string{"ie-box": homeBox, "uk-box": ukEligible}) |
| return fx, cliToken(t, fx, "paul@keymail.dev", "code-region-claim") |
| } |
diff --git a/internal/console/regionconfig.go b/internal/console/regionconfig.go| index 90be4c12c..015260c6c 100644 |
| --- a/internal/console/regionconfig.go |
| +++ b/internal/console/regionconfig.go |
| @@ -6,9 +6,11 @@ import ( |
| "github.com/carlosframework/platform/internal/appconfig" |
| ) |
| -// appRegionsOn is spec §5.6: the switch AND a named home. |
| +// appRegionsOn is spec §5.6: the switch AND a named home, and (the |
| +// nearest-region never-reuse spec §4) the hostname history active. Until |
| +// then the switch has no effect, and LoadHostsMode says so once. |
| func (s *Server) appRegionsOn() bool { |
| - return s.cfg.AppRegions && s.cfg.HomeRegion != "" |
| + return s.cfg.AppRegions && s.cfg.HomeRegion != "" && s.hostsActive() |
| } |
| // expectedSecretsFP is the fingerprint a box must publish to receive |
diff --git a/internal/console/regionconfig_test.go b/internal/console/regionconfig_test.go| index 9d4a714b7..39ce9ab84 100644 |
| --- a/internal/console/regionconfig_test.go |
| +++ b/internal/console/regionconfig_test.go |
| @@ -24,6 +24,7 @@ func mustTestSecretsKey() (pubB64, fp string) { |
| func TestAppRegionsOnNeedsANamedHome(t *testing.T) { |
| fx := newConsoleFixture(t) |
| + historyActive(fx.srv) |
| for _, c := range []struct { |
| on bool |
| home string |
diff --git a/internal/console/regiondefault_test.go b/internal/console/regiondefault_test.go| index 0c3295b72..c8d304027 100644 |
| --- a/internal/console/regiondefault_test.go |
| +++ b/internal/console/regiondefault_test.go |
| @@ -373,6 +373,7 @@ func TestInstancesTabRegionLines(t *testing.T) { |
| fx, _, _ := fillFixture(t, "uk") |
| readNames(fx) |
| fx.srv.cfg.AppRegions = true |
| + historyActive(fx.srv) |
| body := page(fx) |
| if !strings.Contains(body, starts) { |
| t.Fatal("no C7 line for an available region") |
diff --git a/internal/console/regionlabels_test.go b/internal/console/regionlabels_test.go| index b879382b5..7c63ef4e9 100644 |
| --- a/internal/console/regionlabels_test.go |
| +++ b/internal/console/regionlabels_test.go |
| @@ -283,6 +283,7 @@ func TestActivityCreateLineNamesTheLabel(t *testing.T) { |
| tb.setUp(t, false) |
| publishRegionEdges(t, tb) |
| tb.fx.srv.cfg.AppRegions = true |
| + historyActive(tb.fx.srv) |
| c, csrf := signInAs(t, tb.fx, "paul@keymail.dev", "code-labels-create") |
| status, _, _ := postForm(t, c, tb.fx.ts.URL+"/a/"+tb.sqid+"/apps/new", |
| url.Values{"csrf": {csrf}, "name": {"cart"}, "region": {"uk"}}) |
diff --git a/internal/provision/nearest_region_b_census_test.go b/internal/provision/nearest_region_b_census_test.go| index b28234ecb..721a896ca 100644 |
| --- a/internal/provision/nearest_region_b_census_test.go |
| +++ b/internal/provision/nearest_region_b_census_test.go |
| @@ -25,6 +25,12 @@ package provision |
| // - Server.putHostsListing (console), new: Puts one imported listing at |
| // control/hosts-used-window/<target>.json, on the ETag it read. No |
| // record key or body: nonrecord. |
| +// - Server.allocRecordLocked, re-pinned (Task 7): a recovery replay of a |
| +// data-kind allocation marks the hostname first, or requires the mark |
| +// once active (recoveryMark); the door's own call skips it. Its |
| +// create-only WriteRecord is unchanged. |
| +// - Server.createRecordWithLifetimeLocked, re-pinned: passes doorMarked |
| +// to allocRecordLocked. Same sites: still key-site. |
| // - Server.registerCLIRoutes, re-pinned: the window's doors. Same |
| // literals: still key-site. |
| func nearestRegionBWriteCensusInventory() []censusEntry { |
| @@ -52,6 +58,8 @@ func nearestRegionBWriteCensusInventory() []censusEntry { |
| {"internal/provision/hostsused_map.go", "HostsFromBoxListing", "key-site", "lit:instances", "ba7e6529c3820e3bc16dd215734cc6521cea12bd0ba0ab540ffeba888b550f69"}, |
| {"internal/console/apiinstancemove.go", "Server.handleAPIInstanceMoveRequest", "record-writer", "key:SetRecordMove,lit:instances", "7366c131cf6643449687eac2e56e55b5b55c51434b00123c339bb66067f3d413"}, |
| {"internal/console/fleets.go", "Server.placeAppTarget", "record-writer", "key:RecordsPrefix,key:SetRecordRegion", "e9fe8c1b6cddba8902c269f2358ab3394edbb78d8fe9cab57c3ba5918d1e29e0"}, |
| + {"internal/console/lifetimes_create.go", "Server.allocRecordLocked", "record-writer", "key:RecordKey,key:WriteRecord", "302a206cc99aff175e7fe59e8d63c7d25424adad16cfef64f315fce5d19401f4"}, |
| + {"internal/console/lifetimes_create.go", "Server.createRecordWithLifetimeLocked", "key-site", "key:RecordKey", "3cf4ed6b5d4f4abef3dc25e6fc98c42dd10dfa9bc1073c19ff152ed66d4b7774"}, |
| {"internal/console/authcli.go", "Server.registerCLIRoutes", "key-site", "lit:instances,lit:sidecars", "7916f9029b545af12934863b35e00db8e92d65debc84c3cc54002e41d9944ba8"}, |
| } |
| for _, r := range replacements { |