carlos / platform Public

nearest-region-b: whole-branch r1 fixes (Paul's rulings on #404)

accounts migrate never creates a data-kind record, in any mode, and
refuses such a plan before writing (S6). Once active, a fleet the history
recorded refuses add-box and reactivation (N9). Every data-kind create
passes gateDataCreate before its mark: S5 before the start-up check
(seed and import included), S4 on an unexamined or closed target or one
whose targets grew since completion. The serve lock fails closed on any
error and roster takes it; placement refuses an unreadable mode; a
platform-suffixed box file marks its stem's prefixes. Approved copy
applied; censuses re-proposed.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev bfdb7368224c3858deaf08e7cfd4f36b86ba8f09 parent deedadd
28 files changed, +832 −239
  • README.md +8 −3
  • accounts.go +8 −5
  • accounts_hostsused.go +65 −59
  • accounts_record_sequence_test.go +92 −83
  • cmd/console/hostsused.go +4 −2
  • cmd/console/main.go +10 −7
  • cmd/console/servelock_test.go +93 −15
  • cmd/console/servelock_unix.go +10 −1
  • cmd/console/servelock_windows.go +2 −1
  • docs/superpowers/notes/census-proposal-nearest-region-b.md +2 −2
  • docs/superpowers/notes/copy/nearest-region-never-reuse-b.md +30 −0
  • docs/superpowers/plans/2026-10-26-nearest-region-never-reuse.md +2 −0
  • docs/superpowers/specs/2026-10-26-nearest-region-without-claims-design.md +3 −1
  • internal/console/fleets.go +16 −2
  • internal/console/fleets_place_cut_test.go +15 −0
  • internal/console/hostsused.go +116 −6
  • internal/console/hostsused_activate.go +39 −20
  • internal/console/hostsused_activate_test.go +11 −0
  • internal/console/hostsused_active_test.go +24 −2
  • internal/console/hostsused_coverage_test.go +208 −0
  • internal/console/hostsused_writers_test.go +1 −0
  • internal/console/lifetimes_create.go +6 −3
  • internal/layout/hostsused.go +21 −11
  • internal/layout/hostsused_test.go +23 −0
  • internal/provision/nearest_region_b_census_test.go +17 −10
  • internal/provision/testdata/plan14-root-reads-chain.tsv +1 −1
  • internal/provision/testdata/plan14-root-reads-nearest-region-b.tsv +4 −4
  • system.go +1 −1
diff --git a/README.md b/README.md
index 01ac8bcff..2e2128fc4 100644
--- a/README.md
+++ b/README.md
@@ -221,7 +221,9 @@ once both deployments were migrated). Moving an app is a verb:
carlos accounts migrate --app kass --to <sqid>
console migrate-app --app kass --to <sqid> # on the console's box
-It copies the objects and re-stamps the app's routes. The console keeps its
+It copies the objects and re-stamps the app's routes. It moves static sites
+and services only. An app with an instance or sidecar that holds data is
+refused before anything is copied. The console keeps its
own app→account row — console state is the console's authority, and the
carlos binary deliberately never opens its database — so `console
migrate-app` completes the move; `carlos accounts migrate` prints that exact
@@ -374,10 +376,13 @@ while it is stopped.
history covers every record. Until that check passes, new instances
are refused and app regions stay off.
-There are two limits. A deployment runs one console process: `console
+There are three limits. A deployment runs one console process: `console
serve` holds a lock beside its database, and a second process refuses to
start. A region or fleet added after completion takes no new instances
-until the history is completed again.
+until the history is completed again. The same is true for a region that
+a new box joins. A fleet in the history takes no new box. To grow a fleet,
+stop the console, run `console hosts-used invalidate`, start the console,
+add the box, then complete the history again.
**The history's floor.** Completing writes the floor to
`control/hosts-used/@floor`. The floor is the release that completed the
diff --git a/accounts.go b/accounts.go
index b3b41134d..fe4842cac 100644
--- a/accounts.go
+++ b/accounts.go
@@ -339,11 +339,9 @@ func runAccountsMigrate(args []string) {
log.Fatalf("accounts migrate: %q is not an account sqid", *to)
}
// The hostname history (accounts_hostsused.go): the floor before any
- // write (opening the registry migrates its schema), and the mode every
- // record copy is checked against.
+ // write (opening the registry migrates its schema).
histStore := openStore()
- history, err := readMigrationHistoryNow(context.Background(), histStore)
- if err != nil {
+ if err := checkMigrationFloorNow(context.Background(), histStore); err != nil {
log.Fatal(err)
}
r, err := registry.Open(*regPath)
@@ -371,6 +369,11 @@ func runAccountsMigrate(args []string) {
if err := validateMigrationRecords(ctx, store, plan); err != nil {
log.Fatal(err)
}
+ // No data-kind record is created (accounts_hostsused.go): a plan that
+ // would create one refuses before anything is written.
+ if err := refuseDataRecords(ctx, store, plan); err != nil {
+ log.Fatal(err)
+ }
if len(plan) == 0 {
mutedf(os.Stdout, "nothing under %s — nothing to copy\n", release.AppPrefix(srcAcct, *app))
}
@@ -435,7 +438,7 @@ func runAccountsMigrate(args []string) {
}
continue
}
- copied, err := copyMigrationRecord(ctx, store, history, c.to, body)
+ copied, err := copyMigrationRecord(ctx, store, c.to, body)
if err != nil {
log.Fatal(err)
}
diff --git a/accounts_hostsused.go b/accounts_hostsused.go
index f3d188239..5992f2612 100644
--- a/accounts_hostsused.go
+++ b/accounts_hostsused.go
@@ -8,7 +8,6 @@ import (
"os"
"runtime/debug"
"strings"
- "time"
"github.com/carlosframework/platform/internal/provision"
"github.com/carlosframework/platform/internal/release"
@@ -16,37 +15,35 @@ import (
)
// The hostname history at carlos accounts migrate (nearest-region
-// never-reuse spec §2 and §4, plan Task 10). The verb copies an app's
-// records under another account, so it is a record writer: before the
-// history is active a data-kind record's copy marks its hostname first;
-// once the window has opened it never creates a data-kind record at a
-// destination that has none, because a re-run after the destination was
-// deleted would bring a deleted hostname back over its old data (S6). And
-// a carlos below the history's floor refuses before writing anything.
+// never-reuse spec §2 and §4, plan Task 10; Paul's ruling on #404). The verb
+// copies an app's objects under another account, and it never creates a
+// data-kind record (an instance that is not static or service, or any
+// sidecar), in any mode: a copy is a create the console's admission never
+// sees, and a re-run after the destination was deleted would bring a
+// deleted hostname back over its old data. No legacy app with data is left
+// to move. An identical destination is already copied, a different one is
+// the verb's own refusal; static sites, services and every other object
+// copy as before. A carlos below the history's floor refuses before
+// writing anything.
-// migrationHistory is what the verb read before its first write.
-type migrationHistory struct {
- mode string
+// msgMigrateHoldsData is S6: a data-kind record the verb will not create.
+func msgMigrateHoldsData(name string) string {
+ return name + ": not migrated. carlos accounts migrate doesn't move an instance that holds data."
}
-// readMigrationHistory reads the history's mode and floor once, and refuses
-// a build below the floor (B10). A build is at or above it when both are
-// release tags and this one is not older, or when it is the floor's own
-// commit; anything else (a dev build, a bare commit) cannot show it is, and
-// refuses.
-func readMigrationHistory(ctx context.Context, store release.Store, build, commit string) (*migrationHistory, error) {
+// checkMigrationFloor reads the history's floor and refuses a build below
+// it (B10). A build is at or above it when both are release tags and this
+// one is not older, or when it is the floor's own commit; anything else (a
+// dev build, a bare commit) cannot show it is, and refuses.
+func checkMigrationFloor(ctx context.Context, store release.Store, build, commit string) error {
floor, _, err := provision.ReadHostsFloor(ctx, store)
if err != nil {
- return nil, fmt.Errorf("accounts migrate: read the hostname history's floor: %w", err)
+ return fmt.Errorf("accounts migrate: read the hostname history's floor: %w", err)
}
if floor != nil && !buildMeetsFloor(*floor, build, commit) {
- return nil, errors.New("this carlos is older than the hostname history's floor, " + floor.Version + ". update carlos, then run it again.")
+ return errors.New("this carlos is older than the hostname history's floor, " + floor.Version + ". update carlos, then run it again.")
}
- mode, _, err := provision.ReadHostsMode(ctx, store)
- if err != nil {
- return nil, fmt.Errorf("accounts migrate: read the hostname history's mode: %w", err)
- }
- return &migrationHistory{mode: mode}, nil
+ return nil
}
func buildMeetsFloor(floor provision.HostsFloor, build, commit string) bool {
@@ -68,9 +65,9 @@ func thisBuildCommit() string {
return ""
}
-// readMigrationHistoryNow is readMigrationHistory for this build.
-func readMigrationHistoryNow(ctx context.Context, store release.Store) (*migrationHistory, error) {
- return readMigrationHistory(ctx, store, version.Build, thisBuildCommit())
+// checkMigrationFloorNow is checkMigrationFloor for this build.
+func checkMigrationFloorNow(ctx context.Context, store release.Store) error {
+ return checkMigrationFloor(ctx, store, version.Build, thisBuildCommit())
}
// migrationRecordHost is a record key's hostname and whether the record is a
@@ -98,18 +95,15 @@ func migrationRecordHost(key string, body []byte) (host string, data, ok bool) {
}
// errAlreadyCopied is a data-kind record whose identical copy is already at
-// its destination once the history exists: nothing is written.
+// its destination: nothing is written.
var errAlreadyCopied = errors.New("already copied")
-// beforeRecord is the check before a record key is copied to key. Exempt
-// kinds and other objects pass. Before the history is active, a data kind's
-// hostname is marked create-only (a mark already there passes) and the copy
-// goes ahead. Once the history exists (active or invalidated) the verb never
-// writes a data-kind record: an absent destination is S6, an identical one
-// is errAlreadyCopied, and a different one is left to the verb's own
-// refusal, which also writes nothing. No write follows a check that could
-// go stale, so a record deleted meanwhile is never recreated.
-func (h *migrationHistory) beforeRecord(ctx context.Context, store release.Store, key string, body []byte) error {
+// beforeRecord is the check before an object is copied to key. Objects that
+// are not records, and exempt kinds, pass. A data-kind record is never
+// written: an absent destination is S6, an identical one is
+// errAlreadyCopied, and a different one is the verb's own refusal, which
+// also writes nothing.
+func beforeRecord(ctx context.Context, store release.Store, key string, body []byte) error {
if !provision.IsRecordKey(key) {
return nil
}
@@ -117,35 +111,47 @@ func (h *migrationHistory) beforeRecord(ctx context.Context, store release.Store
if !data {
return nil
}
- if h.mode != provision.HostsModeIncomplete {
- cur, _, err := store.Get(ctx, key)
- switch {
- case errors.Is(err, os.ErrNotExist):
- name := host
- if !ok {
- name = key
- }
- return errors.New(name + ": not migrated. Its destination record is gone, and recreating it would reuse a hostname that held data.")
- case err != nil:
- return err
- case string(cur) == string(body):
- return errAlreadyCopied
+ cur, _, err := store.Get(ctx, key)
+ switch {
+ case errors.Is(err, os.ErrNotExist):
+ name := host
+ if !ok {
+ name = key
}
- return fmt.Errorf("accounts migrate: %s already exists with different content — refusing to\n"+
- "overwrite it. Nothing has been deleted; work out which of the two is the real one before going further.", key)
+ return errors.New(msgMigrateHoldsData(name))
+ case err != nil:
+ return err
+ case string(cur) == string(body):
+ return errAlreadyCopied
}
- if !ok {
- return fmt.Errorf("accounts migrate: %s names no hostname, so its copy cannot be recorded", key)
+ return fmt.Errorf("accounts migrate: %s already exists with different content — refusing to\n"+
+ "overwrite it. Nothing has been deleted; work out which of the two is the real one before going further.", key)
+}
+
+// refuseDataRecords is beforeRecord over the whole plan, before the verb
+// writes anything (a dry run included): a plan with a data-kind record it
+// would have to create refuses outright, rather than stopping half way.
+func refuseDataRecords(ctx context.Context, store release.Store, plan []copyOp) error {
+ for _, c := range plan {
+ if c.pointer || !provision.IsRecordKey(c.to) {
+ continue
+ }
+ body, _, err := store.Get(ctx, c.from)
+ if err != nil {
+ return fmt.Errorf("accounts migrate: read %s: %w", c.from, err)
+ }
+ if err := beforeRecord(ctx, store, c.to, body); err != nil && !errors.Is(err, errAlreadyCopied) {
+ return err
+ }
}
- _, err := provision.MarkHostUsed(ctx, store, provision.HostUse{Host: host, Kind: "instance", Source: "accounts migrate", At: time.Now().UTC()})
- return err
+ return nil
}
// copyMigrationRecord is the verb's step for one non-pointer object: the
-// history's check, then the create-only copy. copied is false for an object
+// check (beforeRecord), then the create-only copy. copied is false for an object
// already at its destination with the same bytes.
-func copyMigrationRecord(ctx context.Context, store release.Store, h *migrationHistory, key string, body []byte) (copied bool, err error) {
- if err := h.beforeRecord(ctx, store, key, body); errors.Is(err, errAlreadyCopied) {
+func copyMigrationRecord(ctx context.Context, store release.Store, key string, body []byte) (copied bool, err error) {
+ if err := beforeRecord(ctx, store, key, body); errors.Is(err, errAlreadyCopied) {
return false, nil
} else if err != nil {
return false, err
diff --git a/accounts_record_sequence_test.go b/accounts_record_sequence_test.go
index ea7f5582c..a1696343a 100644
--- a/accounts_record_sequence_test.go
+++ b/accounts_record_sequence_test.go
@@ -110,10 +110,11 @@ func TestPlan9M1MigrationToleratesBodiesMainCopied(t *testing.T) {
}
// The hostname history at carlos accounts migrate (nearest-region
-// never-reuse plan, Task 10; spec §2): before the history is active a
-// data-kind record's copy marks its hostname first; after, the verb never
-// creates a data-kind record at an absent destination (S6), and a carlos
-// below the history's floor refuses before any write.
+// never-reuse plan, Task 10; spec §2; Paul's ruling on #404): the verb never
+// creates a data-kind record, in any mode, and refuses a plan that would
+// before writing anything (S6); an identical destination is already
+// copied; static sites, services and other objects copy as before; and a
+// carlos below the history's floor refuses before any write.
func migrateRecordBody(host, kind string, incarnation bool) []byte {
b := `{"schema":1,"host":"` + host + `","slug":"x","app":"app","account":"cac","channel":"stable","created_at":"2026-10-26T09:00:00Z"`
@@ -137,43 +138,31 @@ func setHistory(t *testing.T, store release.Store, mode string) {
}
}
-// migrateOne is the verb's record step (copyMigrationRecord), with the
-// history read as the verb reads it.
-func migrateOne(t *testing.T, store release.Store, key string, body []byte) error {
- t.Helper()
- ctx := context.Background()
- h, err := readMigrationHistory(ctx, store, "v9.9.9", "")
- if err != nil {
- return err
- }
- _, err = copyMigrationRecord(ctx, store, h, key, body)
- return err
-}
+const sidecarBody = `{"schema":1,"name":"bot","host":"bot.app.cac.sidecar.internal","app":"app","account":"cac","channel":"stable"}`
-func TestMigrateRefusesResurrection(t *testing.T) {
- for _, incarnation := range []bool{false, true} {
- store := release.NewDirStore(t.TempDir())
- ctx := context.Background()
- key := provision.RecordKey("cac", "app", "shop.example.com")
- body := migrateRecordBody("shop.example.com", "", incarnation)
- if err := migrateOne(t, store, key, body); err != nil {
- t.Fatal(err)
- }
- setHistory(t, store, provision.HostsModeActive)
- if err := store.Delete(ctx, key); err != nil {
- t.Fatal(err)
+// TestMigrateNeverCreatesDataRecords: with no history and in every mode, an
+// instance record (with or without an incarnation) or a sidecar is not
+// created at an absent destination, and nothing is written.
+func TestMigrateNeverCreatesDataRecords(t *testing.T) {
+ for _, mode := range []string{"", provision.HostsModeIncomplete, provision.HostsModeActive, provision.HostsModeInvalidated} {
+ inner := release.NewDirStore(t.TempDir())
+ if mode != "" {
+ setHistory(t, inner, mode)
}
- err := migrateOne(t, store, key, body)
- if err == nil || err.Error() != "shop.example.com: not migrated. Its destination record is gone, and recreating it would reuse a hostname that held data." {
- t.Fatalf("migrate again over a deleted record = %v, want S6", err)
+ store := &orderStore{Store: inner}
+ for _, incarnation := range []bool{false, true} {
+ key := provision.RecordKey("cac", "app", "shop.example.com")
+ _, err := copyMigrationRecord(context.Background(), store, key, migrateRecordBody("shop.example.com", "", incarnation))
+ if err == nil || err.Error() != "shop.example.com: not migrated. carlos accounts migrate doesn't move an instance that holds data." {
+ t.Fatalf("mode %q: an instance record = %v, want S6", mode, err)
+ }
}
- if _, _, err := store.Get(ctx, key); !errors.Is(err, os.ErrNotExist) {
- t.Fatalf("the refused migrate wrote: %v", err)
+ if _, err := copyMigrationRecord(context.Background(), store, provision.SidecarRecordKey("cac", "app", "bot"), []byte(sidecarBody)); err == nil ||
+ !strings.HasPrefix(err.Error(), "bot.app.cac.sidecar.internal: not migrated.") {
+ t.Fatalf("mode %q: a sidecar record = %v, want S6", mode, err)
}
- // Sidecars too, by the host in the body.
- sk := provision.SidecarRecordKey("cac", "app", "bot")
- if err := migrateOne(t, store, sk, []byte(`{"schema":1,"name":"bot","host":"bot.app.cac.sidecar.internal","app":"app","account":"cac","channel":"stable"}`)); err == nil {
- t.Fatal("a sidecar record was created at an absent destination once active")
+ if len(store.puts) != 0 {
+ t.Fatalf("mode %q: puts = %v, want none", mode, store.puts)
}
}
}
@@ -182,21 +171,75 @@ func TestMigrateIdenticalDestinationPasses(t *testing.T) {
inner := release.NewDirStore(t.TempDir())
key := provision.RecordKey("cac", "app", "shop.example.com")
body := migrateRecordBody("shop.example.com", "", false)
- if err := migrateOne(t, inner, key, body); err != nil {
+ if _, err := inner.Put(context.Background(), key, body, ""); err != nil {
t.Fatal(err)
}
- setHistory(t, inner, provision.HostsModeActive)
store := &orderStore{Store: inner}
- if err := migrateOne(t, store, key, body); err != nil {
- t.Fatalf("an identical present destination = %v, want it to pass", err)
+ if copied, err := copyMigrationRecord(context.Background(), store, key, body); err != nil || copied {
+ t.Fatalf("an identical present destination = %v %v, want already copied", copied, err)
+ }
+ if _, err := copyMigrationRecord(context.Background(), store, key, migrateRecordBody("shop.example.com", "", true)); err == nil || !strings.Contains(err.Error(), "already exists with different content") {
+ t.Fatalf("a different present destination = %v, want the verb's refusal", err)
}
- // Once the history exists, a data-kind record is never written: a
- // delete between the check and a write could not resurrect it.
if len(store.puts) != 0 {
- t.Fatalf("puts once active = %v, want none", store.puts)
+ t.Fatalf("puts = %v, want none", store.puts)
}
- if err := migrateOne(t, store, key, migrateRecordBody("shop.example.com", "", true)); err == nil || !strings.Contains(err.Error(), "already exists with different content") {
- t.Fatalf("a different present destination = %v, want the verb's refusal", err)
+}
+
+// TestMigrateUnrelatedObjectsPass: a channel pointer, a static record and
+// a service record copy, with no mark.
+func TestMigrateUnrelatedObjectsPass(t *testing.T) {
+ store := &orderStore{Store: release.NewDirStore(t.TempDir())}
+ setHistory(t, store.Store, provision.HostsModeActive)
+ for key, body := range map[string][]byte{
+ "apps/cac/app/channel.json": []byte(`{"v":1}`),
+ provision.RecordKey("cac", "app", "site.example.com"): migrateRecordBody("site.example.com", "static", false),
+ provision.RecordKey("cac", "app", "svc.example.com"): migrateRecordBody("svc.example.com", "service", false),
+ } {
+ store.puts = nil
+ if copied, err := copyMigrationRecord(context.Background(), store, key, body); err != nil || !copied {
+ t.Fatalf("%s = %v %v, want it copied", key, copied, err)
+ }
+ if len(store.puts) != 1 || store.puts[0] != key {
+ t.Fatalf("%s put %v, want the object alone", key, store.puts)
+ }
+ }
+}
+
+// TestMigratePlanWithDataRefusesBeforeWriting: the verb's plan for an app
+// with a static site and an instance that holds data refuses (S6) before
+// anything is copied, the static record and the pointer included.
+func TestMigratePlanWithDataRefusesBeforeWriting(t *testing.T) {
+ inner := release.NewDirStore(t.TempDir())
+ ctx := context.Background()
+ for key, body := range map[string][]byte{
+ "apps/cac/shop/channels/stable.json": []byte(`{"v":1}`),
+ provision.RecordKey("cac", "shop", "site.example.com"): migrateRecordBody("site.example.com", "static", false),
+ provision.RecordKey("cac", "shop", "shop.example.com"): migrateRecordBody("shop.example.com", "", false),
+ } {
+ if _, err := inner.Put(ctx, key, body, ""); err != nil {
+ t.Fatal(err)
+ }
+ }
+ store := &orderStore{Store: inner}
+ plan, _, _ := migrationPlan(ctx, store, "shop", "cac", "bab", release.AppPrefix("bab", "shop"))
+ if len(plan) < 3 {
+ t.Fatalf("plan = %+v, want the three objects", plan)
+ }
+ err := refuseDataRecords(ctx, store, plan)
+ if err == nil || err.Error() != "shop.example.com: not migrated. carlos accounts migrate doesn't move an instance that holds data." {
+ t.Fatalf("plan with an instance = %v, want S6", err)
+ }
+ if len(store.puts) != 0 {
+ t.Fatalf("puts = %v, want none", store.puts)
+ }
+ // Without the instance the plan passes.
+ if err := inner.Delete(ctx, provision.RecordKey("cac", "shop", "shop.example.com")); err != nil {
+ t.Fatal(err)
+ }
+ plan, _, _ = migrationPlan(ctx, store, "shop", "cac", "bab", release.AppPrefix("bab", "shop"))
+ if err := refuseDataRecords(ctx, store, plan); err != nil {
+ t.Fatalf("plan with a static site alone = %v, want it to pass", err)
}
}
@@ -219,40 +262,6 @@ func TestMigrateFloorPrecedesTheRegistry(t *testing.T) {
}
}
-func TestMigrateUnrelatedObjectsPass(t *testing.T) {
- store := release.NewDirStore(t.TempDir())
- setHistory(t, store, provision.HostsModeActive)
- for key, body := range map[string][]byte{
- "apps/cac/app/channel.json": []byte(`{"v":1}`),
- provision.RecordKey("cac", "app", "site.example.com"): migrateRecordBody("site.example.com", "static", false),
- provision.RecordKey("cac", "app", "svc.example.com"): migrateRecordBody("svc.example.com", "service", false),
- } {
- if err := migrateOne(t, store, key, body); err != nil {
- t.Fatalf("%s once active = %v, want it copied", key, err)
- }
- }
-}
-
-func TestMigrateMarksBeforeCopy(t *testing.T) {
- store := &orderStore{Store: release.NewDirStore(t.TempDir())}
- key := provision.RecordKey("cac", "app", "shop.example.com")
- if err := migrateOne(t, store, key, migrateRecordBody("shop.example.com", "", false)); err != nil {
- t.Fatal(err)
- }
- mark := provision.HostsUsedKey("shop.example.com")
- if len(store.puts) < 2 || store.puts[0] != mark || store.puts[1] != key {
- t.Fatalf("puts = %v, want the mark before the record", store.puts)
- }
- // Static records do not mark.
- store.puts = nil
- if err := migrateOne(t, store, provision.RecordKey("cac", "app", "site.example.com"), migrateRecordBody("site.example.com", "static", false)); err != nil {
- t.Fatal(err)
- }
- if len(store.puts) != 1 {
- t.Fatalf("a static record's copy put %v, want the record alone", store.puts)
- }
-}
-
type orderStore struct {
release.Store
puts []string
@@ -266,7 +275,7 @@ func (s *orderStore) Put(ctx context.Context, key string, body []byte, ifMatch s
func TestCLIRefusesBelowFloor(t *testing.T) {
store := release.NewDirStore(t.TempDir())
ctx := context.Background()
- if _, err := readMigrationHistory(ctx, store, "v0.29.0", ""); err != nil {
+ if err := checkMigrationFloor(ctx, store, "v0.29.0", ""); err != nil {
t.Fatalf("no floor = %v, want allowed", err)
}
if _, err := provision.WriteHostsFloor(ctx, store, provision.HostsFloor{Version: "v0.30.0", Commit: "abc123"}, ""); err != nil {
@@ -274,12 +283,12 @@ func TestCLIRefusesBelowFloor(t *testing.T) {
}
want := "this carlos is older than the hostname history's floor, v0.30.0. update carlos, then run it again."
for _, build := range []struct{ version, commit string }{{"v0.29.0", ""}, {"dev", ""}, {"0123abc", "def456"}} {
- if _, err := readMigrationHistory(ctx, store, build.version, build.commit); err == nil || err.Error() != want {
+ if err := checkMigrationFloor(ctx, store, build.version, build.commit); err == nil || err.Error() != want {
t.Errorf("%+v below the floor = %v, want B10", build, err)
}
}
for _, build := range []struct{ version, commit string }{{"v0.30.0", ""}, {"v0.31.2", ""}, {"dev", "abc123"}} {
- if _, err := readMigrationHistory(ctx, store, build.version, build.commit); err != nil {
+ if err := checkMigrationFloor(ctx, store, build.version, build.commit); err != nil {
t.Errorf("%+v at or above the floor = %v, want allowed", build, err)
}
}
diff --git a/cmd/console/hostsused.go b/cmd/console/hostsused.go
index afa77c455..54e11929b 100644
--- a/cmd/console/hostsused.go
+++ b/cmd/console/hostsused.go
@@ -20,8 +20,8 @@ import (
// console hosts-used roster | activate | invalidate (nearest-region
// never-reuse; Paul's cut on #404): the hostname history is made active, and
// invalidated by an operator, offline, on the console's box with the
-// console stopped. activate and invalidate take the console's serve lock
-// (servelock_*.go) for their whole run, which `console serve` holds while
+// console stopped. roster, activate and invalidate take the console's serve
+// lock (servelock_*.go) for their whole run, which `console serve` holds while
// it serves, so they refuse while it runs and it cannot start under them.
// The approved rework strings (nearest-region-never-reuse-b.md, the rework list).
@@ -89,6 +89,8 @@ func runHostsUsed(args []string) {
if *out == "" || fs.NArg() != 0 {
usage()
}
+ lock := holdServeLock()
+ defer lock.Close()
a := console.HostsActivation{Releases: openStore(nil), Registry: envOr("CARLOS_REGISTRY", "/data/registry.db")}
r, err := a.Roster(ctx)
if err != nil {
diff --git a/cmd/console/main.go b/cmd/console/main.go
index 94ed457f0..7618c6ea5 100644
--- a/cmd/console/main.go
+++ b/cmd/console/main.go
@@ -311,14 +311,17 @@ func serve() {
// The serve lock (servelock_*.go), held for the life of the process:
// the offline hosts-used verbs need the console stopped, and refuse
// while this is held; a second console on this database refuses here.
- switch lock, err := takeServeLock(envOr("CONSOLE_DB", "/data/console/console.db")); {
- case errors.Is(err, errServeLockHeld):
- log.Fatalf(msgServeLockHeld, envOr("CONSOLE_DB", "/data/console/console.db")+".serve.lock")
- case err != nil:
- log.Printf("console: the serve lock: %v (serving without it)", err)
- default:
- defer lock.Close()
+ // Any error refuses: a console serving without the lock is one an
+ // offline verb could run under.
+ lockDB := envOr("CONSOLE_DB", "/data/console/console.db")
+ lock, err := takeServeLock(lockDB)
+ if errors.Is(err, errServeLockHeld) {
+ log.Fatalf(msgServeLockHeld, lockDB+".serve.lock")
+ }
+ if err != nil {
+ log.Fatalf("console: take the serve lock %s: %v", lockDB+".serve.lock", err)
}
+ defer lock.Close()
origin := strings.TrimSuffix(os.Getenv("CONSOLE_ORIGIN"), "/")
if origin == "" {
log.Fatal("set CONSOLE_ORIGIN (e.g. https://platform.carlosframework.com)")
diff --git a/cmd/console/servelock_test.go b/cmd/console/servelock_test.go
index cc426c3fb..ae34cc645 100644
--- a/cmd/console/servelock_test.go
+++ b/cmd/console/servelock_test.go
@@ -4,6 +4,7 @@ package main
import (
"errors"
+ "os"
"os/exec"
"path/filepath"
"strings"
@@ -36,31 +37,108 @@ func TestServeLockIsExclusive(t *testing.T) {
again.Close()
}
-// TestHostsUsedVerbsNeedTheConsoleStopped: the built binary's invalidate
-// refuses while the serve lock is held (a running console), and reaches the
-// history once it is free.
-func TestHostsUsedVerbsNeedTheConsoleStopped(t *testing.T) {
- dir := t.TempDir()
- bin := filepath.Join(dir, "console")
+// buildConsole builds this binary once per test.
+func buildConsole(t *testing.T) (bin, dir string) {
+ t.Helper()
+ dir = t.TempDir()
+ bin = filepath.Join(dir, "console")
if out, err := exec.Command("go", "build", "-o", bin, ".").CombinedOutput(); err != nil {
t.Fatalf("build: %v\n%s", err, out)
}
+ return bin, dir
+}
+
+// runConsole runs the built binary with a deployment directory, registry
+// and database under dir, and answers what it printed.
+func runConsole(t *testing.T, bin, dir, db string, args ...string) string {
+ t.Helper()
+ cmd := exec.Command(bin, args...)
+ cmd.Dir = dir
+ cmd.Env = []string{"CONSOLE_DB=" + db, "CARLOS_DEPLOYMENT_DIR=" + filepath.Join(dir, "bucket"),
+ "CARLOS_REGISTRY=" + filepath.Join(dir, "registry.db"), "HOME=" + dir}
+ out, _ := cmd.CombinedOutput()
+ return string(out)
+}
+
+// TestHostsUsedVerbsNeedTheConsoleStopped: through the built binary, every
+// hosts-used verb (roster, activate, invalidate) refuses while the serve
+// lock is held (a running console), and with it free the three run in
+// order: the roster is written, activation completes the history, and
+// invalidate invalidates it.
+func TestHostsUsedVerbsNeedTheConsoleStopped(t *testing.T) {
+ bin, dir := buildConsole(t)
db := filepath.Join(dir, "console.db")
- run := func() string {
- cmd := exec.Command(bin, "hosts-used", "invalidate")
- cmd.Env = []string{"CONSOLE_DB=" + db, "CARLOS_DEPLOYMENT_DIR=" + filepath.Join(dir, "bucket"), "CARLOS_REGISTRY=" + filepath.Join(dir, "registry.db"), "HOME=" + dir}
- out, _ := cmd.CombinedOutput()
- return string(out)
+ roster := filepath.Join(dir, "roster.json")
+ listings := filepath.Join(dir, "scan.jsonl")
+ if err := os.MkdirAll(filepath.Join(dir, "bucket"), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(listings, nil, 0o600); err != nil {
+ t.Fatal(err)
+ }
+ verbs := [][]string{
+ {"hosts-used", "roster", "-o", roster},
+ {"hosts-used", "activate", "-roster", roster, "-listings", listings},
+ {"hosts-used", "invalidate"},
}
lock, err := takeServeLock(db)
if err != nil {
t.Fatal(err)
}
- if out := run(); !strings.Contains(out, "the console is running. stop it, then run this again") {
- t.Fatalf("invalidate with the console running printed:\n%s", out)
+ for _, v := range verbs {
+ if out := runConsole(t, bin, dir, db, v...); !strings.Contains(out, "the console is running. stop it, then run this again") {
+ t.Fatalf("%v with the console running printed:\n%s", v, out)
+ }
+ }
+ if _, err := os.Stat(roster); !errors.Is(err, os.ErrNotExist) {
+ t.Fatalf("roster written while the console runs: %v", err)
}
lock.Close()
- if out := run(); !strings.Contains(out, "The hostname history is not active, so there is nothing to invalidate.") {
- t.Fatalf("invalidate with the console stopped printed:\n%s", out)
+ want := []string{
+ "roster written to " + roster + ": 0 targets to scan",
+ "the hostname history is complete. 0 hostnames recorded",
+ "the hostname history is invalidated. new instances are refused until a fresh inventory completes",
+ }
+ for i, v := range verbs {
+ if out := runConsole(t, bin, dir, db, v...); !strings.Contains(out, want[i]) {
+ t.Fatalf("%v with the console stopped printed:\n%s", v, out)
+ }
+ }
+}
+
+// TestServeRefusesWithoutTheLock: through the built binary, console serve
+// takes the lock before anything else, making the database's directory on
+// a fresh install; refuses while another process holds it; and refuses on
+// any other lock error rather than serving without it.
+func TestServeRefusesWithoutTheLock(t *testing.T) {
+ bin, dir := buildConsole(t)
+ // A fresh install: the directory does not exist. The lock is taken
+ // (the run goes on to the next check, CONSOLE_ORIGIN) and its file
+ // is there.
+ db := filepath.Join(dir, "fresh", "console", "console.db")
+ if out := runConsole(t, bin, dir, db, "serve"); !strings.Contains(out, "set CONSOLE_ORIGIN") {
+ t.Fatalf("serve on a fresh install printed:\n%s", out)
+ }
+ if _, err := os.Stat(db + ".serve.lock"); err != nil {
+ t.Fatalf("serve on a fresh install took no lock: %v", err)
+ }
+ // Held by another process: refused.
+ lock, err := takeServeLock(db)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if out := runConsole(t, bin, dir, db, "serve"); !strings.Contains(out, "another console, or a hosts-used command, holds "+db+".serve.lock") {
+ t.Fatalf("serve with the lock held printed:\n%s", out)
+ }
+ lock.Close()
+ // The lock cannot be taken at all (its directory is a file): refused,
+ // not served without it.
+ blocker := filepath.Join(dir, "blocker")
+ if err := os.WriteFile(blocker, nil, 0o600); err != nil {
+ t.Fatal(err)
+ }
+ out := runConsole(t, bin, dir, filepath.Join(blocker, "console.db"), "serve")
+ if !strings.Contains(out, "take the serve lock") || strings.Contains(out, "set CONSOLE_ORIGIN") {
+ t.Fatalf("serve with no lock possible printed:\n%s", out)
}
}
diff --git a/cmd/console/servelock_unix.go b/cmd/console/servelock_unix.go
index 8512f63f3..2925638da 100644
--- a/cmd/console/servelock_unix.go
+++ b/cmd/console/servelock_unix.go
@@ -5,6 +5,7 @@ package main
import (
"errors"
"os"
+ "path/filepath"
"syscall"
)
@@ -16,8 +17,16 @@ var errServeLockHeld = errors.New("held")
// and without waiting, and holds it for the life of the process (the kernel
// drops it when the process exits, so it is never stale). `console serve`
// holds it while it serves; the offline hosts-used verbs take it to prove
-// the console is stopped.
+// the console is stopped. The database's directory is made first, as
+// console.Open makes it, so a fresh install takes the lock too. Every
+// caller treats any error as a refusal: nothing serves, and no offline verb
+// runs, without the lock.
func takeServeLock(db string) (*os.File, error) {
+ if dir := filepath.Dir(db); dir != "." && dir != "" {
+ if err := os.MkdirAll(dir, 0o755); err != nil {
+ return nil, err
+ }
+ }
f, err := os.OpenFile(db+".serve.lock", os.O_CREATE|os.O_RDWR, 0o600)
if err != nil {
return nil, err
diff --git a/cmd/console/servelock_windows.go b/cmd/console/servelock_windows.go
index 1fe3fad25..c987d73d4 100644
--- a/cmd/console/servelock_windows.go
+++ b/cmd/console/servelock_windows.go
@@ -10,7 +10,8 @@ import (
var errServeLockHeld = errors.New("held")
// takeServeLock has no implementation on Windows, where the console is not
-// deployed: serving goes on without it, and the offline verbs refuse.
+// deployed: the console refuses to serve there, and the offline verbs
+// refuse, as they do on any lock error.
func takeServeLock(db string) (*os.File, error) {
return nil, errors.New("the serve lock is not supported on Windows")
}
diff --git a/docs/superpowers/notes/census-proposal-nearest-region-b.md b/docs/superpowers/notes/census-proposal-nearest-region-b.md
index ebadf340b..1dee9dfc0 100644
--- a/docs/superpowers/notes/census-proposal-nearest-region-b.md
+++ b/docs/superpowers/notes/census-proposal-nearest-region-b.md
@@ -4,7 +4,7 @@ Ruling `census-ruling-nearest-region-b`. The independent reviewer approves or re
| unit | change | read sites | what changed |
|---|---|---|---|
-| `accounts.go` `runAccountsMigrate` | body | unchanged (9) | reads the hostname history before it opens the registry (readMigrationHistoryNow: GETs control/hosts-used/@floor and @mode from the deployment store, the one store the verb uses) and refuses below the floor; each record copy goes through copyMigrationRecord, which GETs the destination key or Puts a create-only mark under control/hosts-used/ and, once the history exists, never writes a data-kind record; no new kind of read, no path or input a tenant, app or box agent can name |
+| `accounts.go` `runAccountsMigrate` | body | unchanged (9) | reads the hostname history's floor before it opens the registry (checkMigrationFloorNow: GETs control/hosts-used/@floor from the deployment store, the one store the verb uses) and refuses below it; before any write it reads each planned record's source and destination keys and refuses a plan that would create a data-kind record (refuseDataRecords), and each record copy checks the same again (copyMigrationRecord) and never writes a data-kind record; no marks, no new kind of read, no path or input a tenant, app or box agent can name |
Envelopes re-pinned: `.`, `internal/layout`, `internal/provision`.
@@ -14,6 +14,6 @@ Recorded dispositions, which each change must still satisfy:
- `accounts.go` `runAccountsMigrate`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=J1,J4;basis=route-and-input
-Seal: `ed0d770a827bdb37a87d21e5c8efb259ca0de88457b0cb3202ebb006fc0cd032` → `3e39f43fc130874481304fcb04b85f7455d360eb974acf4d7f344954e56cd8e3`.
+Seal: `ed0d770a827bdb37a87d21e5c8efb259ca0de88457b0cb3202ebb006fc0cd032` → `f4bd7800db64c0c353510a302f8ff9ce7b6d8c44d56c0f46cb6558fa63e2e14b`.
Overlay: `internal/provision/testdata/plan14-root-reads-nearest-region-b.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`.
diff --git a/docs/superpowers/notes/copy/nearest-region-never-reuse-b.md b/docs/superpowers/notes/copy/nearest-region-never-reuse-b.md
index 0de96c296..2d86d01ab 100644
--- a/docs/superpowers/notes/copy/nearest-region-never-reuse-b.md
+++ b/docs/superpowers/notes/copy/nearest-region-never-reuse-b.md
@@ -193,3 +193,33 @@ If any objects may have been dropped, stop the console, run `console
hosts-used invalidate`, and complete the history again.
(Pools no longer appear as roster targets, per the earlier copy question.)
+
+
+## Whole-branch round 1 fixes: approved copy
+
+approved by delegated Luna pass on Paul's standing rule, 2026-10-26. Apply verbatim; placeholders are in angle brackets.
+
+S6 (replaces S6; `carlos accounts migrate`, printed before anything is copied, and by the copy step if a destination vanished meanwhile):
+<host>: not migrated. carlos accounts migrate doesn't move an instance that holds data.
+
+N9 (`carlos fleets add-box` on a fleet the hostname history recorded, once active):
+Fleet <fleet> can't take another box yet. Ask the platform's operator to add the box.
+
+E3 (replaces E3; `carlos system` help for `hosts-used status`):
+the hostname history: its mode, how many hostnames it has
+recorded, its closed fleets and its floor
+
+README, "Bucket layout, and the migration", after "It copies the objects and re-stamps the app's routes.":
+It moves static sites and services only. An app with an instance or
+sidecar that holds data is refused before anything is copied.
+
+README, "The hostname history" (replaces the "Two limits" paragraph):
+There are three limits. A deployment runs one console process: `console
+serve` holds a lock beside its database, and a second process refuses to
+start. A region or fleet added after completion takes no new instances
+until the history is completed again. The same is true for a region that
+a new box joins. A fleet in the history takes no new box. To grow a fleet,
+stop the console, run `console hosts-used invalidate`, start the console,
+add the box, then complete the history again.
+
+Reused existing strings: placement with the mode unreadable answers "could not update this app's instances — try again"; add-box with the mode unreadable answers "could not add the box — try again"; a create whose targets grew answers S4, and one whose targets cannot be read, or before the start-up check passes (now at seed and import too), answers S5. S4's <target> for an unnamed home region is "the home region".
diff --git a/docs/superpowers/plans/2026-10-26-nearest-region-never-reuse.md b/docs/superpowers/plans/2026-10-26-nearest-region-never-reuse.md
index 0b708c2bd..8fd676a71 100644
--- a/docs/superpowers/plans/2026-10-26-nearest-region-never-reuse.md
+++ b/docs/superpowers/plans/2026-10-26-nearest-region-never-reuse.md
@@ -14,6 +14,8 @@
Merge B's live window (Tasks 5 and 6 as written below) is replaced by offline activation (spec §3b): `console hosts-used roster`, `activate` and `invalidate` on the console's box with the console stopped, proved by its serve lock. Task 5 shrinks to the start-up gate and the console's serve lock; Task 6's import, close-fleet and complete become the offline `activate` (roster compared in full, including each region's and fleet's targets); Task 7 keeps S1-S4 and recovery marking, with the invalidation latch taken under the admission lock before paging; Task 8 keeps the tripwire, now run before any create is served, and loses the online invalidate door; Task 10 never writes a data-kind record once the history exists. Round history: Task 5 r1-r3, Task 6 r1-r2, Task 7 r1-r2, Task 8 r1, Task 10 r1 (all NOT READY; findings under docs/superpowers/notes/reviews/). The reworked branch gets one whole-branch review, a new round for the parts that changed.
+Whole-branch round 1 (`ASTRA-FINDINGS-nearest-region-b-branch-r1.md`): NOT READY, five P1 and three P2; stopping rule 2 (Task 10's and Task 6's families again). Paul ruled on #404: Task 10 never creates a data-kind record in any mode, and an inventoried fleet refuses add-box and reactivation. The fixes (spec §3b, last paragraph) go to round 2 of the whole-branch review.
+
## Global Constraints
- The rule applies only with claims off (`cfg.HostClaim` false) and Phase 1 off (`CARLOS_MOVES_PHASE1`, moves/switch.go:6). `complete` refuses otherwise.
diff --git a/docs/superpowers/specs/2026-10-26-nearest-region-without-claims-design.md b/docs/superpowers/specs/2026-10-26-nearest-region-without-claims-design.md
index 4d470675d..973d04b27 100644
--- a/docs/superpowers/specs/2026-10-26-nearest-region-without-claims-design.md
+++ b/docs/superpowers/specs/2026-10-26-nearest-region-without-claims-design.md
@@ -33,7 +33,7 @@ Each writer first reads its own record and answers with the door's duplicate res
| lifetimes off: `CreateRecord` (apiinstances.go:1706), `createSeedRecord` (apiinstanceseed.go:87) | immediately before the write |
| sidecars, always the direct writer even with lifetimes on (`CreateSidecarRecord`, apisidecars.go:391) | immediately before the write |
| attach (domainattach.go:250, :675), deploy's first create (deploy.go:1023), temporary static sites | exempt: **no mark** |
-| `carlos accounts migrate` (accounts_record_sequence.go:17-40) | **cut:** after activation it refuses to create a data-kind record at an absent destination (S6). An identical present destination and unrelated objects still migrate. It retains its sources (accounts.go:69), so a re-run would resurrect a record |
+| `carlos accounts migrate` (accounts_record_sequence.go:17-40) | **cut:** it never creates a data-kind record, in any mode (S6, §3b). An identical present destination and unrelated objects still migrate. It retains its sources (accounts.go:69), so a re-run would otherwise resurrect a record |
| `internal/hostops` writers | claims-on only, unreachable with claims off (#404). A witness asserts that |
A successful mark followed by a failed write or a crash leaves the hostname refused for ever. That is accepted.
@@ -70,6 +70,8 @@ A one-time maintenance window wraps the inventory. It closes round 3's P1: a mar
The live window of §3a is cut. Its build (merge B) took Astra rounds that kept finding interleavings of one cause, the mode checked in one place and acted on in another: Task 5 r1-r3 (the drain, three times; budget spent), Task 6 r1-r2 (a fleet closure waiving an open target; stopping rule 2), Task 7 r1-r2 (a breach's creates; stopping rule 2), Task 8 r1, Task 10 r1 (findings under docs/superpowers/notes/reviews/). Activation and operator invalidation now run offline, on the console's box with the console stopped: `console hosts-used roster` lists what to scan; `console hosts-used activate` (holding the console's serve lock, a flock on `<CONSOLE_DB>.serve.lock` that `console serve` holds for its life, so it refuses while the console runs and the console cannot start under it) reads the console database directly, refuses on any pending lifetime row, any unfinished move or seed, a roster changed since it was taken (target names and each region's and fleet's targets), a missing, failed or unmappable listing, or claims or Phase 1 on, then marks, writes the floor and the active mode; `console hosts-used invalidate` is the operator's invalidation. There is no activating mode, no drain and no in-process counter. On start the console runs the tripwire before it serves a data-kind create; until it passes, data-kind creates are refused (S5) and the region switch stays off. `carlos accounts migrate` never writes a data-kind record once the history exists. Pools are no separate target: their boxes are on the roster through their edges files.
+**Round 1 of the reworked branch (Paul's rulings on #404, 2026-10-26).** `carlos accounts migrate` never creates a data-kind record, in any mode: a plan with one refuses before anything is written (S6), since no legacy app with data remains. Once active, a fleet the history recorded (examined or closed) takes no new or reactivated box (N9); growing it means invalidating, adding the box and completing the history again. Every data-kind create, at the one step each writer passes before its mark (`gateDataCreate`: the lifetimes-off record create, the sidecar create, the lifetime create), is refused while the start-up check has not passed (S5), on an unexamined or closed target (S4), and when the region's or fleet's targets now include one activation did not record (S4; a box that joins a region does so from infra, so the create is what is refused; targets that cannot be read refuse with S5). `console serve` refuses on any serve-lock error, `roster` takes the lock too, placement refuses when the mode cannot be read, and a box listing's platform-suffixed name marks every host-like prefix of its stem (`<host>.backup.db` marks `<host>`).
+
## 4. Modes and the floor
| Mode | Behaviour |
diff --git a/internal/console/fleets.go b/internal/console/fleets.go
index f427c2b3f..ddd77bde6 100644
--- a/internal/console/fleets.go
+++ b/internal/console/fleets.go
@@ -289,6 +289,14 @@ func (s *Server) handleAPIFleetAddBox(w http.ResponseWriter, r *http.Request) {
"invalid box label — 1-32 characters of a-z, 0-9 and hyphen")
return
}
+ // A fleet the hostname history recorded takes no new or reactivated
+ // box while it is active (N9, Paul's ruling on #404): the box was not
+ // scanned. AddFleetBox both adds and reactivates, so this one check
+ // covers both.
+ if ref := s.fleetGrowthRefusal(r.Context(), fleet.Name); ref != nil {
+ writeDoorRefusalJSON(w, r, ref)
+ return
+ }
plaintext, hash, err := mintFleetToken()
if err != nil {
log.Printf("console: fleet add-box %s/%s: mint token: %v", acct.Sqid, fleet.Name, err)
@@ -572,8 +580,14 @@ func (s *Server) placeAppTarget(ctx context.Context, acct *Account, app, target
// (nearest-region never-reuse spec §5): S3, before the temporary-app
// check, the registry or any write. A placement change on an existing
// app would move data under hostnames the history cannot follow.
- // Placement at app creation (carlos apps create --place) stays.
- if mode, err := s.hostsMode(ctx); err == nil && (mode == provision.HostsModeActive || mode == provision.HostsModeInvalidated) {
+ // Placement at app creation (carlos apps create --place) stays. A mode
+ // that cannot be read refuses too, as a failure to try again.
+ mode, err := s.hostsMode(ctx)
+ if err != nil {
+ log.Printf("console: hosts used: read the mode to place %s: %v", app, err)
+ return http.StatusServiceUnavailable, placeInstancesFailed
+ }
+ if mode == provision.HostsModeActive || mode == provision.HostsModeInvalidated {
return http.StatusConflict, msgPlacementFixed
}
// A temporary app stays on the shared fleet at its own platform address
diff --git a/internal/console/fleets_place_cut_test.go b/internal/console/fleets_place_cut_test.go
index 14fa6a135..4c49c71f7 100644
--- a/internal/console/fleets_place_cut_test.go
+++ b/internal/console/fleets_place_cut_test.go
@@ -67,4 +67,19 @@ func TestPlaceRefusedAfterActivation(t *testing.T) {
t.Fatalf("app create with --place once active = %d %v, want 200", status, out)
}
})
+ t.Run("mode unreadable", func(t *testing.T) {
+ // Astra branch r1, P1 4: an active history whose mode cannot be
+ // read refuses placement, before the registry or any write.
+ fx, token := placeFixture(t, "code-place-cut-unreadable")
+ bucket := wrapBucket(fx)
+ forceHostsState(t, fx.srv, provision.HostsState{Mode: provision.HostsModeActive, Examined: []string{"fleet:pi"}})
+ fx.srv.hosts.reset()
+ bucket.setHook(failNth("get", provision.HostsModeKey, 1, true))
+ status, out := postJSON(t, fx.ts.URL+"/api/cli/apps/"+fx.sqid+"/titogo/place", map[string]string{"target": "fleet/pi"}, token)
+ bucket.setHook(nil)
+ if status != http.StatusServiceUnavailable || out["error"] != placeInstancesFailed {
+ t.Fatalf("API place with the mode unreadable = %d %v, want 503", status, out)
+ }
+ assertPlacement(t, fx, "")
+ })
}
diff --git a/internal/console/hostsused.go b/internal/console/hostsused.go
index a7e1ba545..7baf41f65 100644
--- a/internal/console/hostsused.go
+++ b/internal/console/hostsused.go
@@ -54,6 +54,12 @@ func msgHostsTargetUnexamined(target string) string {
return "New instances can't be created on " + target + " yet. Choose another region."
}
+// msgFleetInventoried is N9: an add-box (or reactivation) on a fleet the
+// history recorded, once active.
+func msgFleetInventoried(fleet string) string {
+ return "Fleet " + fleet + " can't take another box yet. Ask the platform's operator to add the box."
+}
+
// D1-D3, the operator log line and the pages.
const msgAppRegionsWaitForHistory = "app regions are off until the hostname history is complete"
@@ -183,11 +189,18 @@ func regionExamined(st provision.HostsState, code string) bool {
// data-kind create placed on a region or fleet activation did not examine,
// or on a closed fleet, is refused. Pools are not a separate target: their
// boxes are on the roster through their edges files. Before activation, and
-// for exempt kinds (the caller's check), nothing is refused.
+// for exempt kinds (the caller's check), nothing is refused. A mode that
+// cannot be read refuses (S5). It reads only the held state: the doors call
+// it early, before anything is provisioned; gateDataCreate adds the
+// coverage check before the mark.
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 err != nil {
+ log.Printf("console: hosts used: read the mode to place a create on %q: %v", region, err)
+ return &doorRefusal{http.StatusServiceUnavailable, msgHostsInvalidated}
+ }
+ if st.Mode != provision.HostsModeActive {
+ return nil
}
if fleet, ok := registry.FleetPlacement(region); ok {
if slices.Contains(st.Closed, "fleet:"+fleet) || !slices.Contains(st.Examined, "fleet:"+fleet) {
@@ -201,6 +214,95 @@ func (s *Server) hostsTargetRefusal(ctx context.Context, region string) *doorRef
return nil
}
+// hostsCoverageRefusal is the rest of S4 once active: the region's or
+// fleet's targets now are all ones activation scanned (a fleet's or
+// region's target set is fixed once recorded). A box added to a fleet
+// since is refused at its own door (fleetGrowthRefusal); a box that joins
+// a region does so from infra, so a create there is refused here until
+// the history is completed again. Targets that cannot be read refuse (S5).
+// It reads the edges files, or the registry for a fleet, once per
+// data-kind create while the history is active.
+func (s *Server) hostsCoverageRefusal(ctx context.Context, region string) *doorRefusal {
+ st, err := s.hostsState(ctx)
+ if err != nil || st.Mode != provision.HostsModeActive {
+ return nil // hostsTargetRefusal has refused an unreadable mode
+ }
+ var now, recorded []string
+ place := ""
+ if fleet, ok := registry.FleetPlacement(region); ok {
+ place = "fleet " + fleet
+ recorded = st.FleetTargets["fleet:"+fleet]
+ reg, err := openRegistry(s.cfg.Registry)
+ var fl *registry.Fleet
+ if err == nil {
+ fl, err = reg.GetFleet(fleet)
+ }
+ if err == nil && fl != nil {
+ now, err = rosterFleet(reg, *fl)
+ }
+ if err != nil || fl == nil {
+ log.Printf("console: hosts used: read fleet %s's targets: %v", fleet, err)
+ return &doorRefusal{http.StatusServiceUnavailable, msgHostsInvalidated}
+ }
+ } else {
+ if s.cfg.Releases == nil {
+ return nil
+ }
+ snap, err := readEdgesSnapshot(ctx, s.cfg.Releases)
+ if err != nil || !snap.Complete {
+ log.Printf("console: hosts used: read the edges files to check region %q's targets: %v (complete %v)", region, err, snap.Complete)
+ return &doorRefusal{http.StatusServiceUnavailable, msgHostsInvalidated}
+ }
+ now, recorded = rosterRegions(snap)["region:"+region], st.RegionTargets
+ }
+ for _, t := range now {
+ if !slices.Contains(recorded, t) {
+ if place == "" {
+ place = s.placeOf(region, s.candsOrHome(ctx))
+ }
+ if place == "" {
+ place = "the home region"
+ }
+ log.Printf("console: hosts used: %s on %q was not scanned when the history was completed", t, region)
+ return &doorRefusal{http.StatusConflict, msgHostsTargetUnexamined(place)}
+ }
+ }
+ return nil
+}
+
+// gateDataCreate is every data-kind create's whole admission, at the one
+// place each create writer passes before its mark (createRecordMarked,
+// createSidecarMarked, the lifetime create): S5 (admitDataCreate), then S4
+// (hostsTargetRefusal and hostsCoverageRefusal). The instance and sidecar
+// doors also refuse early, before provisioning; the seed and import doors
+// rely on this.
+func (s *Server) gateDataCreate(ctx context.Context, host, region string) *doorRefusal {
+ if ref := s.admitDataCreate(ctx, host); ref != nil {
+ return ref
+ }
+ if ref := s.hostsTargetRefusal(ctx, region); ref != nil {
+ return ref
+ }
+ return s.hostsCoverageRefusal(ctx, region)
+}
+
+// fleetGrowthRefusal is the add-box door's check (Paul's ruling on #404):
+// once the history is active, a fleet activation recorded (examined or
+// closed) takes no new or reactivated box. Growing it means invalidating
+// the history, adding the box, and completing the history again. A mode
+// that cannot be read refuses.
+func (s *Server) fleetGrowthRefusal(ctx context.Context, fleet string) *doorRefusal {
+ st, err := s.hostsState(ctx)
+ if err != nil {
+ log.Printf("console: hosts used: read the mode to add a box to fleet %s: %v", fleet, err)
+ return &doorRefusal{http.StatusServiceUnavailable, "could not add the box — try again"}
+ }
+ if st.Mode == provision.HostsModeActive && (slices.Contains(st.Examined, "fleet:"+fleet) || slices.Contains(st.Closed, "fleet:"+fleet)) {
+ return &doorRefusal{http.StatusConflict, msgFleetInventoried(fleet)}
+ }
+ return nil
+}
+
// admitDataCreate is a data-kind create door's admission: S5 once
// invalidated, and S5 while an active history's start-up check has not
// passed. An unreadable mode refuses with S2 for host, as the mark would.
@@ -437,10 +539,14 @@ func recordUse(rec provision.Record) provision.HostUse {
}
// createRecordMarked is the lifetimes-off create of an instance record
-// (the instance, seed and import doors): the mark for a data kind, then
-// provision.CreateRecord. Exempt kinds write as before.
+// (the instance, seed and import doors): for a data kind, its admission
+// (gateDataCreate) and its mark, then provision.CreateRecord. Exempt kinds
+// write as before.
func (s *Server) createRecordMarked(ctx context.Context, rec provision.Record) error {
if rec.DataKind() {
+ if ref := s.gateDataCreate(ctx, rec.Host, rec.Region); ref != nil {
+ return &hostsUsedError{*ref}
+ }
if err := s.markBeforeCreate(ctx, recordUse(rec), provision.RecordKey(rec.Account, rec.App, rec.Host)); err != nil {
return err
}
@@ -449,8 +555,12 @@ func (s *Server) createRecordMarked(ctx context.Context, rec provision.Record) e
}
// createSidecarMarked is the sidecar door's create: a sidecar is always a
-// data kind, marked at its host, then provision.CreateSidecarRecord.
+// data kind, admitted (gateDataCreate) and marked at its host, then
+// provision.CreateSidecarRecord.
func (s *Server) createSidecarMarked(ctx context.Context, rec provision.SidecarRecord) error {
+ if ref := s.gateDataCreate(ctx, rec.Host, rec.Region); ref != nil {
+ return &hostsUsedError{*ref}
+ }
u := provision.HostUse{Host: rec.Host, Account: rec.Account, App: rec.App, Kind: "sidecar", Source: "create"}
if err := s.markBeforeCreate(ctx, u, provision.SidecarRecordKey(rec.Account, rec.App, rec.Name)); err != nil {
return err
diff --git a/internal/console/hostsused_activate.go b/internal/console/hostsused_activate.go
index dc4b8fa72..814dcfecd 100644
--- a/internal/console/hostsused_activate.go
+++ b/internal/console/hostsused_activate.go
@@ -15,6 +15,7 @@ import (
boxlayout "github.com/carlosframework/platform/internal/layout"
"github.com/carlosframework/platform/internal/provision"
+ "github.com/carlosframework/platform/internal/registry"
"github.com/carlosframework/platform/internal/release"
"github.com/carlosframework/platform/internal/seeds"
"github.com/carlosframework/platform/internal/version"
@@ -104,14 +105,7 @@ func (a HostsActivation) Roster(ctx context.Context) (HostsRoster, error) {
if !snap.Complete {
return HostsRoster{}, errors.New("an edges file could not be read or parsed")
}
- r := HostsRoster{Regions: map[string][]string{}, Fleets: map[string][]string{}}
- for _, f := range snap.Files {
- region := "region:" + f.Placement
- r.Regions[region] = append(r.Regions[region], "box:"+f.Box)
- if f.DataBucket != "" {
- r.Regions[region] = append(r.Regions[region], "bucket:"+f.DataBucket)
- }
- }
+ r := HostsRoster{Regions: rosterRegions(snap), Fleets: map[string][]string{}}
if a.Registry != "" {
reg, err := openRegistry(a.Registry)
if err != nil {
@@ -122,20 +116,11 @@ func (a HostsActivation) Roster(ctx context.Context) (HostsRoster, error) {
return HostsRoster{}, fmt.Errorf("list the fleets: %w", err)
}
for _, fl := range fleets {
- key := "fleet:" + fl.Name
- r.Fleets[key] = []string{}
- if fl.Bucket != "" {
- r.Fleets[key] = append(r.Fleets[key], "bucket:"+fl.Bucket)
- }
- boxes, err := reg.ListFleetBoxes(fl.Name)
+ ts, err := rosterFleet(reg, fl)
if err != nil {
- return HostsRoster{}, fmt.Errorf("list fleet %s's boxes: %w", fl.Name, err)
- }
- for _, b := range boxes {
- if b.Status != "detached" {
- r.Fleets[key] = append(r.Fleets[key], "box:fleet/"+fl.Name+"/"+b.Label)
- }
+ return HostsRoster{}, err
}
+ r.Fleets["fleet:"+fl.Name] = ts
}
}
var all []string
@@ -151,6 +136,40 @@ func (a HostsActivation) Roster(ctx context.Context) (HostsRoster, error) {
return r, nil
}
+// rosterRegions is each region's targets in the edges files: its boxes and
+// their data buckets, keyed "region:<placement code>" ("region:" is the
+// home).
+func rosterRegions(snap edgesSnapshot) map[string][]string {
+ out := map[string][]string{}
+ for _, f := range snap.Files {
+ region := "region:" + f.Placement
+ out[region] = append(out[region], "box:"+f.Box)
+ if f.DataBucket != "" {
+ out[region] = append(out[region], "bucket:"+f.DataBucket)
+ }
+ }
+ return out
+}
+
+// rosterFleet is one fleet's targets in the registry: its bucket and every
+// box not detached.
+func rosterFleet(reg consoleRegistry, fl registry.Fleet) ([]string, error) {
+ out := []string{}
+ if fl.Bucket != "" {
+ out = append(out, "bucket:"+fl.Bucket)
+ }
+ boxes, err := reg.ListFleetBoxes(fl.Name)
+ if err != nil {
+ return nil, fmt.Errorf("list fleet %s's boxes: %w", fl.Name, err)
+ }
+ for _, b := range boxes {
+ if b.Status != "detached" {
+ out = append(out, "box:fleet/"+fl.Name+"/"+b.Label)
+ }
+ }
+ return out, nil
+}
+
// excusedTargets is every listing target the closed fleets excuse: a target
// only when every consumer of it, region or fleet, is a closed fleet.
func (r HostsRoster) excusedTargets(closed []string) map[string]bool {
diff --git a/internal/console/hostsused_activate_test.go b/internal/console/hostsused_activate_test.go
index ac710c2f5..9ef88afc5 100644
--- a/internal/console/hostsused_activate_test.go
+++ b/internal/console/hostsused_activate_test.go
@@ -122,6 +122,17 @@ func TestActivateLocalOnlyLeftoverRefused(t *testing.T) {
}
}
+// TestActivateMarksAnAuxiliaryLeftover (Astra branch r1, P1 5): with the
+// record and primary database gone, a leftover shop.example.com.backup.db
+// still marks shop.example.com, so it is never created again.
+func TestActivateMarksAnAuxiliaryLeftover(t *testing.T) {
+ l := invFx(t)
+ mustActivate(t, l, clean([]string{"left.shop.example.com.backup.db"}, nil))
+ if code, body := createAs(t, l, `{"host":"left.shop.example.com"}`); code != http.StatusConflict || ltErr(body) != msgHostUsed("left.shop.example.com") {
+ t.Fatalf("create of left.shop.example.com with its backup left = %d %s, want 409 S1", code, body)
+ }
+}
+
func TestActivateMarksOrphanSeedSnapshot(t *testing.T) {
l := invFx(t)
mustActivate(t, l, clean(nil, []string{"seeds/orphan.shop.example.com/sd_1/snapshot.db", "instances/bucket.shop.example.com/0000/x.ltx", "moves/@lanes/uk/x"}))
diff --git a/internal/console/hostsused_active_test.go b/internal/console/hostsused_active_test.go
index 4e426edee..a294c8ebc 100644
--- a/internal/console/hostsused_active_test.go
+++ b/internal/console/hostsused_active_test.go
@@ -20,10 +20,31 @@ import (
"github.com/carlosframework/platform/internal/release"
)
+// recordedTargets fills an active state's recorded targets, when the test
+// gave none, from the roster as it is now: what activation would have
+// recorded had it run at this point.
+func recordedTargets(srv *Server, st provision.HostsState) provision.HostsState {
+ if st.Mode != provision.HostsModeActive || st.RegionTargets != nil || st.FleetTargets != nil || srv.cfg.Releases == nil {
+ return st
+ }
+ r, err := HostsActivation{Releases: srv.cfg.Releases, Registry: srv.cfg.Registry}.Roster(context.Background())
+ if err != nil {
+ return st
+ }
+ st.FleetTargets, st.RegionTargets = r.Fleets, []string{}
+ for _, ts := range r.Regions {
+ st.RegionTargets = append(st.RegionTargets, ts...)
+ }
+ return st
+}
+
// forceHostsState writes st and has srv read it, as a console start would.
+// An active state with no recorded targets records the roster as it is now
+// (recordedTargets).
func forceHostsState(t *testing.T, srv *Server, st provision.HostsState) {
t.Helper()
ctx := context.Background()
+ st = recordedTargets(srv, st)
_, etag, err := provision.ReadHostsState(ctx, srv.cfg.Releases)
if err != nil {
t.Fatal(err)
@@ -274,10 +295,11 @@ func TestClosedFleetRefused(t *testing.T) {
// 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) {
+ st := recordedTargets(srv, provision.HostsState{Mode: provision.HostsModeActive,
+ Examined: []string{"region:ie", "region:uk", "region:au", "region:us", "region:jp", "region:de", "region:ca"}})
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"}}
+ srv.hosts.state = st
srv.hosts.verified = true
}
diff --git a/internal/console/hostsused_coverage_test.go b/internal/console/hostsused_coverage_test.go
new file mode 100644
index 000000000..13c0de844
--- /dev/null
+++ b/internal/console/hostsused_coverage_test.go
@@ -0,0 +1,208 @@
+package console
+
+// The history's coverage after activation (Astra branch r1, P1 3 and P2 7):
+// a fleet the history recorded takes no new or reactivated box (Paul's
+// ruling on #404), a region or fleet whose targets have grown since takes
+// no data-kind create, and every create door, seed and import included,
+// passes the whole admission (S5 and S4) through its real request.
+
+import (
+ "context"
+ "net/http"
+ "strings"
+ "testing"
+
+ "github.com/carlosframework/platform/internal/provision"
+ "github.com/carlosframework/platform/internal/registry"
+)
+
+// activeAsNow makes the history active as activation would at this point:
+// every region and fleet on the roster examined, its targets recorded, and
+// the start-up check passed.
+func activeAsNow(t *testing.T, srv *Server) {
+ t.Helper()
+ r, err := HostsActivation{Releases: srv.cfg.Releases, Registry: srv.cfg.Registry}.Roster(context.Background())
+ if err != nil {
+ t.Fatal(err)
+ }
+ st := provision.HostsState{Mode: provision.HostsModeActive, FleetTargets: r.Fleets, RegionTargets: []string{}}
+ for k, ts := range r.Regions {
+ st.Examined = append(st.Examined, k)
+ st.RegionTargets = append(st.RegionTargets, ts...)
+ }
+ for k := range r.Fleets {
+ st.Examined = append(st.Examined, k)
+ }
+ forceHostsState(t, srv, st)
+}
+
+func activeFleetBoxes(t *testing.T, fx *consoleFixture, fleet string) []string {
+ t.Helper()
+ boxes, err := openTestReg(t, fx).ListFleetBoxes(fleet)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var out []string
+ for _, b := range boxes {
+ if b.Status == "active" {
+ out = append(out, b.Label)
+ }
+ }
+ return out
+}
+
+// TestFleetGrowthRefused: once active, add-box on a fleet the history
+// recorded is refused (N9), a new label and a detached one alike, and
+// nothing is written; an unreadable mode refuses; before activation and
+// once invalidated (the way to grow a fleet) the box is added.
+func TestFleetGrowthRefused(t *testing.T) {
+ fx, token := placeFixture(t, "code-fleet-growth")
+ bucket := wrapBucket(fx)
+ add := func(label string) (int, map[string]any) {
+ return postJSON(t, fleetsURL(fx, fx.sqid)+"/pi/boxes", map[string]string{"label": label}, token)
+ }
+ if status, out := add("pi-1"); status != http.StatusOK {
+ t.Fatalf("add-box before activation = %d %v, want 200", status, out)
+ }
+ if err := openTestReg(t, fx).SetFleetBoxStatus("pi", "pi-1", "detached"); err != nil {
+ t.Fatal(err)
+ }
+ activeAsNow(t, fx.srv)
+ for _, label := range []string{"pi-2", "pi-1"} {
+ if status, out := add(label); status != http.StatusConflict || out["error"] != msgFleetInventoried("pi") {
+ t.Fatalf("add-box %s once active = %d %v, want 409 N9", label, status, out)
+ }
+ }
+ if got := activeFleetBoxes(t, fx, "pi"); len(got) != 0 {
+ t.Fatalf("active boxes after refusals = %v, want none", got)
+ }
+ // A closed fleet is recorded too.
+ forceHostsState(t, fx.srv, provision.HostsState{Mode: provision.HostsModeActive, Closed: []string{"fleet:pi"}})
+ if status, out := add("pi-3"); status != http.StatusConflict || out["error"] != msgFleetInventoried("pi") {
+ t.Fatalf("add-box on a closed fleet = %d %v, want 409 N9", status, out)
+ }
+ // The mode cannot be read: refused, nothing added.
+ fx.srv.hosts.reset()
+ bucket.setHook(failNth("get", provision.HostsModeKey, 1, true))
+ if status, out := add("pi-2"); status != http.StatusServiceUnavailable {
+ t.Fatalf("add-box with the mode unreadable = %d %v, want 503", status, out)
+ }
+ bucket.setHook(nil)
+ if got := activeFleetBoxes(t, fx, "pi"); len(got) != 0 {
+ t.Fatalf("active boxes = %v, want none", got)
+ }
+ // Invalidated: the fleet can grow, ahead of completing the history again.
+ forceHostsState(t, fx.srv, provision.HostsState{Mode: provision.HostsModeInvalidated, Examined: []string{"fleet:pi"}})
+ if status, out := add("pi-1"); status != http.StatusOK {
+ t.Fatalf("add-box once invalidated = %d %v, want 200", status, out)
+ }
+}
+
+// TestGrownFleetRefusesCreates is the reviewer's scenario: fleet F is
+// recorded, a box joins it without the door (an older console, a restored
+// registry), and a create on F is refused (S4) with nothing written,
+// lifetimes off and on.
+func TestGrownFleetRefusesCreates(t *testing.T) {
+ lifetimesFor(t, func(t *testing.T, on func(*testing.T, markCase)) {
+ fx, token := placeFixture(t, "code-grown-fleet")
+ on(t, markCase{fx: fx})
+ m := titoManifest()
+ m.Pool, m.Regions = "", nil
+ enableInstances(t, fx, "titogo", m)
+ if status, out := postJSON(t, fx.ts.URL+"/api/cli/apps/"+fx.sqid+"/titogo/place", map[string]string{"target": "fleet/pi"}, token); status != http.StatusOK {
+ t.Fatalf("place = %d %v", status, out)
+ }
+ activeAsNow(t, fx.srv)
+ if err := openTestReg(t, fx).AddFleetBox(registry.FleetBox{Fleet: "pi", Label: "late", TokenHash: strings.Repeat("a", 64), Status: "active"}); err != nil {
+ t.Fatal(err)
+ }
+ code, _, out := rawReq(t, http.MethodPost, instancesURL(fx, fx.sqid, "titogo"), token, `{"host":"fl.go.tito.io"}`)
+ if code != http.StatusConflict || ltErr(out) != msgHostsTargetUnexamined("fleet pi") {
+ t.Fatalf("create on a grown fleet = %d %s, want 409 S4", code, out)
+ }
+ if used, err := provision.HostIsUsed(context.Background(), fx.rel, "fl.go.tito.io"); err != nil || used {
+ t.Fatalf("the refused create marked its host: %v %v", used, err)
+ }
+ if _, _, err := fx.rel.Get(context.Background(), provision.RecordKey(fx.sqid, "titogo", "fl.go.tito.io")); err == nil {
+ t.Fatal("the refused create wrote its record")
+ }
+ })
+}
+
+// TestEveryDoorPassesTheWholeAdmission: through every data-kind create
+// door's real request (instance, address-backed, canary, region, app
+// region, seed, import, sidecar), lifetimes off and on: an active history
+// whose start-up check has not passed refuses (S5), and once it has, a box
+// that joined the door's region since activation refuses (S4). Nothing is
+// written either time.
+func TestEveryDoorPassesTheWholeAdmission(t *testing.T) {
+ for _, d := range markDoors {
+ t.Run(d.name, func(t *testing.T) {
+ lifetimesFor(t, func(t *testing.T, on func(*testing.T, markCase)) {
+ c := d.build(t)
+ on(t, c)
+ activeAsNow(t, c.fx.srv)
+ c.fx.srv.hosts.mu.Lock()
+ c.fx.srv.hosts.verified = false
+ c.fx.srv.hosts.mu.Unlock()
+ if code, out := c.create(t); code != http.StatusServiceUnavailable || ltErr(out) != msgHostsInvalidated {
+ t.Fatalf("create before the start-up check = %d %s, want 503 S5", code, out)
+ }
+ if recordPresent(t, c, c.recordKey) || markOf(t, c) != nil {
+ t.Fatal("the refused create wrote something")
+ }
+ // A target in every region that activation did not
+ // record: as if a box had joined each since. (A new
+ // edges file would also be one, but a box with no fresh
+ // status fails the region's own checks first.)
+ // A fixture with no box at home gets one, so the home has
+ // a target to leave unrecorded.
+ if r, err := (HostsActivation{Releases: c.fx.srv.cfg.Releases}).Roster(context.Background()); err != nil {
+ t.Fatal(err)
+ } else if _, ok := r.Regions["region:"]; !ok {
+ putHostsEdges(t, c.bucket.Store, "home-1", "", "")
+ }
+ activeAsNow(t, c.fx.srv)
+ st, err := c.fx.srv.hostsState(context.Background())
+ if err != nil {
+ t.Fatal(err)
+ }
+ st.RegionTargets = []string{}
+ forceHostsState(t, c.fx.srv, st)
+ code, out := c.create(t)
+ if code != http.StatusConflict || !strings.HasPrefix(ltErr(out), "New instances can't be created on ") {
+ t.Fatalf("create in a region a box joined since = %d %s, want 409 S4", code, out)
+ }
+ if recordPresent(t, c, c.recordKey) || markOf(t, c) != nil {
+ t.Fatal("the refused create wrote something")
+ }
+ })
+ })
+ }
+}
+
+// TestUnreadableEdgesRefuseCreates: once active, a data-kind create whose
+// region's targets cannot be read (an edges file that does not parse) is
+// refused at every door, with nothing written; the coverage check itself
+// answers S5.
+func TestUnreadableEdgesRefuseCreates(t *testing.T) {
+ for _, d := range markDoors {
+ t.Run(d.name, func(t *testing.T) {
+ c := d.build(t)
+ activeAsNow(t, c.fx.srv)
+ if _, err := c.bucket.Store.Put(context.Background(), "control/edges/broken.json", []byte("{"), ""); err != nil {
+ t.Fatal(err)
+ }
+ // 503, or an earlier refusal of the region's own.
+ if code, out := c.create(t); code != http.StatusServiceUnavailable && code != http.StatusConflict {
+ t.Fatalf("create with the edges unreadable = %d %s, want it refused", code, out)
+ }
+ if recordPresent(t, c, c.recordKey) || markOf(t, c) != nil {
+ t.Fatal("the refused create wrote something")
+ }
+ if ref := c.fx.srv.hostsCoverageRefusal(context.Background(), ""); ref == nil || ref.Msg != msgHostsInvalidated {
+ t.Fatalf("coverage with the edges unreadable = %+v, want S5", ref)
+ }
+ })
+ }
+}
diff --git a/internal/console/hostsused_writers_test.go b/internal/console/hostsused_writers_test.go
index 500ebb63f..49b3b8b36 100644
--- a/internal/console/hostsused_writers_test.go
+++ b/internal/console/hostsused_writers_test.go
@@ -178,6 +178,7 @@ func forceHostsMode(t *testing.T, srv *Server, mode string) {
st := provision.HostsState{Mode: mode}
if mode == provision.HostsModeActive {
st.Examined = []string{"region:ie", "region:uk"}
+ st = recordedTargets(srv, st)
}
if _, err := provision.WriteHostsState(ctx, srv.cfg.Releases, st, etag); err != nil {
t.Fatal(err)
diff --git a/internal/console/lifetimes_create.go b/internal/console/lifetimes_create.go
index 8db99c91a..6168d3b1c 100644
--- a/internal/console/lifetimes_create.go
+++ b/internal/console/lifetimes_create.go
@@ -105,11 +105,14 @@ func (s *Server) createRecordWithLifetimeLocked(ctx context.Context, rec provisi
if plan.ownerStaleETag != "" {
a.PrevOwnerKey = provision.RecordKey(plan.ownerAccount, plan.ownerApp, host)
}
- // The hostname history (hostsused.go): a data kind marks its hostname
- // after every check above, step 2's record read among them, and before
- // anything is persisted. Nothing is durable yet, so a refusal leaves
+ // The hostname history (hostsused.go): a data kind is admitted
+ // (gateDataCreate) and marks its hostname after every check above,
+ // step 2's record read among them, and before anything is persisted. Nothing is durable yet, so a refusal leaves
// nothing behind.
if rec.DataKind() {
+ if ref := s.gateDataCreate(ctx, rec.Host, rec.Region); ref != nil {
+ return nil, &hostsUsedError{*ref}
+ }
if ref := s.markForCreate(ctx, recordUse(rec)); ref != nil {
return nil, &hostsUsedError{*ref}
}
diff --git a/internal/layout/hostsused.go b/internal/layout/hostsused.go
index 5d40cef93..538654666 100644
--- a/internal/layout/hostsused.go
+++ b/internal/layout/hostsused.go
@@ -1,6 +1,7 @@
package layout
import (
+ "slices"
"strings"
"github.com/carlosframework/platform/internal/controlname"
@@ -16,9 +17,9 @@ import (
// plus a "." or "-" and more (belongsTo's rule): every host-like prefix
// ending at such a boundary is marked, because an app may name its
// files from its database path. A name with one of the platform's own
-// suffixes is read exactly, and is the box's own (registry.db) when its
-// stem has no dot. A name with a dot that yields no valid hostname is
-// unmapped: nothing is normalised.
+// suffixes also marks its stem, and is the box's own (registry.db) when
+// its stem has no dot. A name with a dot that yields no valid hostname
+// is unmapped: nothing is normalised.
// - instances/<id>/ and .instances/<id>/ map to <id>, or for a hashed id
// ("_" + prefix + hash, provision.InstanceID) to the full host a file
// inside names; a hashed id with none is unmapped.
@@ -111,26 +112,35 @@ func HostsFromBoxListing(paths []string) (hosts, unmapped []string) {
func listingHostLike(x string) bool { return strings.Contains(x, ".") && controlname.ValidHostShape(x) }
// flatNameHosts is every host a flat top-level name may belong to, and
-// whether it looks like a host's (it has a dot) yet names none.
+// whether it looks like a host's (it has a dot) yet names none. A name with
+// one of the platform's suffixes names its stem, and still every host-like
+// prefix too: shop.example.com.backup.db is the host
+// shop.example.com.backup's database by its shape, and shop.example.com's
+// file by belongsTo's rule, so both are marked. Its stem decides
+// malformed: registry.db is the box's own, not a host's, and a dotted stem
+// that is no valid hostname (shop.example.com..db) is unmapped whatever its
+// prefixes name.
func flatNameHosts(name string) (hosts []string, malformed bool) {
name = strings.TrimPrefix(name, ".activator-")
+ stem, fixed := name, false
for _, suffix := range fixedSuffixes {
if x, ok := strings.CutSuffix(name, suffix); ok && x != "" {
- if listingHostLike(x) {
- return []string{x}, false
+ if strings.Contains(x, ".") && !listingHostLike(x) {
+ return nil, true
}
- return nil, strings.Contains(x, ".")
+ stem, fixed = x, true
+ break
}
}
- for i := len(name); i > 0; i-- {
- if i < len(name) && name[i] != '.' && name[i] != '-' {
+ for i := len(stem); i > 0; i-- {
+ if i < len(stem) && stem[i] != '.' && stem[i] != '-' {
continue
}
- if x := name[:i]; listingHostLike(x) {
+ if x := stem[:i]; listingHostLike(x) && !slices.Contains(hosts, x) {
hosts = append(hosts, x)
}
}
- return hosts, len(hosts) == 0 && strings.Contains(name, ".")
+ return hosts, !fixed && len(hosts) == 0 && strings.Contains(name, ".")
}
// hiddenSegmentHosts is the hosts one segment of a hidden entry's path
diff --git a/internal/layout/hostsused_test.go b/internal/layout/hostsused_test.go
index de300967a..0023ef935 100644
--- a/internal/layout/hostsused_test.go
+++ b/internal/layout/hostsused_test.go
@@ -90,6 +90,29 @@ func TestBoxListingShapes(t *testing.T) {
}
}
+// A file with a platform suffix also marks every host-like prefix of its
+// name (Astra branch r1, P1): shop.example.com.backup.db is
+// shop.example.com.backup's database by its shape and shop.example.com's
+// file by belongsTo, so a leftover of either marks both.
+func TestFixedSuffixNameMarksItsOwner(t *testing.T) {
+ hosts, unmapped := HostsFromBoxListing([]string{"shop.example.com.backup.db", ".activator-shop.example.com.old.db-litestream"})
+ got := map[string]bool{}
+ for _, h := range hosts {
+ got[h] = true
+ }
+ for _, h := range []string{"shop.example.com", "shop.example.com.backup", "shop.example.com.old"} {
+ if !got[h] {
+ t.Errorf("%s is not marked (hosts %v)", h, hosts)
+ }
+ }
+ if !belongsTo("shop.example.com.backup.db", "shop.example.com") {
+ t.Fatal("fixture: belongsTo no longer gives the file to shop.example.com")
+ }
+ if len(unmapped) != 0 {
+ t.Fatalf("unmapped %v", unmapped)
+ }
+}
+
func TestHashedInstanceDirMapsByInnerFile(t *testing.T) {
long := strings.Repeat("a", 40) + ".example.com"
id := provision.InstanceID(long)
diff --git a/internal/provision/nearest_region_b_census_test.go b/internal/provision/nearest_region_b_census_test.go
index f9adae17f..9c080733e 100644
--- a/internal/provision/nearest_region_b_census_test.go
+++ b/internal/provision/nearest_region_b_census_test.go
@@ -15,17 +15,21 @@ package provision
// - HostsFromBoxListing (internal/layout), new: pure mapping of a box's
// data-directory listing ("instances" is the layout's directory name).
// No store: key-site.
-// - migrationHistory.beforeRecord, migrationRecordHost (root), new: carlos
-// accounts migrate's check before a record copy: reads the destination
-// record key, or writes a mark through provision.MarkHostUsed. No record
-// write of their own: key-site.
+// - beforeRecord, refuseDataRecords, migrationRecordHost (root), new:
+// carlos accounts migrate's check before a record copy, and over the
+// whole plan before any write: read the source and destination record
+// keys and refuse a data-kind record. No write of their own: key-site.
+// - Server.createRecordMarked, Server.createSidecarMarked (console),
+// re-pinned: gateDataCreate (S5, S4) before the mark. Their create-only
+// writes are unchanged: record-writer.
// - Server.allocRecordLocked, re-pinned: a recovery replay of a data-kind
// allocation marks first, or requires the mark once active. Its
// create-only WriteRecord is unchanged: record-writer.
-// - Server.createRecordWithLifetimeLocked, re-pinned: passes doorMarked.
-// Same sites: key-site.
+// - Server.createRecordWithLifetimeLocked, re-pinned: passes doorMarked,
+// and gateDataCreate before the mark. Same sites: key-site.
// - Server.placeAppTarget, re-pinned: S3 first once the history is active
-// or invalidated. Its write sites are unchanged: record-writer.
+// or invalidated, and a refusal when the mode cannot be read. Its write
+// sites are unchanged: record-writer.
// - Server.registerCLIRoutes, re-pinned (merge A's status door's
// neighbourhood only). Same literals: key-site.
func nearestRegionBWriteCensusInventory() []censusEntry {
@@ -48,12 +52,15 @@ func nearestRegionBWriteCensusInventory() []censusEntry {
replacements := []censusEntry{
{"internal/provision/hostsused.go", "WriteHostsState", "nonrecord", "sel:Put", "5f1b95198e45dedc9715d73a57bfa57cb1305d364895cd981375e0ed3610c8da"},
{"internal/layout/hostsused.go", "HostsFromBoxListing", "key-site", "lit:instances", "b3c85cf9c369941664a8bdb7dcf1fe92b37c8b5ffd719d963e1f88243712d577"},
- {"internal/console/fleets.go", "Server.placeAppTarget", "record-writer", "key:RecordsPrefix,key:SetRecordRegion", "3b67c0d7ace89dfa2fc0f1ff3b025d02a066c2aaa9127200dbd1eda8c830e830"},
+ {"internal/console/fleets.go", "Server.placeAppTarget", "record-writer", "key:RecordsPrefix,key:SetRecordRegion", "d1241f2211ab516bed24305950897d8e603c4206af055d17fc7c7cc91b38b562"},
{"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/lifetimes_create.go", "Server.createRecordWithLifetimeLocked", "key-site", "key:RecordKey", "f18477b47f99098a3bd3e3597cc89d1487e7597d0cbb0449a02db5370d4c3ee7"},
{"internal/console/hostsused_activate.go", "recordFacts", "key-site", "key:IsRecordKey,lit:sidecars", "98c7830b6fb3af8129f9b9d6a8fe27597a9efcecfd44782b209da911f9210771"},
{"internal/console/hostsused_tripwire.go", "Server.hostsTripwire", "key-site", "key:IsRecordKey,lit:instances,lit:sidecars", "6a503a4b29f7909c45ec6a3e52a33a2e5a8b8b37a816942cabba9fa6f80faeba"},
- {"accounts_hostsused.go", "migrationHistory.beforeRecord", "key-site", "key:IsRecordKey", "bf9243ed8c05ebbad2d2a3de1d8d3796c87fa14a6295d8007bf509f3550f8c44"},
+ {"accounts_hostsused.go", "beforeRecord", "key-site", "key:IsRecordKey", "73e989d07dfde038fd917d004c16d2119afcedf5f76a26e85a6800cf0a950a58"},
+ {"accounts_hostsused.go", "refuseDataRecords", "key-site", "key:IsRecordKey", "c7aee0366810562cd3bda840fac75533ec420ce76b277d267216e963f8415114"},
+ {"internal/console/hostsused.go", "Server.createRecordMarked", "record-writer", "key:CreateRecord,key:RecordKey", "4a8cc22bd98a187e7b5e263e8ead2f0b0a962ae644996af582e8cd9e6915052d"},
+ {"internal/console/hostsused.go", "Server.createSidecarMarked", "record-writer", "key:CreateSidecarRecord,key:SidecarRecordKey", "197fba9ee8949f7e61caef81800cb6bb9a4374497884f229312216d0ef8056cf"},
{"accounts_hostsused.go", "migrationRecordHost", "key-site", "lit:sidecars", "709eb800cebb6e9a9fa6ba40caf9bed51ab4ecc81b22676270aab28eefeddbb3"},
{"internal/console/authcli.go", "Server.registerCLIRoutes", "key-site", "lit:instances,lit:sidecars", "25cb2b7d4f7d264d8a45e5b9306f8f7f95fe886237fd88b9e4a492d7e66e90e3"},
}
diff --git a/internal/provision/testdata/plan14-root-reads-chain.tsv b/internal/provision/testdata/plan14-root-reads-chain.tsv
index dcf5c2d45..e18c38f59 100644
--- a/internal/provision/testdata/plan14-root-reads-chain.tsv
+++ b/internal/provision/testdata/plan14-root-reads-chain.tsv
@@ -3,4 +3,4 @@
plan14-root-reads-c2-root-exec-inputs.tsv 0ef813eebfb1a2e2812d897c4f0b5fd7f75e3e39c7602cf64d1634e8374327af
plan14-root-reads-label-case-running-tile.tsv 0ef813eebfb1a2e2812d897c4f0b5fd7f75e3e39c7602cf64d1634e8374327af
plan14-root-reads-remote-instance-metrics.tsv ed0d770a827bdb37a87d21e5c8efb259ca0de88457b0cb3202ebb006fc0cd032
-plan14-root-reads-nearest-region-b.tsv 3e39f43fc130874481304fcb04b85f7455d360eb974acf4d7f344954e56cd8e3
+plan14-root-reads-nearest-region-b.tsv f4bd7800db64c0c353510a302f8ff9ce7b6d8c44d56c0f46cb6558fa63e2e14b
diff --git a/internal/provision/testdata/plan14-root-reads-nearest-region-b.tsv b/internal/provision/testdata/plan14-root-reads-nearest-region-b.tsv
index 43092f33e..0318a5239 100644
--- a/internal/provision/testdata/plan14-root-reads-nearest-region-b.tsv
+++ b/internal/provision/testdata/plan14-root-reads-nearest-region-b.tsv
@@ -1,7 +1,7 @@
# Census overlay nearest-region-b, written by census-propose (#369). census-ruling-nearest-region-b, approved on #280 before the merge; the approval card is docs/superpowers/notes/census-proposal-nearest-region-b.md.
# 1 body, 0 sites, 3 envelope: each changed unit re-frozen at its existing disposition with its claim appended.
-@legacy 0fdb5f0432bd858058ac08c2de8b501fb909839cfda825d6e613de9db2df81f3 accounts.go runAccountsMigrate legacy accepted-legacy accepted-legacy;rev3=J1,J4;basis=route-and-input;rev3=census-ruling-nearest-region-b;basis=reads the hostname history before it opens the registry (readMigrationHistoryNow: GETs control/hosts-used/@floor and @mode from the deployment store, the one store the verb uses) and refuses below the floor; each record copy goes through copyMigrationRecord, which GETs the destination key or Puts a create-only mark under control/hosts-used/ and, once the history exists, never writes a data-kind record; no new kind of read, no path or input a tenant, app or box agent can name file:Open@1260,registry:Account@6252,registry:Account@6386,registry:App@6234,registry:Host@6377,registry:Host@6439,registry:Host@6515,registry:Host@6617,whole:Route@6220 6febe79bb71b3e6db75a847e867707cb0d5d22e924a21468f6660ae17e2f637b
-accounts.go runAccountsMigrate legacy accepted-legacy accepted-legacy;rev3=J1,J4;basis=route-and-input;rev3=census-ruling-nearest-region-b;basis=reads the hostname history before it opens the registry (readMigrationHistoryNow: GETs control/hosts-used/@floor and @mode from the deployment store, the one store the verb uses) and refuses below the floor; each record copy goes through copyMigrationRecord, which GETs the destination key or Puts a create-only mark under control/hosts-used/ and, once the history exists, never writes a data-kind record; no new kind of read, no path or input a tenant, app or box agent can name file:Open@1260,registry:Account@6252,registry:Account@6386,registry:App@6234,registry:Host@6377,registry:Host@6439,registry:Host@6515,registry:Host@6617,whole:Route@6220 6febe79bb71b3e6db75a847e867707cb0d5d22e924a21468f6660ae17e2f637b
-@coverage . 9b7f4107a2e69bb310ef59c04380dbcdf7b058d8f9ed646caae25f1a20c1f51a
-@coverage internal/layout 7ccc87fc72e0bb9a30332b965e43200c223b72a9e46ca495754e2f13770ff940
+@legacy 6851eb26db8755a8c6fb107244687be6444f488e7f097dbd6dae93ffebceb053 accounts.go runAccountsMigrate legacy accepted-legacy accepted-legacy;rev3=J1,J4;basis=route-and-input;rev3=census-ruling-nearest-region-b;basis=reads the hostname history's floor before it opens the registry (checkMigrationFloorNow: GETs control/hosts-used/@floor from the deployment store, the one store the verb uses) and refuses below it; before any write it reads each planned record's source and destination keys and refuses a plan that would create a data-kind record (refuseDataRecords), and each record copy checks the same again (copyMigrationRecord) and never writes a data-kind record; no marks, no new kind of read, no path or input a tenant, app or box agent can name file:Open@1195,registry:Account@6388,registry:Account@6522,registry:App@6370,registry:Host@6513,registry:Host@6575,registry:Host@6651,registry:Host@6753,whole:Route@6356 eed2a538902926640ab74d4f1264e5c1f6eec0ffa7750a4d86b9af835d170308
+accounts.go runAccountsMigrate legacy accepted-legacy accepted-legacy;rev3=J1,J4;basis=route-and-input;rev3=census-ruling-nearest-region-b;basis=reads the hostname history's floor before it opens the registry (checkMigrationFloorNow: GETs control/hosts-used/@floor from the deployment store, the one store the verb uses) and refuses below it; before any write it reads each planned record's source and destination keys and refuses a plan that would create a data-kind record (refuseDataRecords), and each record copy checks the same again (copyMigrationRecord) and never writes a data-kind record; no marks, no new kind of read, no path or input a tenant, app or box agent can name file:Open@1195,registry:Account@6388,registry:Account@6522,registry:App@6370,registry:Host@6513,registry:Host@6575,registry:Host@6651,registry:Host@6753,whole:Route@6356 eed2a538902926640ab74d4f1264e5c1f6eec0ffa7750a4d86b9af835d170308
+@coverage . abe8f1856ec6c8112e91828d2ad39c00bf3f86823ebc59a3492dca0486b152a0
+@coverage internal/layout 6061e8c42cf5feacc06d5bfdab3d10b30801d9c4f1723c78b7a59e0161f41a3f
@coverage internal/provision eb8e66dfc8b4e95269de1d15850f47aba73f2c3420cd3ddd08afe4696dad1b01
diff --git a/system.go b/system.go
index 0e3564fb5..955b66742 100644
--- a/system.go
+++ b/system.go
@@ -174,7 +174,7 @@ The platform's own binary (ops account owners and CARLOS_SYSTEM_OPERATORS):
once, after the old console has stopped. Waits until they are on
hosts-used status
the hostname history: its mode, how many hostnames it has
- recorded, and how much work is still settling
+ recorded, its closed fleets and its floor
box role <box> <default|legacy|platform>
whether new instances may be placed on a box. A legacy or
platform box keeps the instances it has and takes no new ones