carlos / platform Public

console: enroll a new fleet mode-first, completable by retry (#519)

Astra r2 (same family as r1 P1 2): a mode PUT that errs can land after
the read-back, so detaching on a negative read stranded the first box.
Paul chose mode first: record the fleet, naming its first box label,
before adding the box; never detach. A recorded fleet's add-box is N9
except that label while no box of it is active, so the same add-box
again finishes any failure. HostsState gains first_box (census overlay
fleet-examined-519, envelope only). A randomized simulation covers
fail-before, ack-lost and late-landing writes, box-add faults, retries
and console starts.

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

Prompt

Mode first, idempotent (Recommended) — Paul's answer on stopping rule 2 for #519

From this commit's own message. The prompt ledger has no entries for it — which is what a squashed, rebased or amended commit looks like, and what every commit looks like in a repo without a ledger.

Summary

Mode-first enrollment with idempotent completion; invalidation carries the whole state; simulation and late-write test.
claude agent, operated by paul@keymail.dev 90ab5c387e14c870d2b0ebfe219d7e09a1f035ac parent bc8c1e2
7 files changed, +338 −130
  • docs/superpowers/notes/census-proposal-fleet-examined-519.md +11 −0
  • docs/superpowers/specs/2026-10-26-nearest-region-without-claims-design.md +1 −1
  • internal/console/hostsused.go +58 −51
  • internal/console/hostsused_coverage_test.go +260 −78
  • 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 cancelled — superseded by a newer push — 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/specs/2026-10-26-nearest-region-without-claims-design.md b/docs/superpowers/specs/2026-10-26-nearest-region-without-claims-design.md
index 572815438..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,7 +54,7 @@ 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, adds the box and records the fleet as examined, its targets being its bucket and that box. Its next add-box is N9 like any recorded fleet's. A bucket that a closed fleet also uses was never scanned: such a fleet is left unrecorded and completes offline, as before. A write of the mode that errs is read back: if it landed the add succeeds, if not the box is detached again (its token was never shown). **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. A registry restored to a snapshot from before activation is outside it too.
+**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)
diff --git a/internal/console/hostsused.go b/internal/console/hostsused.go
index c2fab1357..88350190c 100644
--- a/internal/console/hostsused.go
+++ b/internal/console/hostsused.go
@@ -4,6 +4,7 @@ import (
"context"
"errors"
"log"
+ "maps"
"net/http"
"os"
"slices"
@@ -307,35 +308,42 @@ const msgFleetBoxNotAdded = "could not add the box — try again"
// - 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.
+// 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):
-// the box is added, then the fleet is examined, its targets as they
-// stand after the add. Its next add-box is N9 like any other.
-// The one exception is a bucket a closed fleet also uses, which was
-// never scanned: the box is added and the fleet left unrecorded, as
-// before #519, to be completed offline.
+// 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
+// every failure 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). An add that lands with
+// its reply lost leaves an active, recorded box; 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 write of the mode that errs may still
-// have landed (Astra r1, P1 2), so the state is read back: landed, the box
-// stays and the add succeeds; not landed, the box is detached again (its
-// token was never shown, so nothing has dialled in with it) and the retry
-// reactivates it. A read-back that fails too leaves the box and forgets the
-// held state, so the next caller reads the store: if the write landed, the
-// box is recorded and rotate-token gives it a token; if not, detaching it
-// and adding it again records the fleet. A mode that cannot be read
-// refuses. err is AddFleetBox's, for the door to tell a duplicate from a
-// failure.
+// 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. A registry
-// restored to a snapshot from before activation is outside it too.
+// 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()
@@ -347,54 +355,54 @@ func (s *Server) addFleetBoxRecorded(ctx context.Context, reg consoleRegistry, f
if st.Mode != provision.HostsModeActive {
return nil, reg.AddFleetBox(box)
}
+ boxes, err := reg.ListFleetBoxes(fl.Name)
+ if err != nil {
+ log.Printf("console: hosts used: list fleet %s's boxes: %v", fl.Name, err)
+ return &doorRefusal{http.StatusServiceUnavailable, msgFleetBoxNotAdded}, nil
+ }
+ 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
}
- if err := reg.AddFleetBox(box); err != nil {
- return nil, err
- }
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, nil
+ return nil, reg.AddFleetBox(box)
}
}
- undo := func(why string, err error) *doorRefusal {
- log.Printf("console: hosts used: record new fleet %s: %s: %v", fl.Name, why, err)
- if derr := reg.SetFleetBoxStatus(fl.Name, box.Label, "detached"); derr != nil {
- log.Printf("console: hosts used: record new fleet %s: detach box %s again: %v", fl.Name, box.Label, derr)
- }
- return &doorRefusal{http.StatusServiceUnavailable, msgFleetBoxNotAdded}
+ if active {
+ return nil, reg.AddFleetBox(box) // the duplicate answer, with nothing written
}
targets, err := rosterFleet(reg, fl)
if err != nil {
- return undo("read its targets", 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 = make(map[string][]string, len(st.FleetTargets)+1)
- for k, ts := range st.FleetTargets {
- next.FleetTargets[k] = ts
+ 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.FleetTargets[key] = sortedUnique(targets)
+ next.FirstBox[key] = box.Label
etag, err := provision.WriteHostsState(ctx, s.cfg.Releases, next, s.hosts.etag)
if err != nil {
- back, backTag, rerr := provision.ReadHostsState(ctx, s.cfg.Releases)
- if rerr != nil {
- log.Printf("console: hosts used: record new fleet %s: write the mode: %v; read it back: %v (box %s left active; the next caller reads the mode again)", fl.Name, err, rerr, box.Label)
- s.hosts.state, s.hosts.etag = provision.HostsState{}, ""
- return &doorRefusal{http.StatusServiceUnavailable, msgFleetBoxNotAdded}, nil
- }
- s.hosts.state, s.hosts.etag = back, backTag
- if back.Mode != provision.HostsModeActive || !slices.Contains(back.Examined, key) {
- return undo("write the mode", err), nil
- }
- log.Printf("console: hosts used: record new fleet %s: write the mode: %v, but it landed", fl.Name, err)
- etag, next = backTag, back
+ // 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, targets %v", fl.Name, next.FleetTargets[key])
- return nil, nil
+ 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
@@ -443,9 +451,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 082c70c94..5f4425e55 100644
--- a/internal/console/hostsused_coverage_test.go
+++ b/internal/console/hostsused_coverage_test.go
@@ -8,8 +8,12 @@ package console
import (
"context"
+ "fmt"
+ "math/rand"
"net/http"
+ "os"
"slices"
+ "strconv"
"strings"
"testing"
@@ -314,7 +318,7 @@ func TestNewFleetRecordedAtFirstBox(t *testing.T) {
// 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 detaches the box again, and the retry reactivates and records it.
+// 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)
@@ -390,99 +394,277 @@ func TestNewFleetNotRecorded(t *testing.T) {
})
}
-// landedButErrs commits the first Put of key and answers an error anyway,
-// as a write whose reply is lost would.
-type landedButErrs struct {
+// 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
- key string
- done bool
+ rng *rand.Rand
+ on bool
+ held *heldPut
}
-func (s *landedButErrs) Put(ctx context.Context, key string, body []byte, ifMatch string) (string, error) {
- etag, err := s.Store.Put(ctx, key, body, ifMatch)
- if err == nil && key == s.key && !s.done {
- s.done = true
+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 etag, err
+ return s.Store.Put(ctx, key, body, ifMatch)
}
-// TestNewFleetModeWriteAmbiguous (Astra r1, P1 2): a write of the mode that
-// errs is read back. Landed, the first box stays and the add succeeds, and
-// the next add-box is N9. Not landed and the read-back failing too, the box
-// is left active and the state is read again, so the next add-box records
-// the fleet with both boxes.
-func TestNewFleetModeWriteAmbiguous(t *testing.T) {
- setup := func(t *testing.T, code 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": "classic-data"}, token); status != http.StatusOK {
- t.Fatalf("create fleet = %d %v", status, body)
- }
- 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{}})
- return fx, func(label string) (int, map[string]any) {
- return postJSON(t, fleetsURL(fx, fx.sqid)+"/classic/boxes", map[string]string{"label": label}, token)
+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
}
}
- targets := func(t *testing.T, fx *consoleFixture) []string {
- t.Helper()
- st, _, err := provision.ReadHostsState(context.Background(), fx.srv.cfg.Releases)
- if err != nil {
- t.Fatal(err)
- }
- return st.FleetTargets["fleet:classic"]
+ 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)
}
- t.Run("landed", func(t *testing.T) {
- fx, add := setup(t, "code-new-fleet-landed")
- fx.srv.cfg.Releases = &landedButErrs{Store: fx.srv.cfg.Releases, key: provision.HostsModeKey}
- if status, out := add("box-1"); status != http.StatusOK || out["token"] == nil {
- t.Fatalf("add-box whose mode write landed but erred = %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 got, want := targets(t, fx), []string{"box:fleet/classic/box-1", "bucket:classic-data"}; !slices.Equal(got, want) {
- t.Fatalf("classic's targets = %v, want %v", got, want)
- }
- if status, out := add("box-2"); status != http.StatusConflict || out["error"] != msgFleetInventoried("classic") {
- t.Fatalf("next add-box = %d %v, want 409 N9", status, out)
+ 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)
}
- if ref := fx.srv.gateDataCreate(context.Background(), "x.go.tito.io", "fleet/classic"); ref != nil {
- t.Fatalf("a data-kind create on the recorded fleet = %+v, want admitted", ref)
+ 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])
+ }
+ }
}
- })
- t.Run("read-back fails", func(t *testing.T) {
- fx, add := setup(t, "code-new-fleet-unread")
- bucket := wrapBucket(fx)
- put, get := failNth("put", provision.HostsModeKey, 1, false), failNth("get", provision.HostsModeKey, 1, false)
- bucket.setHook(func(op, key string) error {
- if err := put(op, key); err != nil {
- return err
+ 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)
+ }
}
- return get(op, key)
- })
- if status, out := add("box-1"); status != http.StatusServiceUnavailable || out["error"] != msgFleetBoxNotAdded {
- t.Fatalf("add-box with the write and read-back failing = %d %v, want 503", status, out)
+ check(step)
+ return ok
}
- bucket.setHook(nil)
- if got := activeFleetBoxes(t, fx, "classic"); !slices.Equal(got, []string{"box-1"}) {
- t.Fatalf("active boxes = %v, want box-1 left active", got)
+ 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)
}
- if got := targets(t, fx); got != nil {
- t.Fatalf("classic recorded after a failed write: %v", got)
+ st, err := fx.srv.hostsState(ctx)
+ if err != nil {
+ t.Fatal(err)
}
- fx.srv.hosts.mu.Lock()
- fx.srv.hosts.verified = true // the start-up check had passed before
- fx.srv.hosts.mu.Unlock()
- if status, out := add("box-2"); status != http.StatusOK {
- t.Fatalf("next add-box = %d %v, want 200", status, out)
+ 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 got, want := targets(t, fx), []string{"box:fleet/classic/box-1", "box:fleet/classic/box-2", "bucket:classic-data"}; !slices.Equal(got, want) {
- t.Fatalf("classic's targets = %v, want %v", got, want)
+ 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