| index 0837c6a0d..c77575a4c 100644 |
| --- a/docs/superpowers/plans/2026-10-30-managed-fleets-1b-box-per-instance.md |
| +++ b/docs/superpowers/plans/2026-10-30-managed-fleets-1b-box-per-instance.md |
| @@ -1,4 +1,4 @@ |
| -# Managed fleets 1b: each instance runs on one named box Implementation Plan (rev 2) |
| +# Managed fleets 1b: each instance runs on one named box Implementation Plan (rev 3) |
| |
| > **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. |
| |
| @@ -8,7 +8,7 @@ |
| |
| **Tech Stack:** Go. `internal/provision`, `internal/registry`, `internal/edge`, `internal/console`, `internal/activator`, `internal/host`, `cmd/console`. |
| |
| -**Spec:** `docs/superpowers/specs/2026-10-28-managed-fleets-design.md` §4 Phase 1, "1b addendum", rules 1-10 (approved by Paul 2026-10-30; rule 6 his option 1; rule 8 his "gate and alert"; rules 5 and 10 revised after plan review R1). Code: main 65fd8060 (1a merged). Review history: round 1 `docs/superpowers/plans/CODEX-FINDINGS-MANAGED-FLEETS-1B-PLAN-R1.md` (7 P1, 4 P2), dispositions at the end of this plan. |
| +**Spec:** `docs/superpowers/specs/2026-10-28-managed-fleets-design.md` §4 Phase 1, "1b addendum", rules 1-10 (approved by Paul 2026-10-30; rule 6 his option 1; rule 8 his "gate and alert"; rules 5 and 10 revised after plan review R1). Code: main 65fd8060 (1a merged). Review history: round 1 `CODEX-FINDINGS-MANAGED-FLEETS-1B-PLAN-R1.md` (7 P1, 4 P2), round 2 `CODEX-FINDINGS-MANAGED-FLEETS-1B-PLAN-R2.md` (2 P1, 5 P2; stopping rule 2 on the restore and drain families; Paul chose "one rule each, enforced in one place"), both in `docs/superpowers/plans/`; dispositions at the end. Round 3 is the last. |
| |
| ## Global Constraints |
| |
| @@ -16,12 +16,13 @@ |
| - **Activation gate** (`release.FleetBoxLabelFloor = "v0.33.0"`; the release that ships this must be v0.33.0 or later): the console labels a fleet only when (a) the fleet has two or more active boxes, (b) the fleet has no sidecar records, (c) every box in the deployment, platform and fleet, reports a version at or above the floor in its heartbeat (the same complete box listing `carlos system status` reads; an incomplete listing counts as not met), and (d) the console's own version is at or above it. |
| - **Alert:** once a fleet has labels, a box in it reporting a version below the floor pauses all relabelling for that fleet and raises an alert (an ERROR log line naming fleet, box and version, plus `LABELS PAUSED` in `carlos fleets ls`), until every box is back at or above the floor. |
| - Every label write is a conditional update: the record's region, current label and `CreatedAt` must equal what the decision read, rechecked inside every retry of the update. |
| -- A stale local copy is set aside, never deleted. A box that set a copy aside and finds no replica refuses to start that instance. |
| +- **The start rule** (one function, `startAllowed`, Task 4): a fleet instance starts only from a copy kept under its current assignment, a restored replica, or empty when its record has never moved (`FleetBoxMoved` false) and no set-aside copy of it exists on this box. Stale copies are set aside, never deleted; the set-aside copy is the persistent reason to refuse. |
| +- **The drain rule** (one function, `drainDone`, Task 6): a draining box may be detached only when its newest heartbeat was composed after `draining_since` and reports no routes for the fleet and no held leases. |
| - The lease stays the one-writer guarantee. Lease take and release are unchanged. |
| - Lost box: no fresh heartbeat for `lease.LeaseTTL + 5*time.Minute` (20 minutes). |
| -- **Request budget** (asserted by store-call counting tests in Tasks 2 and 6): an idle worker pass costs, per labelled fleet, one heartbeat LIST plus one GET per box, then one LIST per placed app; zero record GETs and zero PUTs when nothing is unlabelled, lost or draining. A create on a labelled fleet adds one heartbeat read (memoised per request) and one inventory per fleet (one LIST per placed app). First labelling of a fleet reads each record once and each binding object once, then one PUT per record. A move or drain reads one inventory per pass and writes one PUT per moved record; load counts update in memory after each write. |
| +- **Request budget** (asserted by store-call counting tests in Tasks 2 and 6). The console keeps an in-process inventory cache per fleet: record and sidecar keys with their ETags from the LIST, and the decoded record; a record is re-read only when its ETag changed; any LIST error makes the inventory incomplete (no writes that pass). Per pass, per fleet with two or more active boxes: one heartbeat LIST plus one GET per box (memoised), one deployment-wide heartbeat listing for the gate (shared across fleets in the pass), and one instance LIST plus one sidecar LIST per placed app; record GETs only for changed ETags (zero when idle); zero PUTs when nothing is unlabelled, lost or draining. A create uses the same cache under the fleet lock. First labelling: one GET per record and per binding object, one PUT per record. A move or drain: one conditional update (a GET and a PUT) per moved record. Drain completion reads only the box's heartbeat. |
| - Member-facing strings (drain and detach refusals, the sidecar refusal, the paused state) get a Luna copy pass before merge; log lines do not. |
| -- Local tests: touched packages with `-run`; activator and host e2e tests with `TMPDIR=/tmp/k` (Unix socket path length, memory "Gate tmp exec wrapper"); Go builds in a worktree with `GOFLAGS=-buildvcs=false`; CI runs the full suite. Darwin and windows must cross-compile. |
| +- Local tests: touched packages with `-run`; activator and host e2e tests need a short temp root for Unix socket paths (memory "Gate tmp exec wrapper"): `R=$(mktemp -d /tmp/k.XXXX) && TMPDIR=$R go test ...; rm -r $R` (small, owned, removed); Go builds in a worktree with `GOFLAGS=-buildvcs=false`; CI runs the full suite. Darwin and windows must cross-compile. |
| - Neutral names (`shop`, `example.com`, fleet `pi`, boxes `pi-1`, `pi-2`). |
| |
| ## Review Focus |
| @@ -39,12 +40,12 @@ |
| **Files:** Modify `internal/provision/provision.go` (Record; `SetRecordRegion` :1023); create `internal/provision/fleetbox.go`; test `internal/provision/fleetbox_test.go`; census `internal/provision/plan9_b8_census_test.go` (name table :52-76, the inventory the test selects :369) and a new overlay layered on `fleetPublicRoutesWriteCensusInventory`. |
| |
| **Interfaces (produces):** |
| -- `Record.FleetBox string` (`json:"fleet_box,omitempty"`), `Record.FleetBoxAt string` (`json:"fleet_box_at,omitempty"`, RFC 3339 nanoseconds, UTC). |
| +- `Record.FleetBox string` (`json:"fleet_box,omitempty"`), `Record.FleetBoxAt string` (`json:"fleet_box_at,omitempty"`, RFC 3339 nanoseconds, UTC), `Record.FleetBoxMoved bool` (`json:"fleet_box_moved,omitempty"`): set true by a relabel from one non-empty label to another, never cleared (first labelling from "" leaves it false). |
| - `type FleetBoxExpect struct { Region, Label string; CreatedAt time.Time }`. |
| - `func SetRecordFleetBox(ctx context.Context, s release.Store, acct, app, host string, want FleetBoxExpect, label string, at time.Time) error` writes both fields when the current record's Region, FleetBox and CreatedAt equal `want`, rechecked inside each retry of the update; else `ErrFleetBoxMoved`. |
| - `SetRecordRegion` clears both fields when the region changes. |
| |
| -- [ ] **Step 1: Write the failing tests.** `TestRecordFleetBoxRoundTrip`; `TestSetRecordFleetBoxIsConditional` (label, then a stale `want` loses); `TestSetRecordFleetBoxLosesToAPlacementChange` (region changed between read and write: `ErrFleetBoxMoved`, record unlabelled); `TestSetRecordFleetBoxLosesToARecreate` (same host recreated with a new `CreatedAt`); `TestSetRecordRegionClearsTheBox`. |
| +- [ ] **Step 1: Write the failing tests.** `TestRecordFleetBoxRoundTrip`; `TestSetRecordFleetBoxIsConditional` (label, then a stale `want` loses); `TestSetRecordFleetBoxLosesToAPlacementChange` (region changed between read and write: `ErrFleetBoxMoved`, record unlabelled); `TestSetRecordFleetBoxLosesToARecreate` (same host recreated with a new `CreatedAt`); `TestMovedIsSetByABoxToBoxRelabelOnly` (""→`pi-1` false; `pi-1`→`pi-2` true; `pi-2`→`pi-1` stays true; `SetRecordRegion` clears label and time but the record is new in its fleet only if recreated: keep `FleetBoxMoved` as is); `TestSetRecordRegionClearsTheBox`. |
| - [ ] **Step 2: Run them to see them fail.** `go test ./internal/provision/ -run 'RecordFleetBox|SetRecordFleetBox|SetRecordRegionClears'` → FAIL. |
| - [ ] **Step 3: Implement** through the record's update scaffold (the path `SetRecordRegion` uses, `provision.go:1093-1139`), the expectation checked inside the mutation. |
| - [ ] **Step 4: Census.** Add `SetRecordFleetBox` to the typed-writer name table, extend the rejection witnesses, add the overlay and switch the test's selected inventory to it. `go test ./internal/provision/ -run 'RecordFleetBox|SetRecordFleetBox|SetRecordRegion|TestPlan9B8RecordWriteCensus'` → PASS. |
| @@ -57,14 +58,16 @@ |
| **Interfaces (produces):** |
| - `const release.FleetBoxLabelFloor = "v0.33.0"`. |
| - `type fleetView struct { Boxes []fleetBoxView; Active, HasSidecars, DeploymentCurrent bool; Load map[string]int }`; `type fleetBoxView struct { Label string; Fresh, Draining, RootfsReady, AtRootfsFloor, AtLabelFloor bool; LastSeen time.Time }`. |
| -- `func (s *Server) loadFleetView(ctx context.Context, fleet string) (fleetView, error)`: one heartbeat listing, one deployment-wide box listing for (c), one inventory (`AppsPlacedOn` plus `provision.ListRecordsCompleteJudged` per app) for `Load` and `HasSidecars`. An incomplete or truncated listing leaves `Active` false. |
| +- `func (s *Server) loadDeploymentBoxesComplete(ctx context.Context) (boxes []status.Box, complete bool, err error)`: every heartbeat prefix (platform regions, pools, every fleet) through `loadBoxes`, AND-ing each prefix's completeness flag; a skipped or unreadable heartbeat makes it incomplete. Not `systemBoxes`, which drops that flag (`apisystemupdate.go:270-287`). |
| +- `type fleetInventory struct` (the cache in Global Constraints) with `func (s *Server) fleetInventoryFor(ctx context.Context, fleet string) (records []provision.Record, sidecars int, complete bool, err error)`: per placed app, the instance LIST (as `ListRecordsCompleteJudged` reads) and the sidecar LIST (as `ListSidecarRecordsStrict`, `sidecar.go:404`, reads), re-reading only changed ETags; an unreadable record or sidecar makes it incomplete. |
| +- `func (s *Server) loadFleetView(ctx context.Context, fleet string) (fleetView, error)`: the fleet's heartbeats, the deployment listing for (c), and the inventory for `Load` and `HasSidecars`. Anything incomplete leaves `Active` false. |
| - `func (v fleetView) labelActive() bool`: the Global Constraints gate. |
| - `func (v fleetView) chooseDestination(rootfs bool, exclude string) string`: among boxes that are fresh, not draining, at the label floor (and rootfs-ready at the rootfs floor for a rootfs record), the lowest load, ties by label; "" when none. Independent of whether other boxes are fresh. |
| - `func (s *Server) lockFleet(fleet string) (unlock func())`: one mutex per fleet, held from `loadFleetView` through the record create. |
| - Store `AppsPlacedOn(ctx context.Context, placement string) ([]AppRef, error)`. |
| - Copy: `msgSidecarNeedsSingleBoxFleet(fleet string) string`. |
| |
| -- [ ] **Step 1: Write the failing tests.** `TestCreateOnASingleBoxFleetLeavesNoLabel`; `TestCreateLabelsTheLeastLoadedReadyBox`; `TestCreateSkipsStaleDrainingAndDetachedBoxes`; `TestGateNeedsEveryDeploymentBoxCurrent` (a platform box below the floor: no label); `TestGateClosedForAFleetWithSidecars`; `TestGateClosedOnAnIncompleteListing`; `TestConcurrentCreatesSpreadAcrossBoxes`; `TestSidecarCreateRefusedOnAMultiBoxFleet` (and allowed on a single-box fleet); `TestRootfsAdmissionFollowsTheChosenBox`; `TestCreateOnALabelledFleetCostsOneInventory` (store-call counter: one LIST per placed app, zero record PUTs beyond the create). Existing `rootfs_test.go` and `TestAPIInstanceCreateInheritsFleetPlacement` still pass. |
| +- [ ] **Step 1: Write the failing tests.** `TestCreateOnASingleBoxFleetLeavesNoLabel`; `TestCreateLabelsTheLeastLoadedReadyBox`; `TestCreateSkipsStaleDrainingAndDetachedBoxes`; `TestGateNeedsEveryDeploymentBoxCurrent` (a platform box below the floor: no label); `TestGateClosedForAFleetWithSidecars`; `TestGateClosedOnAnIncompleteListing` (through `loadDeploymentBoxesComplete`: a skipped below-floor heartbeat and a capped listing both close the gate); `TestSidecarOnlyAppClosesTheGate`; `TestInventoryRereadsOnlyChangedRecords` (store-call counter: an unchanged second load does zero record GETs); `TestConcurrentCreatesSpreadAcrossBoxes`; `TestSidecarCreateRefusedOnAMultiBoxFleet` (and allowed on a single-box fleet); `TestRootfsAdmissionFollowsTheChosenBox`; `TestCreateOnALabelledFleetCostsOneInventory` (store-call counter: one LIST per placed app, zero record PUTs beyond the create). Existing `rootfs_test.go` and `TestAPIInstanceCreateInheritsFleetPlacement` still pass. |
| - [ ] **Step 2: Run them to see them fail.** `go test ./internal/console/ -run 'FleetBox|LeastLoaded|SkipsStale|Gate|ConcurrentCreatesSpread|SidecarCreateRefused|RootfsAdmissionFollows|CostsOneInventory'` → FAIL. |
| - [ ] **Step 3: Implement.** Freshness and readiness reuse `status.BoxStale`, `boxRootfsReady`, `boxAtRootfsFloor` and the join at `rootfs.go:212-238`. The create door stamps the label only when `labelActive()`; a rootfs create on an active fleet with no rootfs-ready destination is refused with today's rootfs refusal. |
| - [ ] **Step 4: Run them to see them pass,** plus `-run 'Rootfs|FleetPlacement|Sidecar'` → PASS. |
| @@ -74,23 +77,26 @@ |
| |
| **Files:** modify `internal/provision/reconcile.go` (`ReconcileConfig`; `inScope` callers :1253, :2182, :2263), `internal/provision/seedreconcile.go:177`, `internal/registry` (Route `Assigned`, column `fleet_assigned`, migration), `internal/host/agent.go:3504` (`provisionTickConfig`); tests in `internal/provision/reconcile_test.go`, `reconcile_lifetime_test.go`, `internal/registry`, `internal/host/host_test.go`. |
| |
| -**Interfaces (produces):** `ReconcileConfig.FleetBox string` (from `resolveFleetIdentity`); `func (cfg ReconcileConfig) ownsRecord(rec Record) bool` (true off a fleet, for an unlabelled record, or when the label is `cfg.FleetBox`); `registry.Route.Assigned string`, minted from `rec.FleetBoxAt` on the box's own row and rewritten when it changes. |
| +**Interfaces (produces):** `ReconcileConfig.FleetBox string` (from `resolveFleetIdentity`); `func (cfg ReconcileConfig) ownsRecord(rec Record) bool` (true off a fleet, for an unlabelled record, or when the label is `cfg.FleetBox`); `registry.Route.Assigned string` and `registry.Route.Moved bool` (columns `fleet_assigned`, `fleet_moved`), minted from `rec.FleetBoxAt` and `rec.FleetBoxMoved` on the box's own row and rewritten when they change. |
| |
| - [ ] **Step 1: Write the failing tests.** `TestFleetBoxMintsOnlyItsOwnRecords`; `TestRelabelledRowIsRemovedNotKept` (lifetimes on and off; copy `TestOutOfScopeValidRecordFollowsTodaysRemoval`); `TestRelabelledSeedIsNotAdopted`; `TestMintedRowCarriesTheAssignment`; `TestProvisionTickConfigCarriesTheFleetBox`. |
| - [ ] **Step 2: Run them to see them fail.** `go test ./internal/provision/ ./internal/registry/ ./internal/host/ -run 'FleetBoxMints|RelabelledRow|RelabelledSeed|MintedRowCarries|ProvisionTickConfigCarries'` → FAIL. |
| -- [ ] **Step 3: Implement.** `ownsRecord` is checked at every place `inScope` admits a record or keeps a row on a fleet box. A removed row retires its instance through `RetireExcept`; workers are stopped by `StopRetired`'s worker path (`activator.go:5642-5657`): add `TestRetiredRowStopsItsWorkers` if no existing test covers a rootfs entry with workers. |
| +- [ ] **Step 3: Implement.** `ownsRecord` is checked at every place `inScope` admits a record or keeps a row on a fleet box. A removed row retires its instance through `RetireExcept`; a rootfs entry's workers are stopped by the rootfs worker shutdown at `activator.go:4388` (`:5642` is the standalone-worker exclusion, not this path): add `TestRetiredRowStopsItsWorkers` if no existing test covers a retired rootfs entry with workers. |
| - [ ] **Step 4: Run them to see them pass,** plus `-run 'Reconcile|Seed|Retire'` → PASS. |
| - [ ] **Step 5: Commit.** |
| |
| -### Task 4: Set a stale copy aside, restore, or refuse (rule 6, #470) |
| +### Task 4: The start rule (rule 6, #470) |
| |
| -**Files:** modify `internal/activator/backend_exec.go` (`restorePlain`, beside `reconcileSeedMarker` at :879); test `internal/activator/activator_test.go` beside `TestExecBackendRestoreWarmCacheIsNotFresh` (:5774). |
| +**Files:** modify `internal/activator/backend_exec.go` (`restorePlain` :864, beside `reconcileSeedMarker` at :879, and the fresh-boot branch ~:962); create `internal/activator/startrule.go`; tests `internal/activator/startrule_test.go`, beside `TestExecBackendRestoreWarmCacheIsNotFresh` (:5774). |
| |
| -**Interfaces (produces):** `func (b *ExecBackend) reconcileAssignment(rt registry.Route, dbPath string) (setAside string, err error)`; marker `dbPath + ".assigned"` holding `rt.Assigned`, written atomically (temp file and rename); set-aside directory `<data dir>/.superseded/<host>/<unix nanos>/` holding the database and its litestream sidecar state (the files `reconcileSeedMarker` would remove); `var ErrNothingToRestore` whose message names the set-aside path. |
| +**Interfaces (produces):** |
| +- `func (b *ExecBackend) reconcileAssignment(rt registry.Route, dbPath string) error`: when `rt.Assigned` is set and the marker `dbPath + ".assigned"` is missing or differs, move the database and its litestream sidecar state (the files `reconcileSeedMarker` would remove) into `<data dir>/.superseded/<host>/<unix nanos>.partial/`, then rename that directory to drop `.partial`. An interrupted move leaves a `.partial` directory, which counts as set aside. |
| +- `func (b *ExecBackend) startAllowed(rt registry.Route, haveLocal, restored bool) error`: the one rule. Returns nil for a kept copy under the current marker or a successful restore; for neither, nil only when `!rt.Moved` and no `.superseded/<host>/` entry exists; otherwise `ErrNothingToRestore`, whose message names the set-aside path (or says the instance has moved and no replica was found). Every start path on a fleet box that would boot without a restored or kept copy calls it. |
| +- The marker is written atomically (temp file and rename) only after `startAllowed` returned nil and the start succeeded. |
| |
| -- [ ] **Step 1: Write the failing tests.** `TestAssignmentChangeSetsTheCopyAside` (marker `T1`, route `T2`: the files move to `.superseded`, nothing is deleted, the restore runs, the marker reads `T2`); `TestSameAssignmentKeepsTheWarmCopy`; `TestUnassignedRouteIgnoresTheMarker`; `TestMissingMarkerSetsAside`; `TestNothingToRestoreRefuses` (a copy set aside and no replica: the wake fails with `ErrNothingToRestore`, no fresh boot); `TestNewInstanceBootsFresh` (assigned route, no local copy, nothing set aside, no replica: fresh boot, marker written); `TestFailedRestoreLeavesNoMarker` (the next wake tries again; the set-aside copy is still there); `TestUnreplicatedTailSurvives` (bytes written after the last replication are present in the set-aside copy). |
| -- [ ] **Step 2: Run them to see them fail.** `TMPDIR=/tmp/k go test ./internal/activator/ -run 'AssignmentChange|SameAssignment|UnassignedRoute|MissingMarker|NothingToRestore|NewInstanceBootsFresh|FailedRestoreLeaves|UnreplicatedTail'` → FAIL. |
| -- [ ] **Step 3: Implement.** Called before the warm-cache check. HA routes keep `restoreHA`, unchanged. The marker is written only after a successful restore, a kept matching copy, or a fresh boot of a new instance. |
| +- [ ] **Step 1: Write the failing tests** (fault injection where named). `TestAssignmentChangeSetsTheCopyAside` (files moved, nothing deleted, restore runs, marker updated); `TestSameAssignmentKeepsTheWarmCopy`; `TestUnassignedRouteIgnoresTheRule` (today's behaviour); `TestMissingMarkerSetsAside`; `TestNothingToRestoreRefusesEveryTime` (set aside, no replica: the first wake, a second wake, and a wake through a fresh `ExecBackend` over the same data dir (agent restart) all refuse; no fresh boot); `TestInterruptedSetAsideRefuses` (a `.partial` directory left by a crash: refused); `TestMovedInstanceOnACleanBoxRefusesWithoutReplica`; `TestNewInstanceBootsFresh` (never moved, nothing set aside, no replica: fresh boot, marker written); `TestFailedRestoreLeavesNoMarker`; `TestUnreplicatedTailSurvives`; `TestEveryFreshBootPathConsultsTheRule` (a guard test over the fresh-boot call sites: each one on a fleet box goes through `startAllowed`). |
| +- [ ] **Step 2: Run them to see them fail.** `R=$(mktemp -d /tmp/k.XXXX) && TMPDIR=$R go test ./internal/activator/ -run 'AssignmentChange|SameAssignment|UnassignedRoute|MissingMarker|NothingToRestore|InterruptedSetAside|MovedInstance|NewInstanceBootsFresh|FailedRestoreLeaves|UnreplicatedTail|EveryFreshBootPath'; rm -r $R` → FAIL. |
| +- [ ] **Step 3: Implement.** HA routes keep `restoreHA`, unchanged. |
| - [ ] **Step 4: Run them to see them pass,** plus `-run 'Assignment|Marker|WarmCache|Seed|Restore'` → PASS. |
| - [ ] **Step 5: Commit.** |
| |
| @@ -108,13 +114,13 @@ |
| |
| ### Task 6: The relabel worker, two-step drain, pause and alert (rules 2, 4, 5, 8) |
| |
| -**Files:** create `internal/console/fleetrelabel.go`; modify `internal/console/claim_workers.go`, `cmd/console/main.go`, `internal/console/testdata/claim-routes.txt`, `internal/console/fleets.go` (new drain door; detach doors :544, :1455), `internal/registry/fleets.go` (`draining` column on `fleet_boxes`; `FleetChannelAuth` still admits a draining active box), `fleets.go` at the repo root (the CLI: `carlos fleets drain`, `LABELS PAUSED` in `fleets ls`); tests `internal/console/fleetrelabel_test.go`, `cmd/console/claimworkers_started_test.go`, `internal/registry` fleet tests, `cli_test.go` patterns for the CLI. |
| +**Files:** create `internal/console/fleetrelabel.go`; modify `internal/console/claim_workers.go`, `cmd/console/main.go`, `internal/console/testdata/claim-routes.txt`, `internal/console/fleets.go` (new drain door; detach doors :544, :1455), `internal/registry/fleets.go` (`draining` column on `fleet_boxes`; `FleetChannelAuth` still admits a draining active box), `fleets.go` at the repo root (the CLI: `carlos fleets drain`, `LABELS PAUSED` in `fleets ls`); tests `internal/console/fleetrelabel_test.go`, `cmd/console/claimworkers_started_test.go`, `internal/registry` fleet tests, `cli_test.go` patterns for the CLI; docs `docs/site/cli.md` (document `fleets drain`, drain refusal and completion, detach after a drain, `LABELS PAUSED`, and revise the existing detach-first advice at :2168 for a leaked key: detach still works at once for a box that holds nothing; otherwise rotate its token first, then drain). |
| |
| -**Interfaces (produces):** worker `FleetRelabel` every 5 minutes, started like `StartRunSweep`; `func (s *Server) fleetRelabelPass(ctx context.Context) error`; `func (s *Server) relabelFleet(ctx context.Context, fleet string, v fleetView) (moved int, err error)`; `func (s *Server) drainBox(ctx context.Context, fleet, label string) (stuck []string, err error)`; `func (s *Server) boxEmpty(ctx context.Context, fleet, label string) (bool, error)` (its heartbeat reports no instance of the fleet and no record names it); `const fleetBoxLostAfter = lease.LeaseTTL + 5*time.Minute`; copy `msgDrainStrandsApps(fleet, label string, apps []string) string`, `msgDetachNotDrained(fleet, label string) string`. |
| +**Interfaces (produces):** worker `FleetRelabel` every 5 minutes, started like `StartRunSweep`; `func (s *Server) fleetRelabelPass(ctx context.Context) error`; `func (s *Server) relabelFleet(ctx context.Context, fleet string, v fleetView) (moved int, err error)`; `func (s *Server) drainBox(ctx context.Context, fleet, label string) (stuck []string, err error)`; `func drainDone(hb status.Box, drainingSince time.Time) bool` (the drain rule: `hb` composed after `drainingSince`, no routes for the fleet, `LeasesHeld == 0`), the only check both detach doors make for a draining box; a box that is lost (silent past `fleetBoxLostAfter`) may be detached without it once no record names it, since its access is moot; `status.Box.LeasesHeld int` (`json:"leases_held"`), filled by the box from the activator's held leases when it composes the heartbeat; `fleet_boxes.draining_since` (timestamp; null when not draining); `const fleetBoxLostAfter = lease.LeaseTTL + 5*time.Minute`; copy `msgDrainStrandsApps(fleet, label string, apps []string) string`, `msgDetachNotDrained(fleet, label string) string`. |
| |
| Per fleet, per pass: if a labelled fleet has a box below the floor, log the alert and skip it (paused). Else if `labelActive()`: label each unlabelled record to the box its binding names (`fleets/<f>/bindings/<host>.json`) when that box is a valid destination, otherwise `chooseDestination`; move each record whose box is lost to `chooseDestination(rootfs, lost)`; move each record of a draining box likewise. All writes use `SetRecordFleetBox` with the expectation read in this pass; `ErrFleetBoxMoved` is skipped until the next pass. Truncated or skipped records make the pass write nothing for that fleet. |
| |
| -- [ ] **Step 1: Write the failing tests.** `TestFirstLabellingFollowsBindings` (three running records, bindings on `pi-1`, `pi-1`, `pi-2`: labelled the same; nothing moves); `TestRelabelPassLeavesAnUngatedFleetAlone`; `TestLostBoxMovesToTheSurvivor` (two-box fleet, `pi-1` silent 21 minutes: all its records to `pi-2`; 19 minutes: nothing); `TestRelabelLosesToAPlacementChange`; `TestBelowFloorBoxPausesAndAlerts`; `TestDrainMovesEverythingOrNothing` (one record with no destination: refused naming the app, nothing written); `TestDrainingBoxKeepsFleetAccess` (`FleetChannelAuth` still lists it); `TestDetachRefusedUntilDrainedAndEmpty`; `TestIdlePassCostsTheBudget` (store-call counter for an idle labelled fleet: per the Global Constraints); `TestEveryRegisteredClaimWorkerIsStarted` with `FleetRelabel`; CLI tests for `carlos fleets drain` and the `LABELS PAUSED` column. |
| +- [ ] **Step 1: Write the failing tests.** `TestFirstLabellingFollowsBindings` (three running records, bindings on `pi-1`, `pi-1`, `pi-2`: labelled the same; nothing moves); `TestRelabelPassLeavesAnUngatedFleetAlone`; `TestLostBoxMovesToTheSurvivor` (two-box fleet, `pi-1` silent 21 minutes: all its records to `pi-2`; 19 minutes: nothing); `TestRelabelLosesToAPlacementChange`; `TestBelowFloorBoxPausesAndAlerts`; `TestDrainMovesEverythingOrNothing` (one record with no destination: refused naming the app, nothing written); `TestDrainingBoxKeepsFleetAccess` (`FleetChannelAuth` still lists it); `TestDrainDoneNeedsAPostDrainHeartbeat` (an empty heartbeat composed before `draining_since`: not done); `TestDrainDoneNeedsNoLeases` (no routes but one lease held: not done); `TestBothDetachDoorsUseDrainDone` (API and page); `TestHeartbeatCountsHeldLeases` (in `internal/host` or `internal/status`: a box holding two leases reports 2, after release 0); `TestIdlePassCostsTheBudget` (store-call counter for an idle labelled fleet: per the Global Constraints); `TestEveryRegisteredClaimWorkerIsStarted` with `FleetRelabel`; CLI tests for `carlos fleets drain` and the `LABELS PAUSED` column. |
| - [ ] **Step 2: Run them to see them fail.** `go test ./internal/console/ ./internal/registry/ ./cmd/console/ . -run 'FirstLabelling|RelabelPass|LostBox|RelabelLoses|BelowFloor|Drain|Detach|IdlePass|ClaimWorker|FleetsDrain|LabelsPaused'` → FAIL. |
| - [ ] **Step 3: Implement.** Log one line per moved record (host, from, to, reason). |
| - [ ] **Step 4: Run them to see them pass.** Same command → PASS. |
| @@ -124,10 +130,10 @@ Per fleet, per pass: if a labelled fleet has a box below the floor, log the aler |
| |
| **Files:** create `internal/host/fleettwobox_e2e_test.go` with its own fixture (borrowing from `newE2EWorld`, `internal/host/movesoffline_e2e_test.go:215`), plus the smallest production seams it needs. |
| |
| -**Fixture requirements:** one fake S3 (`leasetest.NewS3Server`) holding one shared fleet data bucket; two real `ExecBackend`s with their own data directories and their own lease identities (`pi-1`, `pi-2`). The lease's owner is process-global today (`internal/lease/self.go`), so add an injectable identity used when set, defaulting to `lease.CurrentSelf()` in production, and a test that production wiring still uses the default. A short lease TTL set by the fixture (seconds, not 15 minutes) for deterministic expiry. The console's `fleetRelabelPass` called directly with an injected clock. A "partitioned" box: its lease keeps renewing while its record reads fail. |
| +**Fixture requirements:** one fake S3 (`leasetest.NewS3Server`) holding one shared fleet data bucket; two real `ExecBackend`s with their own data directories and their own lease identities (`pi-1`, `pi-2`). The lease's owner is process-global today (`internal/lease/self.go`), so add an injectable identity used when set, defaulting to `lease.CurrentSelf()` in production, and a test that production wiring still uses the default. A short lease TTL set by the fixture (seconds, not 15 minutes) for deterministic expiry. The console pass is reached through an exported method `func (s *Server) RunFleetRelabelPass(ctx context.Context, now time.Time) error` (the worker calls it with `time.Now()`). A "partitioned" box: its lease keeps renewing while its record reads fail. |
| |
| -- [ ] **Step 1: Write the test** `TestTwoBoxFleetEndToEnd_Real`: (1) two instances land one per box, with forward rows naming them; (2) each box mints only its own and each lock names its box; (3) `a` on `pi-1` writes `1`; `pi-1` is partitioned: the relabel moves `a` to `pi-2`, which waits while `pi-1` renews; heal the partition: `pi-1` reads the relabel, drops the row, releases; `pi-2` restores, reads `1`, writes `2`; (4) drain `pi-2`: `a` moves to `pi-1`, which sets its old copy aside, restores and reads `2`; (5) a first-labelling run over a fleet started unlabelled moves nothing and loses nothing. |
| -- [ ] **Step 2: Run it.** `TMPDIR=/tmp/k go test ./internal/host/ -run TestTwoBoxFleetEndToEnd_Real -v` → PASS. A failure is fixed in the code, not the test. |
| +- [ ] **Step 1: Write the test** `TestTwoBoxFleetEndToEnd_Real`: (1) two instances land one per box, with forward rows naming them; (2) each box mints only its own and each lock names its box; (3) `a` on `pi-1` writes `1`; `pi-1` is partitioned: the relabel moves `a` to `pi-2`, which waits while `pi-1` renews; heal the partition: `pi-1` reads the relabel, drops the row, releases; `pi-2` restores, reads `1`, writes `2`; (4) drain `pi-2`: `a` moves to `pi-1`, which sets its old copy aside, restores and reads `2`; (5) a first-labelling run over a fleet started unlabelled moves nothing and loses nothing; (6) stopped renewal: `pi-1`'s agent is stopped without releasing, its records move, and `pi-2` takes the lease after it expires (short TTL), restores and serves. |
| +- [ ] **Step 2: Run it.** `R=$(mktemp -d /tmp/k.XXXX) && TMPDIR=$R go test ./internal/host/ -run TestTwoBoxFleetEndToEnd_Real -v; rm -r $R` → PASS. A failure is fixed in the code, not the test. |
| - [ ] **Step 3: Commit.** |
| |
| ### Task 8: Census, copy, review, merge |
| @@ -163,3 +169,17 @@ Live action, needs Paul's go with the scoped plan: account dev (kass), eu-west-1 |
| | 9 | P2 | Task 7 harness needs extensions | Accepted: shared bucket, per-box lease identity seam, short TTL, injected clock, partition (Task 7). Declined: disk-backed test roots for activator/host e2e; they need `/tmp/k` for the Unix socket path limit (memory "Gate tmp exec wrapper"). | |
| | 10 | P2 | Request budgets and counting tests | Accepted: budgets in Global Constraints; counting tests in Tasks 2 and 6; one inventory per pass; incomplete listings write nothing. | |
| | 11 | P2 | Census name table and selected inventory | Accepted: Task 1 Step 4; Task 8 Step 1 adds the new columns. | |
| + |
| +## Round 2 dispositions (`CODEX-FINDINGS-MANAGED-FLEETS-1B-PLAN-R2.md`) |
| + |
| +Stopping rule 2 triggered on two families (restore, drain completion). Paul chose: one rule each, enforced in one place, with fault-injection tests. |
| + |
| +| # | Sev | Finding | Disposition | |
| +|---|---|---|---| |
| +| 1 | P1 | A second wake boots empty after a refusal | Accepted: the start rule (`startAllowed`, Task 4) decides from the record's `FleetBoxMoved` flag and the presence of any set-aside copy, so refusal persists across wakes and restarts; `.partial` counts as set aside; a moved instance on a clean box refuses without a replica; guard test over every fresh-boot path. | |
| +| 2 | P1 | Empty heartbeat does not prove drain completion | Accepted: the drain rule (`drainDone`, Task 6): a heartbeat composed after `draining_since` with no fleet routes and `LeasesHeld == 0`; leases are released only after the stop is proven and the final replication ran. Both detach doors use it. | |
| +| 3 | P2 | System-status listing drops completeness | Accepted: `loadDeploymentBoxesComplete` (Task 2) with tests through it. | |
| +| 4 | P2 | Inventory cannot see sidecars; wrong worker line | Accepted: sidecar LIST in `fleetInventoryFor`; sidecar-only app test; worker reference corrected to `activator.go:4388`. | |
| +| 5 | P2 | Idle budget contradicts the readers | Accepted: the inventory cache re-reads only changed ETags; budget restated; cold and unchanged passes tested separately. | |
| +| 6 | P2 | Fixture seam, expiry case, scratch path | Accepted: exported `RunFleetRelabelPass`; stopped-renewal expiry case; owned short temp roots (`mktemp -d /tmp/k.XXXX`, removed), since socket paths rule out the longer `$TMPDIR`. | |
| +| 7 | P2 | CLI docs | Accepted: `docs/site/cli.md` in Task 6, including the revised leaked-key advice. | |