carlos / platform Public

console: a post-activation fleet is recorded at its first box (#519)

Once the hostname history is active, a fleet created since activation
could only take instances after the offline invalidate and complete
cycle. Its first add-box now records it, before adding the box, as
examined with its bucket, boxes and the new box as targets, naming that
label as its first box. A recorded fleet's add-box stays N9 (#404)
except the first-box label while no box of it is active, so the same
add-box again finishes any failed or ambiguous write. A bucket shared
with a closed fleet leaves the fleet unrecorded.

Paul's rulings 2026-11-02: storage the owner names is examined as new;
mode-first, idempotent enrollment after stopping rule 2. Astra r3
READY; census envelope internal/provision approved (#280).

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

Squashed from fleet-examined-519 into main.
claude agent, operated by paul@keymail.dev adda5541ae72997d47ccef42cc776835618b94e8 parent 5394c7f
11 files changed, +721 −25
  • docs/superpowers/notes/census-proposal-fleet-examined-519.md +11 −0
  • docs/superpowers/notes/reviews/ASTRA-FINDINGS-fleet-examined-519-r1.md +46 −0
  • docs/superpowers/notes/reviews/ASTRA-FINDINGS-fleet-examined-519-r2.md +56 −0
  • docs/superpowers/notes/reviews/ASTRA-FINDINGS-fleet-examined-519-r3.md +64 −0
  • docs/superpowers/specs/2026-10-26-nearest-region-without-claims-design.md +2 −0
  • internal/console/fleets.go +12 −9
  • internal/console/hostsused.go +105 −16
  • internal/console/hostsused_coverage_test.go +417 −0
  • internal/provision/hostsused.go +4 −0
  • internal/provision/testdata/plan14-root-reads-chain.tsv +1 −0
  • internal/provision/testdata/plan14-root-reads-fleet-examined-519.tsv +3 −0

CI passed — run details

diff --git a/docs/superpowers/notes/census-proposal-fleet-examined-519.md b/docs/superpowers/notes/census-proposal-fleet-examined-519.md
new file mode 100644
index 000000000..a39086e16
--- /dev/null
+++ b/docs/superpowers/notes/census-proposal-fleet-examined-519.md
@@ -0,0 +1,11 @@
+# Census approval: fleet-examined-519
+
+Ruling `census-ruling-fleet-examined-519`. The independent reviewer approves or rejects every change below, 0 with a new disposition; nothing goes to the census owner (Paul, #280, 2026-10-26).
+
+Envelopes re-pinned: `internal/provision`.
+
+Review: a model from the other family than the author reads the branch's diff against main on the amadan.net remote (`origin` or `amadan`, whichever points at amadan.net) and gives a verdict for every unit and every re-pinned envelope above. For a unit, compare the change with its recorded disposition and basis below; for an envelope, read every changed function in the package and what it reaches. Reject if the change lets root open, run, query or follow anything it did not before from a path or input a tenant, an app or a box agent can create, write or name; if it weakens a check, refusal, validation, argument or environment the basis relies on; or if the diff cannot settle either. Otherwise approve. Record each verdict on #280 with the tip. A rejected unit goes back to the author to correct; nothing escalates to the census owner.
+
+Seal: `3b6cd29b87d2728254936722ab45fdadcfbb8c1f5b74fdfa19d1921b9dfd1dbe` → `3b6cd29b87d2728254936722ab45fdadcfbb8c1f5b74fdfa19d1921b9dfd1dbe`.
+
+Overlay: `internal/provision/testdata/plan14-root-reads-fleet-examined-519.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`.
diff --git a/docs/superpowers/notes/reviews/ASTRA-FINDINGS-fleet-examined-519-r1.md b/docs/superpowers/notes/reviews/ASTRA-FINDINGS-fleet-examined-519-r1.md
new file mode 100644
index 000000000..9cfd1e69a
--- /dev/null
+++ b/docs/superpowers/notes/reviews/ASTRA-FINDINGS-fleet-examined-519-r1.md
@@ -0,0 +1,46 @@
+# fleet-examined-519 — review round 1 of 3
+
+Reviewed `5394c7f958e4c10f93c94f923211c0814680ff4d..c01c563008a4b92eed63982042f6045c2bac5923`. No earlier rounds were supplied. References below are to the reviewed tip. No repository files were changed.
+
+## P1 findings
+
+### 1. A new fleet identity does not establish that its storage is new or inventoried
+
+**Location:** `internal/console/hostsused.go:338–368`; the new paragraph in spec section 3.
+
+**Problem and verified evidence:** The only eligibility checks are absence from `Examined`/`Closed` and absence of a shared bucket with a recorded closed fleet. `rosterFleet` merely lists the bucket name and every non-detached box (`internal/console/hostsused_activate.go:161–175`); the caller then records all of them as examined. Fleet creation accepts a caller-supplied bucket after a name-shape check (`internal/console/fleets.go:214–259`), and `CreateFleet` inserts a registry row, not a newly provisioned empty bucket (`internal/registry/fleets.go:253–277`). Box registration also inserts or reactivates a logical identity; it does not prove that the machine or its data directory is new (`internal/registry/fleets.go:441–501`). Thus even a genuinely post-activation fleet can point at pre-existing storage absent from the activation roster.
+
+**Failure scenario:** A bucket outside the activation roster contains a current replica for a deleted, pre-history hostname H, with no surviving record or mark. After activation, create fleet F naming that bucket and add its first box. The bucket is not in `Closed`, so this change declares it examined without importing H. Creating H on F now succeeds. The reader still restores from the configured bucket and hostname prefix (`internal/activator/backend_exec.go:1001`; `internal/activator/activator.go:150–153`), so the new record can read the earlier replica. The closed-bucket exclusion does not cover this case.
+
+The stronger claim that an unrecorded fleet must itself be new is also unsupported across registry changes. For example, activation can run against an older registry snapshot that omits F, followed by restoration of a snapshot containing F and its old boxes. Activation compares its roster with the registry visible during that command (`hostsused_activate.go:349–355`), but the start-up tripwire checks records and marks, not registry continuity (`hostsused_tripwire.go:44–87`). Adding one box then records every old non-detached box too. Previously S4 kept such a fleet unavailable.
+
+**Verification:** An additional local Go-overlay witness exercised the real fleet-create, add-box, app-create and instance-create HTTP doors. With a bucket absent from the activation roster and no inventory import, the instance door returned **201** and persisted `old.go.tito.io` on `fleet/classic`. This verifies the admission path; the old-replica read consequence above was checked in source, not against a live bucket.
+
+**Concrete fix:** Keep unproven targets unexamined and require the existing offline inventory. An online exception needs positive evidence that the actual readable storage is fresh or completely inventoried, bound to the fleet and activation; absence of a fleet name, its creation timestamp, or a new box label is insufficient. Add regression cases for an existing bucket and an old fleet reintroduced by a registry restore.
+
+**Invariant / fault family:** Inventory coverage before admission: no new data-kind record over earlier data that a box can still read.
+
+### 2. A committed mode write with a lost reply permanently strands the first-box operation
+
+**Location:** `internal/console/hostsused.go:350–372`.
+
+**Problem and verified evidence:** Any error from `WriteHostsState` detaches the new box, while retaining the old cached mode and ETag. A store error does not prove the PUT failed to commit: the S3 implementation returns the client error without resolving the stored outcome (`internal/release/store.go:992–1007`). `loadHostsLocked` does not refresh an already loaded mode (`hostsused.go:104–107`).
+
+**Failure scenario:** The mode PUT commits F into `Examined`, but its response is lost or the request times out. The handler detaches F's only box and returns 503 without its token. A retry reactivates the row, attempts the mode PUT with the stale ETag, receives a CAS conflict, and detaches it again. Subsequent new-fleet recordings in this process also use that stale ETag. Restarting reloads the committed state, but now N9 refuses reactivation because F is recorded (`hostsused.go:338–339`). Token rotation cannot repair the detached status (`internal/registry/fleets.go:524`). Recovering F requires the offline invalidate/inventory cycle that this change was intended to avoid.
+
+**Verification:** An additional Go-overlay witness wrapped the real store so the first mode PUT committed and then returned `context.DeadlineExceeded`. Through the real add-box HTTP door, the initial request returned 503, retry after the transient fault cleared returned **503/CAS conflict**, and retry after a mode-cache reload returned **409/N9**. The box was detached although the persisted mode examined its fleet. The witness failed its recovery assertion as expected.
+
+**Concrete fix:** Resolve an indeterminate mode write before detaching. Read back the state and ETag under the lock; if the intended recording committed, reconcile the cache and complete the operation without detaching its box. If read-back cannot establish the outcome, retain a recoverable pending operation rather than converting uncertainty into an irreversible N9 state. Cover committed-but-error, read-back failure and subsequent retry. The existing failure test only injects an error before the PUT (`hostsused_coverage_test.go:372`; `lifetimes_create_test.go:87–93`).
+
+**Invariant / fault family:** Recoverable enrollment across the registry and mode-store writes; a transient storage response failure must not leave an examined fleet with an unusable first box.
+
+## Other checks and validation
+
+- No separate P2 or P3 findings.
+- The requested targeted tests passed: `go test ./internal/console/ -run 'TestNewFleet|TestFleetGrowth' -count=1`.
+- The mutex serializes first-box recordings with each other and with in-process invalidation. The copied `Examined` slice and replacement `FleetTargets` map avoid mutating the cached state's containers; the carried target slices are not modified here. The ordinary successful-write path updates the cached ETag.
+- A pending start-up check still blocks data-kind admission through `admitDataCreate`; recording a fleet does not itself set `verified`. Recorded fleets still receive N9. Invalidated-mode additions are not marked examined by this function.
+- The added tests exercise real add-box requests, but call `gateDataCreate` directly for data admission and manually set `verified=true` after reset; they do not exercise a real start-up tripwire. The extra HTTP witness above checked the actual instance-create path.
+- No full test suite, production access or subagents were used. Temporary overlay sources and logs were removed after recording their results here.
+
+NOT READY
diff --git a/docs/superpowers/notes/reviews/ASTRA-FINDINGS-fleet-examined-519-r2.md b/docs/superpowers/notes/reviews/ASTRA-FINDINGS-fleet-examined-519-r2.md
new file mode 100644
index 000000000..c84638a67
--- /dev/null
+++ b/docs/superpowers/notes/reviews/ASTRA-FINDINGS-fleet-examined-519-r2.md
@@ -0,0 +1,56 @@
+Round-1 P1 1: resolved by Paul's 2026-11-02 ruling; owner-named storage and pre-activation registry restores are accepted limits, stated in the code comment and spec section 3.
+Round-1 P1 2: partly resolved; read-back handles an already committed write, but a write that commits after the read-back snapshot can still strand enrollment.
+
+# fleet-examined-519 — review round 2 of 3
+
+Reviewed `5394c7f958e4c10f93c94f923211c0814680ff4d..bc8c1e2701d619f00581182313b8a46b556b93f5`, including the round-1 fixes from `c01c5630`. References are to that tip. No repository files were changed.
+
+## P1 findings
+
+### 1. An old read-back value does not settle an outstanding mode write
+
+**Problem and verified evidence:** `internal/console/hostsused.go:380–390` treats a read-back without the fleet in `Examined` as proof that the failed write did not land, then detaches its box through `undo` at lines 362–367. A transport error can leave the remote PUT outstanding. The GET can read the old value before that PUT commits, even with strongly consistent reads. The S3 implementation returns the client error without a completion barrier (`internal/release/store.go:992–1007`); `ReadHostsState` is one GET (`internal/provision/hostsused.go:152–167`). The mutex serializes console callers, but cannot finish an outstanding remote operation.
+
+There is a related false-success path: lines 388–393 accept any active read-back containing the fleet name, without checking that its recorded targets cover the box being added. A delayed earlier enrollment can therefore be mistaken for the current enrollment.
+
+**Failure scenario:**
+
+1. Adding `classic/box-1` inserts the active box and sends the mode PUT with ETag E. The caller receives a transport error while the remote write is still outstanding.
+2. Read-back takes its snapshot of the old mode. The outstanding conditional PUT then commits, recording `box-1`; the GET returns its old snapshot.
+3. The handler caches that old snapshot, detaches `box-1`, and returns 503 without a token. Persisted state now examines the fleet but its only box is detached.
+4. After a mode-cache reload, adding `box-1` returns 409/N9 at `hostsused.go:350–351`. Rotation returns a token but cannot restore active status: `SetFleetBoxToken` updates only the token and revision (`internal/registry/fleets.go:524`). The fleet requires offline recovery again.
+
+Without a reload, adding a different label demonstrates the false success instead. The handler inserts `box-2`, loses its mode PUT against E, reads the committed recording of `box-1`, and returns 200 with `box-2`'s token because only fleet membership is checked. Coverage then refuses data-kind creation because `box-2` is absent from `FleetTargets` (`hostsused.go:261–267`).
+
+**Verification:** A temporary Go overlay added `TestReview519LateModeCommit`, exercising the real fleet-create, add-box and rotate-token HTTP doors. Its store wrapper retained the first conditional mode PUT while returning a transport error. On the following GET it read the old bytes, committed that retained PUT using its original ETag, then returned the old bytes. This models the read preceding completion of the outstanding write; it requires neither a second console nor an eventually consistent store.
+
+Both regression assertions failed as expected:
+
+- `retry-after-reload`: initial add **503**, persisted fleet examined, **no active boxes**; retry after `hosts.reset()` and `LoadHostsMode` **409/N9**; rotate **200**, still **no active boxes**.
+- `retry-different-label`: initial add **503**; adding `box-2` **200 with a token**, while persisted targets still named `box-1`; `gateDataCreate` returned **409/S4**.
+
+This verifies the application's failure under the injected transport ordering. No live S3 fault experiment was performed.
+
+**Concrete fix:** Treat an ambiguous PUT as pending even when one GET still returns the old value. Keep its box recoverable until the outstanding write is settled or prevented from committing; do not detach solely on that negative read-back. Before declaring an enrollment successful, check that the persisted targets cover the intended box and roster. Centralize this recovery invariant and guard it with delayed-commit, restart and different-label retry tests. The existing `landedButErrs` test commits before returning the error (`hostsused_coverage_test.go:401–407`); the read-back-failure case fails before the PUT commits (lines 458–487), so neither witnesses this ordering.
+
+**Invariant / fault family:** Recoverable enrollment across the registry and mode-store writes: a transient storage response failure must not leave an examined fleet with an unusable first box. This is the same family as round-1 P1 2.
+
+## P2 and P3 findings
+
+None separate from the P1 above.
+
+## Other checks and validation
+
+- The requested `go test ./internal/console/ -run 'TestNewFleet|TestFleetGrowth' -count=1` passed. `git diff --check 5394c7f9..bc8c1e27` passed.
+- Under the declared single-console/offline-activation model, activation enumerates every fleet, compares the current roster, and records each fleet as examined or closed (`hostsused_activate.go:105–141`, `349–364`, `447–461`). Adds while invalidated remain unrecorded until offline activation. Registry replacement and owner-supplied old storage were assessed under Paul's accepted limits, not raised again.
+- Closed-fleet bucket sharing and missing closed-fleet target entries leave the new fleet unrecorded (`hostsused.go:356–360`). Examined targets retain their marks; the new path does not erase any marks or activate regions. Fleet box target names include both fleet and label (`hostsused_activate.go:172`).
+- The mutex covers the registry addition, roster read and mode update. It serializes competing first-box additions with invalidation and its persistence loop. `Examined` is cloned and `FleetTargets` gets a new map; existing target slices are not modified. Successful writes and successful read-backs update the ETag. Recording a fleet does not set `verified`, so a pending start-up check continues to block data-kind admissions.
+- The handler preserves the distinction between `ErrFleetBoxActive` and registry failures (`fleets.go:429–440`). A failed rollback can leave a tokenless active row, but while the fleet remains unexamined S4 still refuses data-kind admission.
+- The added tests exercise the real add-box door and app-create door. Their data-admission assertions call `gateDataCreate` directly; their simulated restart sets `verified` manually. These are narrower witnesses than an instance-create request through a real start-up check.
+- Changed production code is confined to `internal/console`; the other changes are its tests and Markdown. No changed file is in the root-binary census scope. No full suites, production access or subagents were used. Temporary overlay sources and logs were removed after recording their results.
+
+## Stopping rule
+
+Round 1 found the storage-provenance issue, now resolved by Paul's ruling, and the enrollment-recovery defect. Round 2 still finds the enrollment-recovery defect under an outstanding-write ordering. This is two consecutive rounds in the same fault family, so repository stopping rule 2 applies: stop incremental fixes and ask Paul to choose between requiring offline inventory up front, cutting automatic first-box recording, or enforcing recoverable enrollment in one place with a guard test or simulation. I recommend the third option if online first-box recording remains required. This review does not authorize another patch-and-review cycle; the round history remains 2 of 3.
+
+NOT READY
diff --git a/docs/superpowers/notes/reviews/ASTRA-FINDINGS-fleet-examined-519-r3.md b/docs/superpowers/notes/reviews/ASTRA-FINDINGS-fleet-examined-519-r3.md
new file mode 100644
index 000000000..4fc390efa
--- /dev/null
+++ b/docs/superpowers/notes/reviews/ASTRA-FINDINGS-fleet-examined-519-r3.md
@@ -0,0 +1,64 @@
+Round-1 P1 1: resolved by Paul's 2026-11-02 ruling; owner-named storage, later detach/recompletion of the first label, and pre-activation registry restores are accepted limits.
+Round-1 P1 2: resolved; the mode is written first, ambiguous mode writes clear the cache without adding or detaching a box, and the recorded first label remains completable.
+Round-2 P1 1: resolved; an old read cannot authorize adding another label, and a delayed winning write leaves its first label completable.
+
+# fleet-examined-519 — review round 3 of 3
+
+Reviewed `5394c7f958e4c10f93c94f923211c0814680ff4d..90ab5c387e14c870d2b0ebfe219d7e09a1f035ac`, including the rework from `bc8c1e27`. The amadan `origin/main` reference and a read-only remote lookup both identify the stated base. References below are to the reviewed tip. No repository files were changed.
+
+## P1
+
+None.
+
+## P2
+
+None.
+
+## P3 follow-up
+
+### 1. Qualify the comment's promise about failures
+
+**Evidence:** `internal/console/hostsused.go:324–335` says “every failure answers 503 and leaves the registry as it was,” but explicitly recognizes a committed registry add with a lost reply immediately afterward. Registry errors are returned at lines 366 and 405 and become HTTP 500 at `internal/console/fleets.go:434–440`. The fault wrapper deliberately models an add that commits before returning an error (`hostsused_coverage_test.go:463–475`).
+
+**Scenario:** The mode commits, the registry add commits, and its reply is lost. The operation reports an error with an active, recorded box present; another add receives N9, and token rotation supplies a usable credential. This is the accepted recovery path, not a production defect.
+
+**Concrete fix:** Narrow the unchanged-registry/503 statement to mode-read, roster-read and mode-write failures. State separately that a registry failure can leave an active recorded box and require token rotation. Keep the implementation's existing error distinction.
+
+**Fault family:** Documentation of enrollment recovery. Follow-up only; this does not reopen the review.
+
+## Checks against the brief
+
+- **Write ordering and recovery:** `hostsused.go:379–405` constructs the target and `FirstBox` together and writes them through the mode's existing ETag before calling `AddFleetBox`. An error clears the cached state and ETag without changing the registry. A late PUT and a retry using the same old ETag cannot commit different recordings: `WriteHostsState` forwards the precondition (`internal/provision/hostsused.go:174–184`), and the real S3 store sends `IfMatch` (`internal/release/store.go:980–1009`). If the late write wins after a GET captured the old state, the retry loses its conditional write, clears its cache, and reads the winner next time. It cannot return success for its own unrecorded label. If the earlier write never lands, the retry can record and add its box.
+- **Registry failures:** Once a recording commits, a failed-before-commit add leaves the first label eligible at `hostsused.go:364–366`, including after restart. A committed add with a lost reply leaves an active recorded box. The registry's atomic conflict guard prevents an add from replacing an active box's token (`internal/registry/fleets.go:479–501`); `SetFleetBoxToken` supplies recovery without changing status (`fleets.go:504–535`). No enrollment path detaches a box. The literal “every failure leaves the registry unchanged” is therefore too broad, as noted above, but the recovery mechanism is sound under the stated fault model.
+- **Concurrent calls:** The same history mutex covers loading, eligibility, recording and the registry add (`hostsused.go:347–405`). Concurrent add-box requests are serialized. A pending remote PUT can outlive that lock, but retains its original ETag and cannot overwrite a later successful recording. Invalidation uses the same lock and conditional writes (`hostsused.go:438–468`, `489–515`). This assessment uses the design's single-console model.
+- **Exception boundaries:** A recorded fleet passes only for its non-active first label and only when it is not closed (`hostsused.go:363–368`). HTTP input rejects an empty label (`fleets.go:406–410`), so an absent map entry cannot match. Activation creates a fresh state without `FirstBox` (`hostsused_activate.go:447–462`); activation-roster fleets therefore gain no exception. Another label remains N9. The closed-bucket and missing-target cases retain the explicitly accepted unrecorded/offline path (`hostsused.go:370–374`).
+- **Invalidation copy:** Comparing all fields of `HostsState` (`internal/provision/hostsused.go:130–151`), the new copy at `hostsused.go:454–455` preserves exactly the formerly copied fields plus `FirstBox`; mode, reason and time are still replaced. No slice or map is mutated there. It agrees with the existing retry and offline-invalidation copies (`hostsused.go:505–507`; `hostsused_activate.go:488–490`). A fresh activation drops the first-label exceptions. The latch, refusal and persistence behavior is unchanged.
+- **Simulation:** The wrappers delegate to the real fixture store and registry. Held writes retain their original bytes and ETag, including when they land after a GET has captured the old value (`hostsused_coverage_test.go:397–475`); the directory store enforces that ETag under its mutex (`internal/release/store.go:496–532`). The simulation checks successful additions against persisted targets, checks every active box of a recorded fleet, and checks recovery and data admission after faults stop (`hostsused_coverage_test.go:517–591`). It is a useful bounded witness, not an exhaustive schedule proof: it holds at most one outstanding PUT, calls additions sequentially, and simulates a restart by resetting the mode cache with the tripwire already verified. Concurrency and the real tripwire were also inspected in source.
+
+## Validation
+
+All checks of the reviewed tip passed:
+
+- `go test ./internal/console/ -run 'TestNewFleet|TestFleetGrowth' -count=1` (including the default 150 simulation seeds).
+- `go test ./internal/console -run '^Test(FailedInvalidationStillRefuses|ReactivateFromInvalidated|InvalidateOffline|TripwireInvalidatesOnUnmarkedRecord)$' -count=1`.
+- `go test ./internal/provision -run '^(TestPlan14RootReadCensus|TestCensusScopeIsTheRootBinary)$' -count=1`.
+- `git diff --check 5394c7f9..90ab5c38`.
+
+Two temporary Go-overlay checks tested whether the new tests reject the old behavior:
+
+1. Substituting round two's `hostsused.go` made `TestNewFleetLateModeWrite` fail at line 626: adding `box-2` returned **200** while the delayed write recorded `box-1`, instead of the required 503. This is the exact prior false-success ordering.
+2. The simulation initially rejected round two immediately because it has no `FirstBox`. To avoid treating that schema difference as evidence of fault coverage, a second overlay added only the new metadata to the old ordering. The simulation then failed its recovery assertion at seed 29: an active box remained on an unrecorded fleet after recovery. Thus its recovery assertion detects an actual enrollment failure beyond the missing-field mismatch.
+
+These overlays did not change the checkout. Their sources and logs were removed after the results were recorded. No full suites, production operations or subagents were used.
+
+## Census verdict
+
+**APPROVE the `internal/provision` envelope** in `internal/provision/testdata/plan14-root-reads-fleet-examined-519.tsv:3`, fingerprint `e9a018eea2b8a748db347575b5d7e5d1ec4dfc34ff5745cb3433690c9eac4a4a`, at tip `90ab5c387e14c870d2b0ebfe219d7e09a1f035ac`.
+
+The only production-source change in that package is the optional `HostsState.FirstBox` field and its comment (`internal/provision/hostsused.go:142–145`). No function body changes. I read the enclosing schema at lines 128–152 and its readers/writers at lines 154–195: the field adds JSON metadata to the existing fixed `@mode` read/write, retains old-body compatibility, and changes neither the key nor its conditional-write precondition. I also read its only behavioral consumer, `internal/console/hostsused.go:347–405`, and activation's fresh-state construction at `hostsused_activate.go:447–462`.
+
+The field does not cause root to open, run, query or follow a new tenant-, app- or agent-named input, and no root validation or refusal is weakened. There are no changed units or dispositions requiring separate verdicts. The census and root-binary scope tests pass. This file records the reviewer's approval for the author to cite on #280; no discussion post was made.
+
+The first round with no P1 ends review under stopping rule 1. The P3 goes on the branch's follow-up list; no fourth round is requested.
+
+READY
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 973d04b27..e72858822 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
@@ -54,6 +54,8 @@ Deleted history and noncurrent versions are not sources, because they are harmle
**After completion, unexamined targets are refused.** A region, pool or fleet that was not in the roster gets S4 for data-kind creates, and the nearest-region picker skips it, until its own inventory is imported.
+**A fleet created after completion is recorded at its first box (#519, 2026-11-02).** Activation records every fleet on its roster, so a fleet the history has not recorded was created since. No box of it existed before completion, so none holds its old data. Its first add-box, with the console serving, records the fleet as examined before it adds the box: its targets are its bucket, its boxes so far and the new box, and the new label is its first box (`first_box`). Its next add-box is N9 like any recorded fleet's, except its first-box label while no box of that label is active, which completes the enrollment. A box is never added before the record lands and never detached, so a write of the mode that errs, lands late or never lands is finished by the same add-box again (Paul's ruling on Astra r2; `TestNewFleetEnrollmentSimulation`). A bucket that a closed fleet also uses was never scanned: such a fleet is left unrecorded and completes offline, as before. **What this takes on trust (Paul, 2026-11-02, on Astra r1 P1 1):** the console never reads a fleet's bucket or boxes, so storage the owner names is examined as new, as anything they copy into an examined fleet's storage later would be. The first-box label stays completable after a detach, on the same terms. A registry restored to a snapshot from before activation is outside it too.
+
## 3a. The activation window (accepted 2026-10-26)
A one-time maintenance window wraps the inventory. It closes round 3's P1: a marked allocation started before activation and still pending could otherwise publish over old data after `complete` (recovery's "our slot, absent record" branch, lifetimes_recovery.go:204).
diff --git a/internal/console/fleets.go b/internal/console/fleets.go
index 39b54b7f0..681e6c5a7 100644
--- a/internal/console/fleets.go
+++ b/internal/console/fleets.go
@@ -409,26 +409,29 @@ 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)
jsonError(w, http.StatusInternalServerError, "could not mint a token — try again")
return
}
+ // The hostname history's fleet rules wrap the write
+ // (addFleetBoxRecorded): a fleet it recorded takes no new or
+ // reactivated box while it is active (N9, Paul's ruling on #404), and
+ // a fleet created since activation is recorded at its first box (#519).
+ // AddFleetBox both adds and reactivates, so this covers both.
+ //
// The fleet is already proven to exist (apiFleet), so AddFleetBox's own
// "no fleet" case is unreachable here — but a tx/busy/disk failure is
// not, and must not be rendered as the ordinary duplicate-box 409:
// errors.Is against the sentinel is what tells the two apart, rather
// than assuming every failure here is the uniqueness guard.
- if err := reg.AddFleetBox(registry.FleetBox{Fleet: fleet.Name, Label: label, TokenHash: hash, Status: "active"}); err != nil {
+ ref, err := s.addFleetBoxRecorded(r.Context(), reg, *fleet, registry.FleetBox{Fleet: fleet.Name, Label: label, TokenHash: hash, Status: "active"})
+ if ref != nil {
+ writeDoorRefusalJSON(w, r, ref)
+ return
+ }
+ if err != nil {
if errors.Is(err, registry.ErrFleetBoxActive) {
jsonError(w, http.StatusConflict, "fleet "+fleet.Name+" already has an active box "+label)
return
diff --git a/internal/console/hostsused.go b/internal/console/hostsused.go
index e38c0160d..eb7cdf060 100644
--- a/internal/console/hostsused.go
+++ b/internal/console/hostsused.go
@@ -4,6 +4,7 @@ import (
"context"
"errors"
"log"
+ "maps"
"net/http"
"os"
"slices"
@@ -218,7 +219,7 @@ func (s *Server) hostsTargetRefusal(ctx context.Context, region string) *doorRef
// 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
+// since is refused at its own door (addFleetBoxRecorded); 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 (one snapshot, which also names the place), or
@@ -299,21 +300,110 @@ func (s *Server) gateDataCreate(ctx context.Context, host, region string) *doorR
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)
+const msgFleetBoxNotAdded = "could not add the box — try again"
+
+// addFleetBoxRecorded is the add-box door's write, with the history's
+// fleet rules around it. Once the history is active:
+//
+// - A fleet the history recorded (examined or closed) takes no new or
+// reactivated box (N9, Paul's ruling on #404). Growing it means
+// invalidating the history, adding the box, and completing the
+// history again. The one exception is below.
+// - A fleet the history has not recorded was created since activation
+// (activation records every fleet on its roster, and refuses a
+// roster that changed under it). No box of it existed before, so
+// none can hold its old data, and no record can be placed on it
+// until it is recorded (S4). Its first add-box records it (#519),
+// naming the box: the fleet is examined, its targets its bucket, its
+// boxes so far and this one, and the label is its first box
+// (HostsState.FirstBox). Its next add-box is N9 like any other.
+// A bucket a closed fleet also uses was never scanned: the box is
+// added and the fleet left unrecorded, as before #519, to be
+// completed offline.
+//
+// The invariant (Paul's ruling on Astra r2, 2026-11-02): the mode is
+// written before the box is added, and a box is never detached here.
+// Two stores are written, the mode and the registry, and the mode write
+// can err and still land, even after a read that says it has not. So a
+// failure to read the mode or the fleet's targets, or to write the mode,
+// answers 503 and leaves the registry as it was; a mode write that errs
+// also forgets the held state, so the next caller reads the store. A
+// recorded fleet's add-box of its first-box label, while no box of that
+// label is active, completes the enrollment: the label's target is already
+// recorded. Whatever failed, the same add-box again finishes it
+// (TestNewFleetEnrollmentSimulation). A registry add that fails answers
+// its error: if it landed with the reply lost, the box is active and
+// recorded, and rotate-token gives it a token.
+//
+// It all runs under the lock every admission takes, so two add-boxes on a
+// new fleet cannot both record it. A mode that cannot be read refuses.
+// err is AddFleetBox's, for the door to tell a duplicate from a failure.
+//
+// What examining at the first box takes on trust (#519, Paul's ruling
+// 2026-11-02 on Astra r1, P1 1): the console never reads a fleet's bucket
+// or boxes, so storage the owner names is examined as new, as anything
+// they copy into an examined fleet's storage later would be. The first
+// box's label stays completable after a detach, on the same terms. A
+// registry restored to a snapshot from before activation is outside it.
+func (s *Server) addFleetBoxRecorded(ctx context.Context, reg consoleRegistry, fl registry.Fleet, box registry.FleetBox) (*doorRefusal, error) {
+ s.hosts.mu.Lock()
+ defer s.hosts.mu.Unlock()
+ if err := s.loadHostsLocked(ctx); err != nil {
+ log.Printf("console: hosts used: read the mode to add a box to fleet %s: %v", fl.Name, err)
+ return &doorRefusal{http.StatusServiceUnavailable, msgFleetBoxNotAdded}, nil
+ }
+ st, key := s.hosts.state, "fleet:"+fl.Name
+ if st.Mode != provision.HostsModeActive {
+ return nil, reg.AddFleetBox(box)
+ }
+ boxes, err := reg.ListFleetBoxes(fl.Name)
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"}
+ log.Printf("console: hosts used: list fleet %s's boxes: %v", fl.Name, err)
+ return &doorRefusal{http.StatusServiceUnavailable, msgFleetBoxNotAdded}, nil
}
- if st.Mode == provision.HostsModeActive && (slices.Contains(st.Examined, "fleet:"+fleet) || slices.Contains(st.Closed, "fleet:"+fleet)) {
- return &doorRefusal{http.StatusConflict, msgFleetInventoried(fleet)}
+ active := slices.ContainsFunc(boxes, func(b registry.FleetBox) bool { return b.Label == box.Label && b.Status == "active" })
+ if slices.Contains(st.Examined, key) || slices.Contains(st.Closed, key) {
+ if !slices.Contains(st.Closed, key) && st.FirstBox[key] == box.Label && !active {
+ return nil, reg.AddFleetBox(box)
+ }
+ return &doorRefusal{http.StatusConflict, msgFleetInventoried(fl.Name)}, nil
}
- return nil
+ for _, c := range st.Closed {
+ if ts, ok := st.FleetTargets[c]; !ok || (fl.Bucket != "" && slices.Contains(ts, "bucket:"+fl.Bucket)) {
+ log.Printf("console: hosts used: fleet %s is left unrecorded: its bucket may be %s's, which was closed, not scanned", fl.Name, c)
+ return nil, reg.AddFleetBox(box)
+ }
+ }
+ if active {
+ return nil, reg.AddFleetBox(box) // the duplicate answer, with nothing written
+ }
+ targets, err := rosterFleet(reg, fl)
+ if err != nil {
+ log.Printf("console: hosts used: record new fleet %s: read its targets: %v", fl.Name, err)
+ return &doorRefusal{http.StatusServiceUnavailable, msgFleetBoxNotAdded}, nil
+ }
+ next := st
+ next.Examined = sortedUnique(append(slices.Clone(st.Examined), key))
+ next.FleetTargets = maps.Clone(st.FleetTargets)
+ if next.FleetTargets == nil {
+ next.FleetTargets = map[string][]string{}
+ }
+ next.FleetTargets[key] = sortedUnique(append(targets, "box:fleet/"+fl.Name+"/"+box.Label))
+ next.FirstBox = maps.Clone(st.FirstBox)
+ if next.FirstBox == nil {
+ next.FirstBox = map[string]string{}
+ }
+ next.FirstBox[key] = box.Label
+ etag, err := provision.WriteHostsState(ctx, s.cfg.Releases, next, s.hosts.etag)
+ if err != nil {
+ // It may land yet: read the store next time, never this guess.
+ log.Printf("console: hosts used: record new fleet %s: write the mode: %v (no box added; the next caller reads the mode again)", fl.Name, err)
+ s.hosts.state, s.hosts.etag = provision.HostsState{}, ""
+ return &doorRefusal{http.StatusServiceUnavailable, msgFleetBoxNotAdded}, nil
+ }
+ s.hosts.state, s.hosts.etag = next, etag
+ log.Printf("console: hosts used: fleet %s recorded at its first box %s, targets %v", fl.Name, box.Label, next.FleetTargets[key])
+ return nil, reg.AddFleetBox(box)
}
// admitDataCreate is a data-kind create door's admission: S5 once
@@ -362,9 +452,8 @@ func (s *Server) invalidateHosts(ctx context.Context, reason string) error {
}
return err
}
- next := provision.HostsState{Mode: provision.HostsModeInvalidated, Reason: reason, Closed: s.hosts.state.Closed,
- Examined: s.hosts.state.Examined, FleetTargets: s.hosts.state.FleetTargets, RegionTargets: s.hosts.state.RegionTargets,
- At: time.Now().UTC()}
+ next := s.hosts.state
+ next.Mode, next.Reason, next.At = provision.HostsModeInvalidated, reason, time.Now().UTC()
etag, err := provision.WriteHostsState(ctx, s.cfg.Releases, next, s.hosts.etag)
if err == nil {
s.hosts.state, s.hosts.etag, s.hosts.latched = next, etag, ""
diff --git a/internal/console/hostsused_coverage_test.go b/internal/console/hostsused_coverage_test.go
index 6dc47d00e..5f4425e55 100644
--- a/internal/console/hostsused_coverage_test.go
+++ b/internal/console/hostsused_coverage_test.go
@@ -8,7 +8,12 @@ package console
import (
"context"
+ "fmt"
+ "math/rand"
"net/http"
+ "os"
+ "slices"
+ "strconv"
"strings"
"testing"
@@ -251,3 +256,415 @@ func TestCoverageRefusalReadsOneSnapshot(t *testing.T) {
t.Fatalf("reads = %d lists, %d gets, want 1 list and at most %d gets", counter.lists, counter.gets, len(files))
}
}
+
+// TestNewFleetRecordedAtFirstBox (#519): once active, a fleet created since
+// activation is recorded at its first add-box, examined with its bucket and
+// that box as its targets, so an app can be created placed on it and a
+// data-kind create there passes S4, with the console serving. Its next
+// add-box is N9, and the record survives a console start.
+func TestNewFleetRecordedAtFirstBox(t *testing.T) {
+ fx, token := placeFixture(t, "code-new-fleet")
+ activeAsNow(t, fx.srv)
+ if status, body := postJSON(t, fleetsURL(fx, fx.sqid)+"/new", map[string]string{"name": "classic", "bucket": "classic-data"}, token); status != http.StatusOK {
+ t.Fatalf("create fleet = %d %v", status, body)
+ }
+ if ref := fx.srv.hostsTargetRefusal(context.Background(), "fleet/classic"); ref == nil {
+ t.Fatal("a create on a new fleet with no box was admitted")
+ }
+ add := func(label string) (int, map[string]any) {
+ return postJSON(t, fleetsURL(fx, fx.sqid)+"/classic/boxes", map[string]string{"label": label}, token)
+ }
+ if status, out := add("box-1"); status != http.StatusOK {
+ t.Fatalf("first add-box on a new fleet = %d %v, want 200", status, out)
+ }
+ check := func(when string) {
+ t.Helper()
+ st, err := fx.srv.hostsState(context.Background())
+ if err != nil {
+ t.Fatal(err)
+ }
+ if st.Mode != provision.HostsModeActive || !slices.Contains(st.Examined, "fleet:classic") || !slices.Contains(st.Examined, "fleet:pi") {
+ t.Fatalf("%s: state = %+v, want active with classic and pi examined", when, st)
+ }
+ if got, want := st.FleetTargets["fleet:classic"], []string{"box:fleet/classic/box-1", "bucket:classic-data"}; !slices.Equal(got, want) {
+ t.Fatalf("%s: classic's targets = %v, want %v", when, got, want)
+ }
+ if _, ok := st.FleetTargets["fleet:pi"]; !ok {
+ t.Fatalf("%s: pi's targets were dropped: %+v", when, st.FleetTargets)
+ }
+ if ref := fx.srv.gateDataCreate(context.Background(), "x.go.tito.io", "fleet/classic"); ref != nil {
+ t.Fatalf("%s: a data-kind create on the recorded fleet = %+v, want admitted", when, ref)
+ }
+ }
+ check("recorded")
+ if status, out := add("box-2"); status != http.StatusConflict || out["error"] != msgFleetInventoried("classic") {
+ t.Fatalf("second add-box = %d %v, want 409 N9", status, out)
+ }
+ if got := activeFleetBoxes(t, fx, "classic"); !slices.Equal(got, []string{"box-1"}) {
+ t.Fatalf("active boxes = %v, want [box-1]", got)
+ }
+ status, _, out := rawReq(t, http.MethodPost, fx.ts.URL+"/api/cli/apps/"+fx.sqid+"/new", token, `{"name":"placed","place":"fleet/classic"}`)
+ if status != http.StatusOK && status != http.StatusCreated {
+ t.Fatalf("app create placed on the recorded fleet = %d %s, want it created", status, out)
+ }
+ // A console start reads the same record.
+ fx.srv.hosts.reset()
+ fx.srv.hosts.mu.Lock()
+ fx.srv.hosts.verified = true
+ fx.srv.hosts.mu.Unlock()
+ check("after a start")
+}
+
+// TestNewFleetNotRecorded: a new fleet's first add-box leaves it
+// unrecorded, as before #519, when its bucket is a closed fleet's (never
+// scanned) and before the history is active; a write of the mode that
+// fails adds no box, and the retry adds and records it.
+func TestNewFleetNotRecorded(t *testing.T) {
+ newFleet := func(t *testing.T, code, bucket string) (*consoleFixture, func(string) (int, map[string]any)) {
+ fx, token := placeFixture(t, code)
+ if status, body := postJSON(t, fleetsURL(fx, fx.sqid)+"/new", map[string]string{"name": "classic", "bucket": bucket}, token); status != http.StatusOK {
+ t.Fatalf("create fleet = %d %v", status, body)
+ }
+ return fx, func(label string) (int, map[string]any) {
+ return postJSON(t, fleetsURL(fx, fx.sqid)+"/classic/boxes", map[string]string{"label": label}, token)
+ }
+ }
+ unrecorded := func(t *testing.T, fx *consoleFixture) {
+ t.Helper()
+ st, err := fx.srv.hostsState(context.Background())
+ if err != nil {
+ t.Fatal(err)
+ }
+ if slices.Contains(st.Examined, "fleet:classic") || st.FleetTargets["fleet:classic"] != nil {
+ t.Fatalf("classic was recorded: %+v", st)
+ }
+ if ref := fx.srv.hostsTargetRefusal(context.Background(), "fleet/classic"); st.Mode == provision.HostsModeActive && ref == nil {
+ t.Fatal("a create on the unrecorded fleet was admitted")
+ }
+ }
+ t.Run("closed bucket", func(t *testing.T) {
+ fx, add := newFleet(t, "code-new-fleet-closed", "pi-fleet-data")
+ st, err := HostsActivation{Releases: fx.srv.cfg.Releases, Registry: fx.srv.cfg.Registry}.Roster(context.Background())
+ if err != nil {
+ t.Fatal(err)
+ }
+ delete(st.Fleets, "fleet:classic") // as if created since
+ forceHostsState(t, fx.srv, provision.HostsState{Mode: provision.HostsModeActive, Closed: []string{"fleet:pi"}, FleetTargets: st.Fleets, RegionTargets: []string{}})
+ for _, label := range []string{"box-1", "box-2"} {
+ if status, out := add(label); status != http.StatusOK {
+ t.Fatalf("add-box %s = %d %v, want 200", label, status, out)
+ }
+ }
+ unrecorded(t, fx)
+ })
+ t.Run("not active", func(t *testing.T) {
+ fx, add := newFleet(t, "code-new-fleet-incomplete", "classic-data")
+ if status, out := add("box-1"); status != http.StatusOK {
+ t.Fatalf("add-box = %d %v, want 200", status, out)
+ }
+ unrecorded(t, fx)
+ })
+ t.Run("write fails", func(t *testing.T) {
+ fx, add := newFleet(t, "code-new-fleet-write", "classic-data")
+ bucket := wrapBucket(fx)
+ st, err := HostsActivation{Releases: fx.srv.cfg.Releases, Registry: fx.srv.cfg.Registry}.Roster(context.Background())
+ if err != nil {
+ t.Fatal(err)
+ }
+ delete(st.Fleets, "fleet:classic")
+ forceHostsState(t, fx.srv, provision.HostsState{Mode: provision.HostsModeActive, Examined: []string{"fleet:pi"}, FleetTargets: st.Fleets, RegionTargets: []string{}})
+ bucket.setHook(failNth("put", provision.HostsModeKey, 1, false))
+ if status, out := add("box-1"); status != http.StatusServiceUnavailable || out["error"] != msgFleetBoxNotAdded {
+ t.Fatalf("add-box with the mode write failing = %d %v, want 503", status, out)
+ }
+ bucket.setHook(nil)
+ if got := activeFleetBoxes(t, fx, "classic"); len(got) != 0 {
+ t.Fatalf("active boxes after the failed write = %v, want none", got)
+ }
+ unrecorded(t, fx)
+ if status, out := add("box-1"); status != http.StatusOK {
+ t.Fatalf("retried add-box = %d %v, want 200", status, out)
+ }
+ if got := activeFleetBoxes(t, fx, "classic"); !slices.Equal(got, []string{"box-1"}) {
+ t.Fatalf("active boxes after the retry = %v, want [box-1]", got)
+ }
+ if ref := fx.srv.gateDataCreate(context.Background(), "x.go.tito.io", "fleet/classic"); ref != nil {
+ t.Fatalf("a data-kind create after the retry = %+v, want admitted", ref)
+ }
+ })
+}
+
+// modeFaults is a store whose writes of the mode can fail before they
+// land, land with the reply lost, or be held and land later (after a read
+// of the old value, or never), as an outstanding PUT can.
+type modeFaults struct {
+ release.Store
+ rng *rand.Rand
+ on bool
+ held *heldPut
+}
+
+type heldPut struct {
+ body []byte
+ ifMatch string
+}
+
+func (s *modeFaults) Put(ctx context.Context, key string, body []byte, ifMatch string) (string, error) {
+ if key != provision.HostsModeKey || !s.on {
+ return s.Store.Put(ctx, key, body, ifMatch)
+ }
+ switch s.rng.Intn(5) {
+ case 0: // fails before it lands
+ return "", errBucketDown
+ case 1: // lands, the reply lost
+ s.Store.Put(ctx, key, body, ifMatch)
+ return "", errBucketDown
+ case 2: // outstanding
+ if s.held == nil {
+ s.held = &heldPut{body: slices.Clone(body), ifMatch: ifMatch}
+ return "", errBucketDown
+ }
+ }
+ return s.Store.Put(ctx, key, body, ifMatch)
+}
+
+func (s *modeFaults) Get(ctx context.Context, key string) ([]byte, string, error) {
+ if key != provision.HostsModeKey || s.held == nil {
+ return s.Store.Get(ctx, key)
+ }
+ switch s.rng.Intn(3) {
+ case 0: // lands before the read
+ s.land(ctx)
+ return s.Store.Get(ctx, key)
+ case 1: // the read sees the old value, then it lands
+ b, e, err := s.Store.Get(ctx, key)
+ s.land(ctx)
+ return b, e, err
+ }
+ return s.Store.Get(ctx, key)
+}
+
+// land commits the held write as its PUT would: on its own ETag, so a
+// write that landed since makes it lose.
+func (s *modeFaults) land(ctx context.Context) {
+ h := s.held
+ s.held = nil
+ s.Store.Put(ctx, provision.HostsModeKey, h.body, h.ifMatch)
+}
+
+// boxFaults is a registry whose box adds can fail before or after they
+// land.
+type boxFaults struct {
+ consoleRegistry
+ rng *rand.Rand
+ on bool
+}
+
+func (r *boxFaults) AddFleetBox(b registry.FleetBox) error {
+ if r.on {
+ switch r.rng.Intn(5) {
+ case 0:
+ return errBucketDown
+ case 1:
+ if err := r.consoleRegistry.AddFleetBox(b); err != nil {
+ return err
+ }
+ return errBucketDown
+ }
+ }
+ return r.consoleRegistry.AddFleetBox(b)
+}
+
+// TestNewFleetEnrollmentSimulation (Paul's ruling on Astra r2, 2026-11-02):
+// a new fleet's first add-box under every ordering of mode-write and
+// box-add faults, retries with the same or another label, and console
+// starts. Every step: an add that answers success has its box recorded,
+// and a recorded fleet's active boxes are all its recorded targets (no
+// create is stuck behind S4). Once the faults stop: the same add-box
+// again (the first-box label, or any label while unrecorded) leaves the
+// fleet recorded with an active box and a data-kind create admitted,
+// with no offline cycle. CARLOS_SIM_SEEDS runs more seeds.
+func TestNewFleetEnrollmentSimulation(t *testing.T) {
+ fx, _ := placeFixture(t, "code-new-fleet-sim")
+ activeAsNow(t, fx.srv)
+ ctx := context.Background()
+ base := fx.srv.cfg.Releases
+ creg, err := openRegistry(fx.srv.cfg.Registry)
+ if err != nil {
+ t.Fatal(err)
+ }
+ seeds := 150
+ if n, err := strconv.Atoi(os.Getenv("CARLOS_SIM_SEEDS")); err == nil && n > 0 {
+ seeds = n
+ }
+ start := func() {
+ fx.srv.hosts.reset()
+ fx.srv.hosts.mu.Lock()
+ fx.srv.hosts.verified = true // the start-up check's own tests are elsewhere
+ fx.srv.hosts.mu.Unlock()
+ }
+ for seed := 0; seed < seeds; seed++ {
+ rng := rand.New(rand.NewSource(int64(seed)))
+ store := &modeFaults{Store: base, rng: rng, on: true}
+ reg := &boxFaults{consoleRegistry: creg, rng: rng, on: true}
+ fx.srv.cfg.Releases = store
+ start()
+ fl := registry.Fleet{Name: fmt.Sprintf("sim-%d", seed), Account: fx.sqid, Bucket: fmt.Sprintf("sim-%d-data", seed)}
+ if _, err := creg.CreateFleet(fl); err != nil {
+ t.Fatal(err)
+ }
+ key := "fleet:" + fl.Name
+ check := func(step string) {
+ t.Helper()
+ st, _, err := provision.ReadHostsState(ctx, base)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !slices.Contains(st.Examined, key) {
+ return
+ }
+ boxes, err := creg.ListFleetBoxes(fl.Name)
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, b := range boxes {
+ if b.Status == "active" && !slices.Contains(st.FleetTargets[key], "box:fleet/"+fl.Name+"/"+b.Label) {
+ t.Fatalf("seed %d %s: active box %s of recorded %s is not a recorded target %v", seed, step, b.Label, fl.Name, st.FleetTargets[key])
+ }
+ }
+ }
+ add := func(step, label string) bool {
+ t.Helper()
+ box := registry.FleetBox{Fleet: fl.Name, Label: label, TokenHash: fmt.Sprintf("%064x", rng.Int63()), Status: "active"}
+ ref, err := fx.srv.addFleetBoxRecorded(ctx, reg, fl, box)
+ ok := ref == nil && err == nil
+ if ok {
+ st, _, rerr := provision.ReadHostsState(ctx, base)
+ if rerr != nil {
+ t.Fatal(rerr)
+ }
+ if !slices.Contains(st.FleetTargets[key], "box:fleet/"+fl.Name+"/"+label) {
+ t.Fatalf("seed %d %s: add of %s answered success, but it is not recorded: %+v", seed, step, label, st)
+ }
+ }
+ check(step)
+ return ok
+ }
+ for i, n := 0, 1+rng.Intn(6); i < n; i++ {
+ if rng.Intn(4) == 0 {
+ start()
+ }
+ add(fmt.Sprintf("step %d", i), []string{"a", "b"}[rng.Intn(2)])
+ }
+ // The faults stop; an outstanding write lands or never does.
+ store.on, reg.on = false, false
+ if store.held != nil && rng.Intn(2) == 0 {
+ store.land(ctx)
+ }
+ store.held = nil
+ check("settled")
+ if rng.Intn(2) == 0 {
+ start()
+ }
+ // The way back: the same add-box again.
+ for i := 0; i < 2; i++ {
+ st, err := fx.srv.hostsState(ctx)
+ if err != nil {
+ t.Fatal(err)
+ }
+ label := "a"
+ if l, ok := st.FirstBox[key]; ok {
+ label = l
+ }
+ add(fmt.Sprintf("recovery %d", i), label)
+ }
+ st, err := fx.srv.hostsState(ctx)
+ if err != nil {
+ t.Fatal(err)
+ }
+ label := st.FirstBox[key]
+ if !slices.Contains(st.Examined, key) || !slices.Contains(activeFleetBoxes(t, fx, fl.Name), label) {
+ t.Fatalf("seed %d: after recovery %s is %+v with active boxes %v, want it recorded with its first box %q active", seed, fl.Name, st, activeFleetBoxes(t, fx, fl.Name), label)
+ }
+ if ref := fx.srv.gateDataCreate(ctx, fmt.Sprintf("x%d.go.tito.io", seed), "fleet/"+fl.Name); ref != nil {
+ t.Fatalf("seed %d: a data-kind create after recovery = %+v, want admitted", seed, ref)
+ }
+ }
+ fx.srv.cfg.Releases = base
+}
+
+// TestNewFleetLateModeWrite is Astra r2's ordering through the real door:
+// the first mode write is outstanding, the retry's read sees the old value
+// and then it lands. No box is added on a write that errs, so the first
+// label is completed by the same add-box again; another label is N9.
+func TestNewFleetLateModeWrite(t *testing.T) {
+ fx, token := placeFixture(t, "code-new-fleet-late")
+ if status, body := postJSON(t, fleetsURL(fx, fx.sqid)+"/new", map[string]string{"name": "classic", "bucket": "classic-data"}, token); status != http.StatusOK {
+ t.Fatalf("create fleet = %d %v", status, body)
+ }
+ r, err := HostsActivation{Releases: fx.srv.cfg.Releases, Registry: fx.srv.cfg.Registry}.Roster(context.Background())
+ if err != nil {
+ t.Fatal(err)
+ }
+ delete(r.Fleets, "fleet:classic")
+ forceHostsState(t, fx.srv, provision.HostsState{Mode: provision.HostsModeActive, Examined: []string{"fleet:pi"}, FleetTargets: r.Fleets, RegionTargets: []string{}})
+ add := func(label string) (int, map[string]any) {
+ return postJSON(t, fleetsURL(fx, fx.sqid)+"/classic/boxes", map[string]string{"label": label}, token)
+ }
+ base := fx.srv.cfg.Releases
+ late := &lateModeWrite{Store: base}
+ fx.srv.cfg.Releases = late
+ if status, out := add("box-1"); status != http.StatusServiceUnavailable {
+ t.Fatalf("add-box with its mode write outstanding = %d %v, want 503", status, out)
+ }
+ if got := activeFleetBoxes(t, fx, "classic"); len(got) != 0 {
+ t.Fatalf("active boxes = %v, want none", got)
+ }
+ // The retry with another label reads the old value; then box-1's
+ // write lands, so this one loses.
+ if status, out := add("box-2"); status != http.StatusServiceUnavailable {
+ t.Fatalf("add-box box-2 as box-1's write lands = %d %v, want 503", status, out)
+ }
+ if status, out := add("box-2"); status != http.StatusConflict || out["error"] != msgFleetInventoried("classic") {
+ t.Fatalf("add-box box-2 once classic is recorded = %d %v, want 409 N9", status, out)
+ }
+ if status, out := add("box-1"); status != http.StatusOK || out["token"] == nil {
+ t.Fatalf("add-box box-1 again = %d %v, want 200 with a token", status, out)
+ }
+ if got := activeFleetBoxes(t, fx, "classic"); !slices.Equal(got, []string{"box-1"}) {
+ t.Fatalf("active boxes = %v, want [box-1]", got)
+ }
+ if status, out := add("box-1"); status != http.StatusConflict {
+ t.Fatalf("add-box box-1 while active = %d %v, want 409", status, out)
+ }
+ if ref := fx.srv.gateDataCreate(context.Background(), "x.go.tito.io", "fleet/classic"); ref != nil {
+ t.Fatalf("a data-kind create = %+v, want admitted", ref)
+ }
+}
+
+// lateModeWrite holds the first write of the mode and answers an error;
+// the next read of the mode returns the old value and then lands it.
+type lateModeWrite struct {
+ release.Store
+ held *heldPut
+ done bool
+}
+
+func (s *lateModeWrite) Put(ctx context.Context, key string, body []byte, ifMatch string) (string, error) {
+ if key == provision.HostsModeKey && !s.done {
+ s.done = true
+ s.held = &heldPut{body: slices.Clone(body), ifMatch: ifMatch}
+ return "", errBucketDown
+ }
+ return s.Store.Put(ctx, key, body, ifMatch)
+}
+
+func (s *lateModeWrite) Get(ctx context.Context, key string) ([]byte, string, error) {
+ b, e, err := s.Store.Get(ctx, key)
+ if key == provision.HostsModeKey && s.held != nil {
+ h := s.held
+ s.held = nil
+ s.Store.Put(ctx, key, h.body, h.ifMatch)
+ }
+ return b, e, err
+}
diff --git a/internal/provision/hostsused.go b/internal/provision/hostsused.go
index ad59fce97..d83706222 100644
--- a/internal/provision/hostsused.go
+++ b/internal/provision/hostsused.go
@@ -139,6 +139,10 @@ type HostsState struct {
// RegionTargets is the listing targets the regions used at activation:
// closing a fleet never excuses one of them.
RegionTargets []string `json:"region_targets,omitempty"`
+ // FirstBox is, for each fleet recorded since activation at its first
+ // add-box (#519), that box's label: its add-box completes the
+ // enrollment while no box of that label is active.
+ FirstBox map[string]string `json:"first_box,omitempty"`
// Closed is the fleets closed instead of scanned ("fleet:<name>"),
// which take no data-kind create.
Closed []string `json:"closed,omitempty"`
diff --git a/internal/provision/testdata/plan14-root-reads-chain.tsv b/internal/provision/testdata/plan14-root-reads-chain.tsv
index 65cf22662..1092b4bd2 100644
--- a/internal/provision/testdata/plan14-root-reads-chain.tsv
+++ b/internal/provision/testdata/plan14-root-reads-chain.tsv
@@ -62,3 +62,4 @@ plan14-root-reads-domain-registration-1.tsv 8e7126042fef8cc99899a29e9e06c22763a2
plan14-root-reads-edge-held-streams.tsv c61b055182bf84e822fab92199432bd2d462c268c03ead17c3cfa18f09bd82cd
plan14-root-reads-edge-protect-hard-block.tsv 3b6cd29b87d2728254936722ab45fdadcfbb8c1f5b74fdfa19d1921b9dfd1dbe
plan14-root-reads-edge-held-first-ping.tsv 3b6cd29b87d2728254936722ab45fdadcfbb8c1f5b74fdfa19d1921b9dfd1dbe
+plan14-root-reads-fleet-examined-519.tsv 3b6cd29b87d2728254936722ab45fdadcfbb8c1f5b74fdfa19d1921b9dfd1dbe
diff --git a/internal/provision/testdata/plan14-root-reads-fleet-examined-519.tsv b/internal/provision/testdata/plan14-root-reads-fleet-examined-519.tsv
new file mode 100644
index 000000000..a5c1147d6
--- /dev/null
+++ b/internal/provision/testdata/plan14-root-reads-fleet-examined-519.tsv
@@ -0,0 +1,3 @@
+# Census overlay fleet-examined-519, written by census-propose (#369). census-ruling-fleet-examined-519, approved on #280 before the merge; the approval card is docs/superpowers/notes/census-proposal-fleet-examined-519.md.
+# 0 body, 0 sites, 1 envelope: each changed unit re-frozen at its existing disposition with its claim appended.
+@coverage internal/provision e9a018eea2b8a748db347575b5d7e5d1ec4dfc34ff5745cb3433690c9eac4a4a