carlos / platform Public

fix: preserve managed cleanup evidence and repair branch gates

Require exact-cloud-ID absence evidence after a termination attempt, clear
resolved publication uncertainty, and preserve never-launched reservations
when no compute provider is configured.

Add the missing claim inventories and strict configuration classification.
Restore BYO fleet ownership updates while retaining managed-fleet guards.
Record fix round 1 and the updated census proposal for controller review.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev 3a52d27f808751fa3e53b3564532f73fe9fc2faa parent afbc94c
21 files changed, +378 −32
  • docs/superpowers/notes/census-proposal-managed-fleets-2a-task-6-fix1.md +31 −0
  • internal/compute/fake.go +23 −0
  • internal/compute/fake_test.go +28 −0
  • internal/compute/provisioner.go +3 −0
  • internal/console/claim_authority_census_test.go +5 −0
  • internal/console/claim_invariant_fixtures_test.go +3 −0
  • internal/console/claim_invariant_probes_nonapp_test.go +15 −0
  • internal/console/claim_invariant_probes_read_test.go +4 −2
  • internal/console/managedconfig.go +4 −14
  • internal/console/managedstore.go +2 −1
  • internal/console/managedworker.go +46 −12
  • internal/console/managedworker_test.go +102 −2
  • internal/console/testdata/claim-authority-sites.txt +1 −0
  • internal/console/testdata/claim-routes.txt +4 −0
  • internal/hostops/storage_classifier.go +13 −0
  • internal/hostops/storage_classifier_test.go +24 −0
  • internal/provision/testdata/plan14-root-reads-chain.tsv +1 −0
  • internal/provision/testdata/plan14-root-reads-managed-fleets-2a-task-6-fix1.tsv +7 −0
  • internal/registry/fleets.go +1 −1
  • internal/registry/fleets_test.go +42 −0
  • internal/release/managedfleets.go +19 −0
diff --git a/docs/superpowers/notes/census-proposal-managed-fleets-2a-task-6-fix1.md b/docs/superpowers/notes/census-proposal-managed-fleets-2a-task-6-fix1.md
new file mode 100644
index 000000000..bc235dd3f
--- /dev/null
+++ b/docs/superpowers/notes/census-proposal-managed-fleets-2a-task-6-fix1.md
@@ -0,0 +1,31 @@
+# Census approval: managed-fleets-2a-task-6-fix1
+
+Ruling `census-ruling-managed-fleets-2a-task-6-fix1`. 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).
+
+| unit | change | read sites | what changed |
+|---|---|---|---|
+| `internal/registry/fleets.go` `Registry.UpsertFleet` | body | unchanged (17) | Restore pre-branch account and bucket updates for BYO-to-BYO conflicts only; both existing and incoming managed flags must remain false. Managed ownership and bucket remain protected. Witness TestManagedUpsertPreservesBYOOwnerUpdates local/remote and eight edge regression tests. |
+
+Envelopes re-pinned: `internal/hostops`, `internal/registry`, `internal/release`.
+
+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.
+
+Recorded dispositions, which each change must still satisfy:
+
+- `internal/registry/fleets.go` `Registry.UpsertFleet`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=J1,J4;basis=route-and-input;rev3=census-ruling-managed-fleets-2a-task-4;basis=Persist Managed on insertion; conflict updates require same account and BYO on both sides, preserving ownership and Managed; managed fleet bucket changes refused.
+
+Seal: `d63dcbb0494381ce43314094fecfd1780abc890af3774c145eb9ec9b1d54afde` → `6f7852cb59ad8e795883178b98353b385b6ccfc430f28dada330d019d5e5061d`.
+
+Overlay: `internal/provision/testdata/plan14-root-reads-managed-fleets-2a-task-6-fix1.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`.
+
+## Fix round 1 context
+
+This proposal covers Task 6 fix round 1, following the controller's independent review. The plan's rounds 1–3 remain closed. No new independent review or #280 posting was performed here. Minors remain deferred.
+
+Registry.UpsertFleet restores pre-branch account and bucket updates for BYO-to-BYO conflicts. Existing managed fleets remain immutable through this method, and an incoming managed flag cannot convert a BYO fleet. The earlier same-account restriction broke all eight named edge reload/tenancy tests locally. TestManagedUpsertPreservesBYOOwnerUpdates checks local/remote behavior and the revision bump; the eight edge tests pass after this restoration.
+
+The hostops classifier now admits only PUT of the exact system/managed-fleets.json key, strictly decoded into the shared release.ManagedFleetsConfig wire type. Unknown top-level or nested fields, lookalike keys and deletion remain refused. The console still validates admission values and requires a user who is a system operator. The shared schema adds no runtime provider or app record. TestManagedConfigClassification and the claim mutation probe cover this authority change.
+
+Console cleanup uses the new provider Lookup method for exact-cloud-ID evidence after a persisted attempt. An empty identity search is never absence proof. The fake can change tags while retaining the physical instance; TestManagedIdentityCleanup verifies hourly cleanup, held quota and a retained registry row after that change. Publication uncertainty is cleared only when verification resolves to ready or proven absence. Missing compute providers leave reserved rows untouched until their never-launched deadline. These console changes are outside root-binary scope but still need the controller's authority review.
+
+Claim census additions: GET /api/cli/fleets/{account}/{fleet} and GET /api/cli/system/managed-fleets are reads; PUT /api/cli/system/managed-fleets is deployment configuration with an observed effect; worker ManagedFleets is added to the route inventory (its refusal fixture/probe already existed). The authority source inventory adds managedhistory.go|managedCredentialsHeld|seal.Open(sealed): fleet/account-selected sealed credentials, under the fleet lock, reused for preparation/enrolment, never UserData or app records.
diff --git a/internal/compute/fake.go b/internal/compute/fake.go
index 370315799..62aac9b74 100644
--- a/internal/compute/fake.go
+++ b/internal/compute/fake.go
@@ -4,6 +4,7 @@ import (
"context"
"errors"
"fmt"
+ "os"
"reflect"
"slices"
"sort"
@@ -139,3 +140,25 @@ func (f *Fake) match(accept func(Instance) bool) []Instance {
sort.Slice(out, func(i, j int) bool { return out[i].CloudID < out[j].CloudID })
return out
}
+
+func (f *Fake) Lookup(ctx context.Context, region, cloudID string) (Instance, error) {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ f.calls["Lookup"]++
+ if err := ctx.Err(); err != nil {
+ return Instance{}, err
+ }
+ a, ok := f.instances[cloudID]
+ if !ok || a.Region != region {
+ return Instance{}, os.ErrNotExist
+ }
+ return a, nil
+}
+func (f *Fake) SetIdentity(cloudID string, id Identity) {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ if a, ok := f.instances[cloudID]; ok {
+ a.Identity = id
+ f.instances[cloudID] = a
+ }
+}
diff --git a/internal/compute/fake_test.go b/internal/compute/fake_test.go
index 4eb02fbb9..8b2098210 100644
--- a/internal/compute/fake_test.go
+++ b/internal/compute/fake_test.go
@@ -3,6 +3,7 @@ package compute
import (
"context"
"errors"
+ "os"
"sync"
"testing"
)
@@ -154,3 +155,30 @@ func TestFakeConcurrentCalls(t *testing.T) {
t.Fatal("aliased counters")
}
}
+
+func TestFakeLookupIgnoresIdentityTags(t *testing.T) {
+ f := NewFake()
+ ctx := context.Background()
+ want := Identity{Deployment: "deployment", Fleet: "production", Label: "box-1", Operation: "operation"}
+ a, err := f.Launch(ctx, LaunchSpec{Identity: want, Region: "region", ClientToken: "token"})
+ if err != nil {
+ t.Fatal(err)
+ }
+ f.SetIdentity(a.CloudID, Identity{Deployment: "foreign"})
+ matches, err := f.Find(ctx, a.Region, want)
+ if err != nil || len(matches) != 0 {
+ t.Fatal("identity lookup was not empty", err)
+ }
+ got, err := f.Lookup(ctx, a.Region, a.CloudID)
+ if err != nil || got.CloudID != a.CloudID || got.Identity == want {
+ t.Fatal("exact lookup lost instance", got, err)
+ }
+ if _, err = f.Lookup(ctx, a.Region, "missing"); !errors.Is(err, os.ErrNotExist) {
+ t.Fatal("missing exact ID was not definitive", err)
+ }
+ canceled, cancel := context.WithCancel(ctx)
+ cancel()
+ if _, err = f.Lookup(canceled, a.Region, a.CloudID); !errors.Is(err, context.Canceled) {
+ t.Fatal("lookup ignored cancellation", err)
+ }
+}
diff --git a/internal/compute/provisioner.go b/internal/compute/provisioner.go
index 15d2c1784..2ca735fba 100644
--- a/internal/compute/provisioner.go
+++ b/internal/compute/provisioner.go
@@ -41,6 +41,9 @@ type Instance struct {
type Provisioner interface {
Launch(ctx context.Context, s LaunchSpec) (Instance, error)
Find(ctx context.Context, region string, id Identity) ([]Instance, error)
+ // Lookup addresses the exact cloud ID, without filtering by identity tags.
+ // Only definitive absence of that ID in the region returns os.ErrNotExist.
+ Lookup(ctx context.Context, region, cloudID string) (Instance, error)
Terminate(ctx context.Context, region, cloudID string, want Identity) error
ListDeployment(ctx context.Context, region, deployment string) ([]Instance, error)
ConsoleOutput(ctx context.Context, region, cloudID string) (string, error)
diff --git a/internal/console/claim_authority_census_test.go b/internal/console/claim_authority_census_test.go
index c6e8b1049..1963bcaf7 100644
--- a/internal/console/claim_authority_census_test.go
+++ b/internal/console/claim_authority_census_test.go
@@ -15,6 +15,11 @@ import (
// The reviewed inventory is committed. The test never regenerates it: new
// constructors or typed control callers need a matching coverage change.
+// managedCredentialsHeld opens only the sealed credential selected by fleet
+// and account from managed_fleet_storage while the caller holds lockFleet.
+// The plaintext is reused for that fleet's preparation/enrolment; it never
+// reaches UserData or an app-scoped record. Covered by TestManagedFleetCredentials
+// and TestManagedFleetCredentialsLostSealWrite.
func claimAuthoritySites(t *testing.T) []string {
t.Helper()
selected := map[string]bool{
diff --git a/internal/console/claim_invariant_fixtures_test.go b/internal/console/claim_invariant_fixtures_test.go
index a886a1a20..6f2b6124c 100644
--- a/internal/console/claim_invariant_fixtures_test.go
+++ b/internal/console/claim_invariant_fixtures_test.go
@@ -889,6 +889,9 @@ var claimFixtures = map[string]claimFixture{
"route GET /api/cli/store/approvals": claimRead("operator entitlement queue"),
"route GET /api/cli/accounts/{account}/plan": claimRead("operator view of an account's plan and limits"),
"route GET /api/cli/billing/problems": claimRead("operator view of billing problems; names no app"),
+ "route GET /api/cli/fleets/{account}/{fleet}": claimRead("reads the owned fleet and its boxes; writes nothing"),
+ "route GET /api/cli/system/managed-fleets": claimRead("reads operator managed fleet configuration; writes nothing"),
+ "route PUT /api/cli/system/managed-fleets": claimNonApp("operator configuration at system/managed-fleets.json; no app record write"),
"route GET /api/cli/system/antivirus": claimRead("reads the deployment scanning setting"),
"route GET /api/cli/system/geoip": claimRead("operator view of the GeoIP pointer, box heartbeats and feed status (control/geoip/, status/, edge files); writes nothing"),
"route GET /api/cli/system/hosts-used/status": claimRead("operator view of the hostname history: its mode, a count of control/hosts-used/ marks, closed fleets and the floor; writes nothing"),
diff --git a/internal/console/claim_invariant_probes_nonapp_test.go b/internal/console/claim_invariant_probes_nonapp_test.go
index cb5893d76..d0bc8ec63 100644
--- a/internal/console/claim_invariant_probes_nonapp_test.go
+++ b/internal/console/claim_invariant_probes_nonapp_test.go
@@ -1090,6 +1090,21 @@ var claimNonAppProbes = map[string]claimProbe{
},
// ---- the platform system doors ----
+ "route PUT /api/cli/system/managed-fleets": {
+ do: claimAPIReply(http.MethodPut, "/api/cli/system/managed-fleets", `{"enabled":false,"ceiling":3}`),
+ body: []string{`"ceiling":3`},
+ effect: func(t *testing.T, cx *claimCase, r claimReply) string {
+ raw, _, err := cx.rel.Get(context.Background(), managedConfigKey)
+ if err != nil {
+ return "configuration missing"
+ }
+ c, err := decodeManagedConfig(raw)
+ if err != nil || c.Ceiling != 3 || c.Enabled {
+ return "configuration differs"
+ }
+ return ""
+ },
+ },
"route POST /api/cli/system/antivirus": {
do: claimAPIReply(http.MethodPost, "/api/cli/system/antivirus", `{"enabled":true}`),
body: []string{`"enabled":true`},
diff --git a/internal/console/claim_invariant_probes_read_test.go b/internal/console/claim_invariant_probes_read_test.go
index 4aa0b1459..532e5c150 100644
--- a/internal/console/claim_invariant_probes_read_test.go
+++ b/internal/console/claim_invariant_probes_read_test.go
@@ -342,8 +342,10 @@ var claimReadProbes = map[string]claimProbe{
"route GET /api/cli/store/approvals": claimAPIRead(claimWorldApply, "/api/cli/store/approvals", `"applications"`, claimFxOwner),
"route GET /api/cli/accounts/{account}/plan": claimAPIRead(func(t *testing.T, cx *claimCase) { cx.srv.cfg.PlanCatalog = examplePlanCatalog(t) },
"/api/cli/accounts/bab/plan", `"plan":"free"`),
- "route GET /api/cli/billing/problems": claimAPIRead(claimBillingProblemWorld, "/api/cli/billing/problems", `"reason":"unrecognised"`),
- "route GET /api/cli/system/antivirus": claimAPIRead(nil, "/api/cli/system/antivirus", `"wired":true`),
+ "route GET /api/cli/billing/problems": claimAPIRead(claimBillingProblemWorld, "/api/cli/billing/problems", `"reason":"unrecognised"`),
+ "route GET /api/cli/fleets/{account}/{fleet}": claimAPIRead(claimWorldFleet, "/api/cli/fleets/bab/pi", `"name":"pi"`),
+ "route GET /api/cli/system/managed-fleets": claimAPIRead(nil, "/api/cli/system/managed-fleets", `"enabled":false`),
+ "route GET /api/cli/system/antivirus": claimAPIRead(nil, "/api/cli/system/antivirus", `"wired":true`),
"route GET /api/cli/system/geoip": func() claimProbe {
p := claimAPIRead(claimWorldGeoip, "/api/cli/system/geoip", `"pointer"`, "GeoIP2-City")
p.serial = "claimWorldGeoip swaps the package variable geoipProbeAddrs (withFixtureProbes)"
diff --git a/internal/console/managedconfig.go b/internal/console/managedconfig.go
index 55c0b15e9..a0d3a04c2 100644
--- a/internal/console/managedconfig.go
+++ b/internal/console/managedconfig.go
@@ -16,21 +16,11 @@ import (
"github.com/carlosframework/platform/internal/release"
)
-const managedConfigKey = "system/managed-fleets.json"
+const managedConfigKey = release.ManagedFleetsConfigKey
+
+type managedConfig = release.ManagedFleetsConfig
+type managedRegion = release.ManagedFleetRegion
-type managedConfig struct {
- Enabled bool `json:"enabled"`
- Ceiling int `json:"ceiling"`
- AccountLimit int `json:"account_limit"`
- Regions map[string]managedRegion `json:"regions"`
-}
-type managedRegion struct {
- Image string `json:"image"`
- Subnets []string `json:"subnets"`
- SecurityGroups []string `json:"security_groups"`
- RootGB int `json:"root_gb"`
- Sizes map[string]string `json:"sizes"`
-}
type managedResolved struct {
Generation uint64
Region, Size string
diff --git a/internal/console/managedstore.go b/internal/console/managedstore.go
index 1aa6dd0db..8d6e380aa 100644
--- a/internal/console/managedstore.go
+++ b/internal/console/managedstore.go
@@ -381,7 +381,8 @@ func (s *Store) AdvanceManagedBox(ctx context.Context, before, after managedBox)
if (!after.TerminateAttemptedAt.IsZero() || !after.TerminateSentAt.IsZero()) && after.CloudID == "" {
return false, errors.New("managed termination requires cloud identity")
}
- if before.LastError != "" {
+ resolvedPublication := before.State == "publishing" && before.LastError == "uncertain" && (after.State == "ready" || after.State == "failed")
+ if before.LastError != "" && !resolvedPublication {
after.LastError = before.LastError
}
data, e := json.Marshal(after)
diff --git a/internal/console/managedworker.go b/internal/console/managedworker.go
index b83a43f08..740f7b901 100644
--- a/internal/console/managedworker.go
+++ b/internal/console/managedworker.go
@@ -284,7 +284,7 @@ func (s *Server) stepManagedBox(ctx context.Context, b managedBox, now time.Time
if !now.Before(b.CreatedAt.Add(30 * time.Minute)) {
return s.failManagedBoxHeld(ctx, b, "managed_preparation_timeout", now)
}
- if b.Storage.Bucket == "" || b.Storage.Region == "" {
+ if s.cfg.ManagedCompute == nil || b.Storage.Bucket == "" || b.Storage.Region == "" {
return nil
}
// Validate before recording an attempt: a changed key on a never-launched
@@ -491,20 +491,37 @@ func (s *Server) cleanupManagedBox(ctx context.Context, b managedBox, now time.T
return s.managedRetry(ctx, b, "managed_identity_multiple", now, true)
}
if len(found) == 0 {
+ reason := "managed_absence_unconfirmed"
+ if b.RecoveryReason == "managed_identity_mismatch" {
+ reason = b.RecoveryReason
+ }
if b.CloudID != "" && !b.TerminateAttemptedAt.IsZero() && b.TerminateAttemptCloudID == b.CloudID {
- next := b
- next.TerminationConfirmed = true
- if err = s.saveManagedBox(ctx, b, next, now); err != nil {
- return err
+ call, cancel := context.WithTimeout(ctx, managedCallTimeout)
+ exact, lookupErr := s.cfg.ManagedCompute.Lookup(call, b.Region, b.CloudID)
+ cancel()
+ absent := errors.Is(lookupErr, os.ErrNotExist)
+ if lookupErr != nil && !absent {
+ return s.managedRetry(ctx, b, "managed_find_failed", now, true)
+ }
+ if !absent && (!managedInstanceMatches(b, exact) || exact.CloudID != b.CloudID) {
+ return s.managedRetry(ctx, b, "managed_identity_mismatch", now, true)
}
- b, err = s.loadManagedBox(ctx, b)
- if err != nil {
- return err
+ if absent || exact.State == compute.StateTerminated {
+ next := b
+ next.TerminationConfirmed = true
+ if err = s.saveManagedBox(ctx, b, next, now); err != nil {
+ return err
+ }
+ b, err = s.loadManagedBox(ctx, b)
+ if err != nil {
+ return err
+ }
+ return s.finishManagedCleanup(ctx, b, present, now)
}
- return s.finishManagedCleanup(ctx, b, present, now)
}
- return s.managedRetry(ctx, b, "managed_absence_unconfirmed", now, true)
+ return s.managedRetry(ctx, b, reason, now, true)
}
+
a := found[0]
if !managedInstanceMatches(b, a) || (b.CloudID != "" && b.CloudID != a.CloudID) {
return s.managedRetry(ctx, b, "managed_identity_mismatch", now, true)
@@ -569,7 +586,7 @@ func (s *Server) verifyManagedPublication(ctx context.Context, b managedBox, now
if now.Before(b.LaunchStartedAt.Add(20 * time.Minute)) {
return nil
}
- next := b
+ next := clearManagedPublicationUncertainty(b)
next.State = "failed"
next.LastError = "managed_publication_absent"
next.NextCleanupAt = time.Time{}
@@ -586,7 +603,7 @@ func (s *Server) verifyManagedPublication(ctx context.Context, b managedBox, now
if decodeErr != nil || decoder.Decode(&extra) != io.EOF || got.Fleet != b.Fleet || got.Label != b.Label || got.Op != b.OpID || !got.ReadyAt.Equal(b.ReadyAt) || b.ReadyAt.IsZero() {
return s.managedPublicationUncertain(ctx, b, now)
}
- next := b
+ next := clearManagedPublicationUncertainty(b)
next.State = "ready"
next.NextCleanupAt = time.Time{}
if err = s.saveManagedBox(ctx, b, next, now); err != nil {
@@ -644,3 +661,20 @@ func (s *Server) finishManagedCleanup(ctx context.Context, b managedBox, present
next.NextCleanupAt = time.Time{}
return s.saveManagedBox(ctx, b, next, now)
}
+
+func clearManagedPublicationUncertainty(b managedBox) managedBox {
+ if b.LastError == "uncertain" {
+ b.LastError = ""
+ }
+ if b.RecoveryReason == "uncertain" {
+ b.RecoveryReason = ""
+ }
+ checks := make(map[string]managedCheck, len(b.Checks))
+ for k, v := range b.Checks {
+ if k != "recovery" || v.Reason != "uncertain" {
+ checks[k] = v
+ }
+ }
+ b.Checks = checks
+ return b
+}
diff --git a/internal/console/managedworker_test.go b/internal/console/managedworker_test.go
index d16ca4653..559bbee08 100644
--- a/internal/console/managedworker_test.go
+++ b/internal/console/managedworker_test.go
@@ -163,6 +163,13 @@ func TestManagedIdentityCleanup(t *testing.T) {
s, p, _, now := managedWorkerFixture(t)
workerStep(t, s, now)
b := workerStep(t, s, now.Add(20*time.Minute))
+ reg, err := openRegistry(s.cfg.Registry)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err = reg.AddFleetBox(registry.FleetBox{Fleet: b.Fleet, Label: b.Label, TokenHash: b.EnrolHash}); err != nil {
+ t.Fatal(err)
+ }
p.TerminateIdentityMismatch = true
b = workerStep(t, s, now.Add(20*time.Minute))
if b.State == "terminated" || b.NextCleanupAt.IsZero() || b.RecoveryReason == "" {
@@ -177,6 +184,25 @@ func TestManagedIdentityCleanup(t *testing.T) {
if p.Calls()["Terminate"] != 2 {
t.Fatal("missing hourly retry")
}
+ p.SetIdentity(b.CloudID, compute.Identity{Deployment: "foreign"})
+ b = workerStep(t, s, b.NextCleanupAt.Add(time.Hour))
+ if b.State == "terminated" || b.TerminationConfirmed || b.RecoveryReason != "managed_identity_mismatch" {
+ t.Fatal("empty identity lookup released a live instance")
+ }
+ if b.NextCleanupAt.IsZero() {
+ t.Fatal("mismatch lost hourly schedule")
+ }
+ boxes, err := reg.ListFleetBoxes(b.Fleet)
+ if err != nil || len(boxes) != 1 || boxes[0].Status != "active" {
+ t.Fatal("mismatch detached registry row", err)
+ }
+ var held int
+ if err = s.store.db.QueryRow(`SELECT count(*) FROM managed_boxes WHERE state!='terminated'`).Scan(&held); err != nil || held != 1 {
+ t.Fatal("mismatch released quota", held, err)
+ }
+ if p.Calls()["Lookup"] != 1 || p.Calls()["Terminate"] != 2 {
+ t.Fatal("unsafe exact-ID recovery", p.Calls())
+ }
}
func TestManagedFailedEnrolledCleanup(t *testing.T) {
s, p, b, now := managedWorkerFixture(t)
@@ -214,6 +240,7 @@ func TestManagedFailedEnrolledCleanup(t *testing.T) {
type managedComputeScript struct {
*compute.Fake
find func(context.Context, string, compute.Identity) ([]compute.Instance, error)
+ lookup func(context.Context, string, string) (compute.Instance, error)
terminate func(context.Context, string, string, compute.Identity) error
}
@@ -223,6 +250,12 @@ func (p *managedComputeScript) Find(ctx context.Context, region string, id compu
}
return p.Fake.Find(ctx, region, id)
}
+func (p *managedComputeScript) Lookup(ctx context.Context, region, id string) (compute.Instance, error) {
+ if p.lookup != nil {
+ return p.lookup(ctx, region, id)
+ }
+ return p.Fake.Lookup(ctx, region, id)
+}
func (p *managedComputeScript) Terminate(ctx context.Context, region, id string, want compute.Identity) error {
if p.terminate != nil {
return p.terminate(ctx, region, id, want)
@@ -230,7 +263,7 @@ func (p *managedComputeScript) Terminate(ctx context.Context, region, id string,
return p.Fake.Terminate(ctx, region, id, want)
}
func TestManagedAcceptedTerminateAbsent(t *testing.T) {
- for _, kind := range []string{"lost-response", "notfound", "crash-before-dispatch", "no-attempt", "different-id", "stopped", "shutting-down"} {
+ for _, kind := range []string{"lost-response", "notfound", "crash-before-dispatch", "no-attempt", "different-id", "identity-empty", "stopped", "shutting-down"} {
t.Run(kind, func(t *testing.T) {
s, p, _, now := managedWorkerFixture(t)
b := workerStep(t, s, now)
@@ -247,7 +280,7 @@ func TestManagedAcceptedTerminateAbsent(t *testing.T) {
return errors.New("lost response")
}
b = workerStep(t, s, now.Add(20*time.Minute))
- case "crash-before-dispatch", "notfound", "different-id":
+ case "crash-before-dispatch", "notfound", "different-id", "identity-empty":
b = workerAdvance(t, s, b, func(b *managedBox) {
b.State = "terminating"
b.TerminateAttemptedAt = now
@@ -269,6 +302,14 @@ func TestManagedAcceptedTerminateAbsent(t *testing.T) {
return nil, nil
}
}
+ if kind != "identity-empty" && kind != "stopped" && kind != "shutting-down" {
+ spy.lookup = func(_ context.Context, region, id string) (compute.Instance, error) {
+ if region != b.Region || id != b.CloudID {
+ t.Fatal("lookup did not address exact instance")
+ }
+ return compute.Instance{}, os.ErrNotExist
+ }
+ }
s = restartManagedWorker(t, s)
b = workerStep(t, s, now.Add(2*time.Hour))
wantTerminated := kind == "lost-response" || kind == "notfound" || kind == "crash-before-dispatch"
@@ -789,3 +830,62 @@ func TestManagedWorkerClearsRetrySchedule(t *testing.T) {
t.Fatal("successful observation retained an expired retry time")
}
}
+
+func TestManagedProviderMissingKeepsReservation(t *testing.T) {
+ s, p, b, now := managedWorkerFixture(t)
+ s.cfg.ManagedCompute = nil
+ got := workerStep(t, s, now)
+ if got.storedLaunch != b.storedLaunch {
+ t.Fatal("missing provider changed reservation")
+ }
+ s = restartManagedWorker(t, s)
+ got = workerStep(t, s, b.CreatedAt.Add(30*time.Minute))
+ if got.State != "terminated" || !got.LaunchStartedAt.IsZero() || got.CloudID != "" || p.Calls()["Launch"] != 0 || p.Calls()["Terminate"] != 0 {
+ t.Fatal("never-launched reservation did not expire safely")
+ }
+ var held int
+ if err := s.store.db.QueryRow(`SELECT count(*) FROM managed_boxes WHERE state!='terminated'`).Scan(&held); err != nil || held != 0 {
+ t.Fatal("quota not released", held, err)
+ }
+}
+func TestManagedPublicationUncertaintyResolves(t *testing.T) {
+ for _, published := range []bool{false, true} {
+ t.Run(map[bool]string{false: "absent", true: "ready"}[published], func(t *testing.T) {
+ s, _, b, now := managedWorkerFixture(t)
+ reg, err := openRegistry(s.cfg.Registry)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err = reg.AddFleetBox(registry.FleetBox{Fleet: b.Fleet, Label: b.Label, TokenHash: b.EnrolHash}); err != nil {
+ t.Fatal(err)
+ }
+ b = workerStep(t, s, now)
+ b = workerAdvance(t, s, b, func(b *managedBox) { b.State = "publishing"; b.ReadyAt = now })
+ st := &managedWorkerStore{Store: s.cfg.Releases, getErr: errors.New("unavailable")}
+ s.cfg.Releases = st
+ b = workerStep(t, s, now.Add(20*time.Minute))
+ if b.LastError != "uncertain" {
+ t.Fatal("fixture did not become uncertain")
+ }
+ st.getErr = nil
+ if published {
+ raw, _ := json.Marshal(managedReadyObject{Fleet: b.Fleet, Label: b.Label, ReadyAt: b.ReadyAt, Op: b.OpID})
+ if _, err = st.Put(context.Background(), managedReadyKey(b), raw, ""); err != nil {
+ t.Fatal(err)
+ }
+ }
+ s = restartManagedWorker(t, s)
+ b = workerStep(t, s, b.NextCleanupAt)
+ if b.RecoveryReason == "uncertain" || b.LastError == "uncertain" || b.Checks["recovery"].Reason == "uncertain" {
+ t.Fatal("resolved publication retained uncertainty")
+ }
+ if published {
+ if b.State != "ready" || b.LastError != "" {
+ t.Fatal("wrong ready evidence")
+ }
+ } else if b.State != "failed" || b.LastError != "managed_publication_absent" {
+ t.Fatal("wrong failure evidence")
+ }
+ })
+ }
+}
diff --git a/internal/console/testdata/claim-authority-sites.txt b/internal/console/testdata/claim-authority-sites.txt
index 6f8f5073b..d8914cae6 100644
--- a/internal/console/testdata/claim-authority-sites.txt
+++ b/internal/console/testdata/claim-authority-sites.txt
@@ -152,3 +152,4 @@ claim_loss_pages.go|pageClaimLossesAt|s.store.db.QueryRowContext(ctx, `SELECT la
store_gate.go|OpenGated|s.db.Exec(`ALTER TABLE claim_loss_pages ADD COLUMN last_key TEXT NOT NULL DEFAULT ''`)
awsregionmetric.go|capacityPublisherFromEnv|cloudwatch.NewFromConfig(cfg, func(o *cloudwatch.Options) { o.Region = awsRegion })
../../cmd/console/hostsused.go|runHostsUsed|os.Open(*listingsPath)
+managedhistory.go|managedCredentialsHeld|seal.Open(sealed)
diff --git a/internal/console/testdata/claim-routes.txt b/internal/console/testdata/claim-routes.txt
index 865bdd9e1..b913afeea 100644
--- a/internal/console/testdata/claim-routes.txt
+++ b/internal/console/testdata/claim-routes.txt
@@ -110,6 +110,7 @@ route GET /api/cli/apps/{account}/{app}/telemetry
route GET /api/cli/apps/{account}/{app}/version-target
route GET /api/cli/billing/problems
route GET /api/cli/fleets/{account}
+route GET /api/cli/fleets/{account}/{fleet}
route GET /api/cli/services/{account}
route GET /api/cli/status/instances
route GET /api/cli/status/layout
@@ -119,6 +120,7 @@ route GET /api/cli/system/geoip
route GET /api/cli/system/hosts-used/status
route GET /api/cli/system/jobs/{id}
route GET /api/cli/system/layout
+route GET /api/cli/system/managed-fleets
route GET /api/cli/system/pointer-digests
route GET /api/cli/system/status
route GET /apps
@@ -353,9 +355,11 @@ route PUT /api/cli/apps/{account}/{app}/updates
route PUT /api/cli/apps/{account}/{app}/version-target
route PUT /api/cli/fleets/{account}/{fleet}/secrets-key
route PUT /api/cli/system/geoip
+route PUT /api/cli/system/managed-fleets
route PUT /api/cli/system/upload
worker FleetRelabel
worker LogPlacementDiscrepancies
+worker ManagedFleets
worker PublishMovesConsole
worker PublishPlansMarker
worker ReportApexSquats
diff --git a/internal/hostops/storage_classifier.go b/internal/hostops/storage_classifier.go
index 64e9571a1..6d070fa21 100644
--- a/internal/hostops/storage_classifier.go
+++ b/internal/hostops/storage_classifier.go
@@ -83,6 +83,8 @@ func deploymentFamily(key string) (string, familyCheck) {
return "moves-console", checkMovesConsole
case len(p) == 3 && p[0] == "accounts" && p[2] == "telemetry.json" && controlname.ValidAccount(p[1]):
return "account-telemetry", checkAccountTelemetry
+ case key == release.ManagedFleetsConfigKey:
+ return "system-managed-fleets", checkManagedFleetsConfig
case key == release.SystemKey(release.AntivirusName):
return "system-antivirus", checkAntivirus
case len(p) == 4 && p[0] == "bootstrap" && p[1] == "router":
@@ -318,3 +320,14 @@ func checkSystemPointer(w *ControlWriter, channel string, t MutationTarget) (str
}
return "root-signed platform channel pointer; names a platform release, never an app's", nil
}
+
+func checkManagedFleetsConfig(_ *ControlWriter, t MutationTarget) (string, error) {
+ var config release.ManagedFleetsConfig
+ if err := strictJSON(t.After, &config); err != nil {
+ return "", err
+ }
+ if config.Ceiling < 0 || config.AccountLimit < 0 {
+ return "", ErrIdentity
+ }
+ return "operator-managed deployment compute admission configuration; contains no app records", nil
+}
diff --git a/internal/hostops/storage_classifier_test.go b/internal/hostops/storage_classifier_test.go
index b0a37b582..8c9352a89 100644
--- a/internal/hostops/storage_classifier_test.go
+++ b/internal/hostops/storage_classifier_test.go
@@ -99,3 +99,27 @@ func TestScanDayIsRewrittenByCASNotCreateOnly(t *testing.T) {
t.Fatalf("ClassifyMutation = %+v, %v", c, err)
}
}
+
+func TestManagedConfigClassification(t *testing.T) {
+ for _, tc := range []struct {
+ key, body, method string
+ ok bool
+ }{
+ {"system/managed-fleets.json", `{"enabled":false,"ceiling":3,"account_limit":0,"regions":{}}`, "Put", true},
+ {"system/managed-fleets.json", `{"enabled":false,"app":"shop"}`, "Put", false},
+ {"system/managed-fleets.json/extra", `{}`, "Put", false},
+ {"system/managed-fleets.jsonx", `{}`, "Put", false},
+ {"system/managed-fleets.json", `{}`, "Delete", false},
+ {"system/managed-fleets.json", `{"regions":{"eu-west-1":{"image":"image","apps":["shop"]}}}`, "Put", false},
+ } {
+ t.Run(tc.key+tc.body+tc.method, func(t *testing.T) {
+ c, err := ClassifyMutation(context.Background(), nil, nil, MutationTarget{Key: tc.key, Method: tc.method, After: []byte(tc.body)})
+ if (err == nil) != tc.ok {
+ t.Fatalf("classification: %v, want allowed=%v", err, tc.ok)
+ }
+ if tc.ok && (c.NonApp == "" || len(c.Scopes) != 0) {
+ t.Fatal("not deployment scope")
+ }
+ })
+ }
+}
diff --git a/internal/provision/testdata/plan14-root-reads-chain.tsv b/internal/provision/testdata/plan14-root-reads-chain.tsv
index f96db77bf..55ab19233 100644
--- a/internal/provision/testdata/plan14-root-reads-chain.tsv
+++ b/internal/provision/testdata/plan14-root-reads-chain.tsv
@@ -61,3 +61,4 @@ plan14-root-reads-managed-fleets-2a-task-3.tsv 43389a9f6ddf3f5f2c23dbfaec9fd0df2
plan14-root-reads-managed-fleets-2a-task-4.tsv 63ec311c20f67c064f2c2066f5aed2f7ddd9ecc545b385511485c480fceafb6f
plan14-root-reads-managed-fleets-2a-task-5.tsv 19ad67bdbe2f4269fbfadd44bd36ca166118908e4e9d9da8f9b7a95916d013ee
plan14-root-reads-managed-fleets-2a-task-6.tsv d63dcbb0494381ce43314094fecfd1780abc890af3774c145eb9ec9b1d54afde
+plan14-root-reads-managed-fleets-2a-task-6-fix1.tsv 6f7852cb59ad8e795883178b98353b385b6ccfc430f28dada330d019d5e5061d
diff --git a/internal/provision/testdata/plan14-root-reads-managed-fleets-2a-task-6-fix1.tsv b/internal/provision/testdata/plan14-root-reads-managed-fleets-2a-task-6-fix1.tsv
new file mode 100644
index 000000000..1d6655558
--- /dev/null
+++ b/internal/provision/testdata/plan14-root-reads-managed-fleets-2a-task-6-fix1.tsv
@@ -0,0 +1,7 @@
+# Census overlay managed-fleets-2a-task-6-fix1, written by census-propose (#369). census-ruling-managed-fleets-2a-task-6-fix1, approved on #280 before the merge; the approval card is docs/superpowers/notes/census-proposal-managed-fleets-2a-task-6-fix1.md.
+# 1 body, 0 sites, 3 envelope: each changed unit re-frozen at its existing disposition with its claim appended.
+@legacy 0e8ee3e7dee96d62627431dbd9985d1e89101e95acd3f8b55fbeaac6317f1167 internal/registry/fleets.go Registry.UpsertFleet legacy accepted-legacy accepted-legacy;rev3=J1,J4;basis=route-and-input;rev3=census-ruling-managed-fleets-2a-task-4;basis=Persist Managed on insertion; conflict updates require same account and BYO on both sides, preserving ownership and Managed; managed fleet bucket changes refused.;rev3=census-ruling-managed-fleets-2a-task-6-fix1;basis=Restore pre-branch account and bucket updates for BYO-to-BYO conflicts only; both existing and incoming managed flags must remain false. Managed ownership and bucket remain protected. Witness TestManagedUpsertPreservesBYOOwnerUpdates local/remote and eight edge regression tests. file:Exec@325,registry:Account@604,registry:Bucket@615,registry:CreatedAt@258,registry:CreatedAt@279,registry:CreatedAt@625,registry:Managed@638,registry:Name@188,registry:Name@243,registry:Name@596,registry:remote@52,registry:remote@82,registry:sql@325,whole:Fleet@138,whole:Fleet@141,whole:remoteClient@54,whole:remoteClient@84 b1a39543d3b381f0d760a90ac62722483f4d025dfd8f433c11a7c0639264c934
+internal/registry/fleets.go Registry.UpsertFleet legacy accepted-legacy accepted-legacy;rev3=J1,J4;basis=route-and-input;rev3=census-ruling-managed-fleets-2a-task-4;basis=Persist Managed on insertion; conflict updates require same account and BYO on both sides, preserving ownership and Managed; managed fleet bucket changes refused.;rev3=census-ruling-managed-fleets-2a-task-6-fix1;basis=Restore pre-branch account and bucket updates for BYO-to-BYO conflicts only; both existing and incoming managed flags must remain false. Managed ownership and bucket remain protected. Witness TestManagedUpsertPreservesBYOOwnerUpdates local/remote and eight edge regression tests. file:Exec@325,registry:Account@604,registry:Bucket@615,registry:CreatedAt@258,registry:CreatedAt@279,registry:CreatedAt@625,registry:Managed@638,registry:Name@188,registry:Name@243,registry:Name@596,registry:remote@52,registry:remote@82,registry:sql@325,whole:Fleet@138,whole:Fleet@141,whole:remoteClient@54,whole:remoteClient@84 b1a39543d3b381f0d760a90ac62722483f4d025dfd8f433c11a7c0639264c934
+@coverage internal/hostops 925016dd7464127f9288649670523dda4ebba01335c5fcdcc49fd6cc97dac921
+@coverage internal/registry bfe1f9bc635427eae1a34c0f74fa02d59991989eb2d6d4f30d74229fc050b2ab
+@coverage internal/release 374fe119b06f3e8a0babebf5998be26fb2bf294494e048eaed34471eb5f4eaf7
diff --git a/internal/registry/fleets.go b/internal/registry/fleets.go
index 019dd7571..5498e4019 100644
--- a/internal/registry/fleets.go
+++ b/internal/registry/fleets.go
@@ -238,7 +238,7 @@ func (r *Registry) UpsertFleet(f Fleet) error {
INSERT INTO fleets (name, account, bucket, created_at, managed, rev)
VALUES (?, ?, ?, ?, ?, 1)
ON CONFLICT(name) DO UPDATE SET
- bucket = excluded.bucket, rev = fleets.rev + 1 WHERE fleets.account = excluded.account AND fleets.managed = 0 AND excluded.managed = 0`,
+ account = excluded.account, bucket = excluded.bucket, rev = fleets.rev + 1 WHERE fleets.managed = 0 AND excluded.managed = 0`,
f.Name, f.Account, f.Bucket, f.CreatedAt, f.Managed)
return err
}
diff --git a/internal/registry/fleets_test.go b/internal/registry/fleets_test.go
index 5b0bfc819..5e35ae77c 100644
--- a/internal/registry/fleets_test.go
+++ b/internal/registry/fleets_test.go
@@ -845,3 +845,45 @@ func TestManagedRegistryPreparationMethods(t *testing.T) {
})
}
}
+
+func TestManagedUpsertPreservesBYOOwnerUpdates(t *testing.T) {
+ for _, remote := range []bool{false, true} {
+ t.Run(map[bool]string{false: "local", true: "remote"}[remote], func(t *testing.T) {
+ var r *Registry
+ if remote {
+ r, _ = remoteTestRegistry(t)
+ } else {
+ r = openTestRegistry(t)
+ }
+ original := Fleet{Name: "production", Account: "owner", Bucket: "old-data"}
+ if err := r.UpsertFleet(original); err != nil {
+ t.Fatal(err)
+ }
+ before, err := r.Fingerprint()
+ if err != nil {
+ t.Fatal(err)
+ }
+ replacement := Fleet{Name: original.Name, Account: "new-owner", Bucket: "new-data"}
+ if err = r.UpsertFleet(replacement); err != nil {
+ t.Fatal(err)
+ }
+ got, err := r.GetFleet(original.Name)
+ if err != nil || got.Account != replacement.Account || got.Bucket != replacement.Bucket || got.Managed {
+ t.Fatal("BYO update lost", got, err)
+ }
+ after, err := r.Fingerprint()
+ if err != nil || before == after {
+ t.Fatal("owner change did not bump fingerprint", err)
+ }
+ replacement.Managed = true
+ replacement.Account = "foreign"
+ if err = r.UpsertFleet(replacement); err != nil {
+ t.Fatal(err)
+ }
+ got, err = r.GetFleet(original.Name)
+ if err != nil || got.Account != "new-owner" || got.Managed {
+ t.Fatal("upsert converted BYO to managed", got, err)
+ }
+ })
+ }
+}
diff --git a/internal/release/managedfleets.go b/internal/release/managedfleets.go
new file mode 100644
index 000000000..20c42a179
--- /dev/null
+++ b/internal/release/managedfleets.go
@@ -0,0 +1,19 @@
+package release
+
+// The console writer and the host-claim classifier share this wire shape,
+// so a new field cannot silently bypass the classifier's strict decoding.
+const ManagedFleetsConfigKey = "system/managed-fleets.json"
+
+type ManagedFleetsConfig struct {
+ Enabled bool `json:"enabled"`
+ Ceiling int `json:"ceiling"`
+ AccountLimit int `json:"account_limit"`
+ Regions map[string]ManagedFleetRegion `json:"regions"`
+}
+type ManagedFleetRegion struct {
+ Image string `json:"image"`
+ Subnets []string `json:"subnets"`
+ SecurityGroups []string `json:"security_groups"`
+ RootGB int `json:"root_gb"`
+ Sizes map[string]string `json:"sizes"`
+}