carlos / platform Public

Seed files on customer fleets (#1139, slice 3)

The console side of carlos instances create --seed-file on a fleet-placed
app: deployment-bucket snapshot, fleet readiness (one active nested box at
protocol 4), and POST /api/fleet/seeds/{account}/{app}/{host}/{op} for the
owning box's placed/failed/rolledback. A fleet file seed's hostname is held
in the retire primitives until rolledback; trash and purge refuse while one
is unfinished; delete names where a leftover copy is. Census APPROVED (#280);
branch review READY AFTER FIXES.

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

Squashed from fleet-seeded-create-3 into main.
Paul Campbell pushed by claude agent, operated by paul@keymail.dev fe854a4e086fbbb0cf950764cb17748dcba488a0 parent 772aabb
46 files changed, +3,365 −133
  • approved_fleet_seeded_copy_test.go +18 −1
  • docs/parity.md +1 −1
  • docs/site/cli.md +3 −1
  • docs/superpowers/notes/census-proposal-fleet-seeded-create-3.md +11 −0
  • docs/superpowers/plans/2026-11-20-fleet-seeded-create.md +1 −0
  • internal/activator/seedfleet_linux_test.go +1 −1
  • internal/console/apicli.go +10 −0
  • internal/console/apidomains.go +4 −0
  • internal/console/apifleetseeds.go +321 −0
  • internal/console/apifleetseeds_test.go +666 −0
  • internal/console/apiinstanceimport.go +19 −7
  • internal/console/apilinks_test.go +3 −0
  • internal/console/appsettings.go +10 −0
  • internal/console/claim_invariant_fixtures_test.go +5 −0
  • internal/console/claim_invariant_seeds_test.go +69 −0
  • internal/console/demo_expiry.go +9 −0
  • internal/console/domainattach.go +6 −0
  • internal/console/domainattach_test.go +8 −0
  • internal/console/expirypass.go +20 −0
  • internal/console/hostclaimops.go +43 −0
  • internal/console/lifetimes_create_test.go +3 −1
  • internal/console/lifetimes_purge.go +9 −0
  • internal/console/lifetimes_retire.go +10 −0
  • internal/console/linkedpolicy.go +3 −0
  • internal/console/ownership.go +18 −0
  • internal/console/routedecls.go +7 −0
  • internal/console/seedfile.go +388 −38
  • internal/console/seedfile_copy.go +49 −0
  • internal/console/seedfile_test.go +4 −5
  • internal/console/seedfilefleet_test.go +602 −0
  • internal/console/seedfinish.go +14 −6
  • internal/console/seedfloor.go +25 −15
  • internal/console/seedholdreview_test.go +294 −0
  • internal/console/seedpurgehold_test.go +173 −0
  • internal/console/seedslice3review_test.go +180 −0
  • internal/console/seedsweep.go +167 −36
  • internal/console/temphook_test.go +16 −0
  • internal/console/testdata/claim-routes.txt +3 −0
  • internal/provision/fleet_seeded_create_3_census_test.go +116 −0
  • internal/provision/plan9_b8_census_test.go +1 −1
  • internal/provision/seed.go +30 −14
  • internal/provision/seed_test.go +19 −5
  • internal/provision/testdata/plan14-root-reads-chain.tsv +1 −0
  • internal/provision/testdata/plan14-root-reads-fleet-seeded-create-3.tsv +3 −0
  • parity/parity.tsv +1 −1
  • scripts/gitleaks-gate/notscanned.go +1 −0

CI passed — run details

diff --git a/approved_fleet_seeded_copy_test.go b/approved_fleet_seeded_copy_test.go
index 514618d60..de2ad5121 100644
--- a/approved_fleet_seeded_copy_test.go
+++ b/approved_fleet_seeded_copy_test.go
@@ -38,8 +38,25 @@ func TestApprovedFleetSeededCopy(t *testing.T) {
{"FS-42", "internal/console/seedfile_copy.go", "began seeding %s from a file (%s, %d bytes)"},
{"FS-43", "internal/console/seedfile_copy.go", "uploaded the seed file for %s"},
{"FS-25", "internal/console/seedfile_copy.go", "This deployment’s seeds floor does not allow seed files yet. An operator publishes it again with carlos system seeds-floor publish."},
+ {"FS-21", "internal/console/seedfile_copy.go", "fleet %s has more than one active box. A seeded instance needs a fleet with one active box for now."},
+ {"FS-22", "internal/console/seedfile_copy.go", "could not confirm every box in fleet %s. Try again in a minute."},
+ {"FS-23", "internal/console/seedfile_copy.go", "the platform on %s in fleet %s is below the seeds floor. Update it, then try again."},
+ {"FS-24", "internal/console/seedfile_copy.go", "claim control is on for %s in fleet %s. Seeded instances are not supported there yet."},
+ {"FS-26", "internal/console/seedfile_copy.go", "%s in fleet %s keeps all its instances in one shared directory. A seed file needs a box that keeps each instance in its own."},
+ {"FS-27", "internal/console/seedfile_copy.go", "the seed file on the box did not match the upload"},
+ {"FS-28", "internal/console/seedfile_copy.go", "the seed file on the box failed its integrity check"},
+ {"FS-29", "internal/console/seedfile_copy.go", "a copy of data already exists for this hostname"},
+ {"FS-30", "internal/console/seedfile_copy.go", "a copy of its data is still in the fleet’s storage"},
+ {"FS-33", "internal/console/seedfile_copy.go", "%s was not created. Its hostname is free again once its box has cleaned up."},
+ {"FS-34", "internal/console/seedfile_copy.go", "%s keeps its hostname while a copy of its data is still in the fleet’s storage, under %s. Remove everything there, and the hostname is free again after the box’s next pass."},
+ {"FS-35", "internal/console/seedfile_copy.go", "%s can’t be deleted permanently until its fleet box has cleaned up %s."},
+ {"FS-39", "internal/console/seedfile_copy.go", "%s can’t be moved to the trash until its fleet box has cleaned up %s. Delete each with carlos instances delete, then try again."},
+ {"FS-36", "internal/console/seedfile_copy.go", "%s/ (after the box’s CARLOS_HIBERNATE_PREFIX, if set)"},
+ {"FS-37", "internal/console/seedfile_copy.go", "moves/%s/"},
+ {"FS-38", "internal/console/seedfile_copy.go", "%s and %s"},
{"FS-40", "internal/activator/seedfleet.go", "%s could not start from its seed: a copy of data already exists for this hostname."},
- {"docs seed-file", "docs/site/cli.md", "To start a new instance from a SQLite database file you already have, add --seed-file. The file can be up to 4 GiB. The CLI uploads it, the console checks that it is a sound database, and the new instance starts from it the first time it wakes. This is for an app that runs in a region. You can't combine it with --from, and the new instance is an ordinary one, so --kind, --addr and --role don't apply. If the upload or the check fails, nothing is created, and the hostname is free again once its box has cleaned up."},
+ {"docs seed-file", "docs/site/cli.md", "To start a new instance from a SQLite database file you already have, add --seed-file. The file can be up to 4 GiB. The CLI uploads it, the console checks that it is a sound database, and the new instance starts from it the first time it wakes. This works for an app that runs in a region and for an app on a fleet of your own. You can't combine it with --from, and the new instance is an ordinary one, so --kind, --addr and --role don't apply. If the upload or the check fails, nothing is created, and the hostname is free again once its box has cleaned up."},
+ {"docs fleet seed-file", "docs/site/cli.md", "On a fleet of your own, the fleet must have exactly one active box, and that box must keep each instance in its own directory. If the upload or the check fails, or you delete the instance before it first wakes, the hostname stays taken until the fleet's box has cleaned up. If a copy of the data is still in the fleet's bucket, the hostname stays taken after that too, and the delete answer names where the copy is. Remove that host's copy from the fleet's bucket, and the hostname is free again on the box's next pass. For example, if fleet main holds a leftover copy of new.example.com, remove it from main's bucket."},
}
for _, row := range rows {
t.Run(row.key, func(t *testing.T) {
diff --git a/docs/parity.md b/docs/parity.md
index 1212b2fef..fe68bf72b 100644
--- a/docs/parity.md
+++ b/docs/parity.md
@@ -501,5 +501,5 @@ Discussion #1289.
| legacy-apps | platform | | `GET /apps`<br>`GET /apps/{app}` | Old URLs kept as redirects into the account. |
| billing-webhook | platform | | `POST /billing/webhook` | Stripe calls it. |
| ses-events | platform | | `POST /api/ses/events` | Amazon SES delivery events. |
-| box-doors | platform | | `POST /api/fleet/enrol`<br>`GET /api/box/interactive/{id}`<br>`GET /api/box/runs/{id}`<br>`POST /api/fleet/replicas/{account}/{app}/{host}/coordinator`<br>`POST /api/fleet/replicas/{account}/{app}/{host}/release`<br>`POST /api/fleet/replicas/{account}/{app}/{host}/deploy` | Doors boxes and managed fleets call, not people. |
+| box-doors | platform | | `POST /api/fleet/enrol`<br>`GET /api/box/interactive/{id}`<br>`GET /api/box/runs/{id}`<br>`POST /api/fleet/replicas/{account}/{app}/{host}/coordinator`<br>`POST /api/fleet/replicas/{account}/{app}/{host}/release`<br>`POST /api/fleet/replicas/{account}/{app}/{host}/deploy`<br>`POST /api/fleet/seeds/{account}/{app}/{host}/placed`<br>`POST /api/fleet/seeds/{account}/{app}/{host}/failed`<br>`POST /api/fleet/seeds/{account}/{app}/{host}/rolledback` | Doors boxes and managed fleets call, not people. |
| plumbing | platform | `__demo-snapshot`<br>`__registry-child`<br>`__rootfs-check-probe`<br>`__rootfs-check-prepare`<br>`__cgexec`<br>`__cgprobe` | | Words the binary runs itself as, dispatched before the command switch. |
diff --git a/docs/site/cli.md b/docs/site/cli.md
index bd4a0d2e9..428ea03cf 100644
--- a/docs/site/cli.md
+++ b/docs/site/cli.md
@@ -1400,12 +1400,14 @@ carlos instances create --app shop --host canary.example.com --from www.example.
carlos instances create --app shop --host canary.example.com --from www.example.com --at 4211
```
-To start a new instance from a SQLite database file you already have, add --seed-file. The file can be up to 4 GiB. The CLI uploads it, the console checks that it is a sound database, and the new instance starts from it the first time it wakes. This is for an app that runs in a region. You can't combine it with --from, and the new instance is an ordinary one, so --kind, --addr and --role don't apply. If the upload or the check fails, nothing is created, and the hostname is free again once its box has cleaned up.
+To start a new instance from a SQLite database file you already have, add --seed-file. The file can be up to 4 GiB. The CLI uploads it, the console checks that it is a sound database, and the new instance starts from it the first time it wakes. This works for an app that runs in a region and for an app on a fleet of your own. You can't combine it with --from, and the new instance is an ordinary one, so --kind, --addr and --role don't apply. If the upload or the check fails, nothing is created, and the hostname is free again once its box has cleaned up.
```sh
carlos instances create --app shop --host new.example.com --seed-file shop.db
```
+On a fleet of your own, the fleet must have exactly one active box, and that box must keep each instance in its own directory. If the upload or the check fails, or you delete the instance before it first wakes, the hostname stays taken until the fleet's box has cleaned up. If a copy of the data is still in the fleet's bucket, the hostname stays taken after that too, and the delete answer names where the copy is. Remove that host's copy from the fleet's bucket, and the hostname is free again on the box's next pass. For example, if fleet main holds a leftover copy of new.example.com, remove it from main's bucket.
+
carlos instances import moves an instance the platform never ran onto the platform. Stop the old process, take a consistent snapshot of its database (VACUUM INTO works), and run the import with the address of the route it replaces. The console checks the file, the box swaps the route on its next pass, and from then until you commit, the host answers only requests that carry the verify token. With --verify, the CLI requests that path with the token and commits on a 2xx or aborts otherwise. Without it, the CLI prints the token and the two commands to finish by hand. Aborting puts the old route back exactly as it was.
```sh
diff --git a/docs/superpowers/notes/census-proposal-fleet-seeded-create-3.md b/docs/superpowers/notes/census-proposal-fleet-seeded-create-3.md
new file mode 100644
index 000000000..44c647e31
--- /dev/null
+++ b/docs/superpowers/notes/census-proposal-fleet-seeded-create-3.md
@@ -0,0 +1,11 @@
+# Census approval: fleet-seeded-create-3
+
+Ruling `census-ruling-fleet-seeded-create-3`. 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: `8a0a9cca336d3e695b79990a9aeda17f5ee8d74908752944f7dcd129918c80fc` → `8a0a9cca336d3e695b79990a9aeda17f5ee8d74908752944f7dcd129918c80fc`.
+
+Overlay: `internal/provision/testdata/plan14-root-reads-fleet-seeded-create-3.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`.
diff --git a/docs/superpowers/plans/2026-11-20-fleet-seeded-create.md b/docs/superpowers/plans/2026-11-20-fleet-seeded-create.md
index 1cf27542b..c104b02a3 100644
--- a/docs/superpowers/plans/2026-11-20-fleet-seeded-create.md
+++ b/docs/superpowers/plans/2026-11-20-fleet-seeded-create.md
@@ -854,6 +854,7 @@ House rules applied: no em dashes; curly apostrophes; placeholders in their orde
| FS-37 | (FS-34's location, `held` staging) moves/%s/ | new | approved (Paul, 2026-11-20) (Decision D12) |
| FS-38 | (FS-34's location, `held` both: FS-36, then FS-37) %s and %s | new | approved (Paul, 2026-11-20) (Decision D12) |
| FS-35 | %s can’t be deleted permanently until its fleet box has cleaned up %s. | %s can’t be purged yet: %s still hold their hostnames until their fleet box has cleaned up. | approved (Paul, 2026-11-20) (the Trash page's "Delete now", and the trash sweep's log) |
+| FS-39 | %s can’t be moved to the trash until its fleet box has cleaned up %s. Delete each with carlos instances delete, then try again. | new | approved (Paul, 2026-11-20) (slice 3 review P2-1: the trash doors' 409 and the expiry pass's log while an app holds an unfinished fleet file seed; %s is the app, then the hosts) |
| FS-41 | kind must be file, or left out for an import | new | approved (Paul, 2026-11-20) (an import object whose kind is neither absent nor `file`; 400, as the sibling shape sentences SD-N48 and the sha256 rule; only a hand-written API call reaches it) |
| FS-42 | began seeding %s from a file (%s, %d bytes) | new | approved (Paul, 2026-11-20) (the begin's `instance-seed` activity row: host, first 12 of the sha256, length; as the import's "began an import of …") |
| FS-43 | uploaded the seed file for %s | new | approved (Paul, 2026-11-20) (the upload's `seed-file-uploaded` activity row; as the import's "uploaded the snapshot for %s") |
diff --git a/internal/activator/seedfleet_linux_test.go b/internal/activator/seedfleet_linux_test.go
index 2deebb931..e7fc1c5d9 100644
--- a/internal/activator/seedfleet_linux_test.go
+++ b/internal/activator/seedfleet_linux_test.go
@@ -738,7 +738,7 @@ func TestFleetFileSeedInterruptedPlacementHoldsHostname(t *testing.T) {
case provision.FleetSeedPlaced:
return placedErr
case provision.FleetSeedFailed:
- _, err := provision.SetRecordSeed(ctx, store, a, app, h, provision.SeedFail(id, code))
+ _, err := provision.SetRecordSeed(ctx, store, a, app, h, provision.SeedFail(id, code, held))
return err
}
return nil
diff --git a/internal/console/apicli.go b/internal/console/apicli.go
index 034a81841..a0f6390dd 100644
--- a/internal/console/apicli.go
+++ b/internal/console/apicli.go
@@ -1787,6 +1787,16 @@ func (s *Server) handleAPITrashApp(w http.ResponseWriter, r *http.Request) {
})
return
}
+ // A fleet file seed its box has not proved gone (fleetSeedTrashRefusal):
+ // refused before the marker, so nothing changes.
+ if msg, err := s.fleetSeedTrashRefusal(ctx, acct.Sqid, app); err != nil {
+ log.Printf("console: api trash %s/%s: fleet seeds: %v", acct.Sqid, app, err)
+ jsonError(w, http.StatusBadGateway, "could not write the trash marker — nothing was deleted; try again")
+ return
+ } else if msg != "" {
+ jsonError(w, http.StatusConflict, msg)
+ return
+ }
now := time.Now()
if err := release.TrashApp(ctx, s.cfg.Releases, acct.Sqid, app, addr, now); err != nil {
log.Printf("console: api trash %s/%s: %v", acct.Sqid, app, err)
diff --git a/internal/console/apidomains.go b/internal/console/apidomains.go
index 503f47511..8331fe835 100644
--- a/internal/console/apidomains.go
+++ b/internal/console/apidomains.go
@@ -1261,6 +1261,10 @@ func (s *Server) handleAPIDomainDetach(w http.ResponseWriter, r *http.Request) {
}
} else if err == nil && cur.Account == acct.Sqid && cur.App == app && cur.Route == "" {
if err := s.retireInstanceRecord(ctx, acct.Sqid, app, host, principal, cur.RecordIncarnation, retireAny); err != nil {
+ if ref, ok := fleetSeedHoldRefusal(err); ok {
+ jsonError(w, ref.Status, ref.Msg)
+ return
+ }
if accepted, ok := claimRetireAcceptedOf(err); ok {
s.audit(acct, app, principal, "domain-detach", "detach of hostname "+host+" accepted, operation "+accepted.operation+" (cli)")
s.bumpSerial(ctx)
diff --git a/internal/console/apifleetseeds.go b/internal/console/apifleetseeds.go
new file mode 100644
index 000000000..1e7996e16
--- /dev/null
+++ b/internal/console/apifleetseeds.go
@@ -0,0 +1,321 @@
+// The fleet seeds door (fleet seeded create design §3.5, plan Task 15).
+//
+// A customer-fleet box cannot write records: the store door refuses it
+// (ruling 4). So it reports what it did with a file seed here, and the
+// console makes the record's transition:
+//
+// POST /api/fleet/seeds/{account}/{app}/{host}/placed|failed|rolledback
+// {"id": "<seed id>", "code": "<code>", "held": "<where>"}
+//
+// The box sends codes, never text (decisions D4, D12): the console maps a
+// code to its approved sentence, and keeps held so the delete door can name
+// where the copy is from the host alone.
+//
+// This door is the only way a fleet file seed reaches rolled-back. The box
+// reports rolledback only after it has proved nothing of the seed is left
+// (provision.rollbackFleetFileSeed, design §3.6), and that is what lets the
+// finish here release the hostname.
+//
+// The gates, in order: the box's identity and its ownership of the record
+// (fleetSeedRecord), each refused with the identical 404 before anything
+// about the record is revealed; then the body (400); then, under the app's
+// record lock and with ownership checked again there, the record's own seed
+// id and state (409 when the record says otherwise, nothing changed).
+
+package console
+
+import (
+ "context"
+ "errors"
+ "log"
+ "net/http"
+ "os"
+ "strings"
+
+ "github.com/carlosframework/platform/internal/provision"
+ "github.com/carlosframework/platform/internal/registry"
+ "github.com/carlosframework/platform/internal/release"
+ "github.com/carlosframework/platform/internal/seeds"
+)
+
+// fleetSeedRecord authenticates the caller exactly as replicaFleetRecord
+// does (replicacoordinator.go): the tunnel name and bearer token are an
+// active box of a fleet the path's account owns, and the record is placed
+// on that fleet ("fleet/<fleet>") and not retired. Then the seed is a file
+// seed, and the caller owns the record: FleetBox names it, or there is no
+// FleetBox and the caller is the fleet's sole active box (a file seed's
+// record is created unlabelled, plan G1). A record that carries a replica
+// assignment is refused outright: the box grants itself ownership by
+// assignment (provision ownsRecord), but no create path writes one on a
+// file seed's record, so one there is not a record this door knows how to
+// own, and it is answered like any other caller's.
+//
+// Any failure is false, which every caller answers with the byte-identical
+// http.NotFound before anything about the record is revealed. It answers
+// the record and the caller's box label.
+func (s *Server) fleetSeedRecord(r *http.Request) (*provision.Record, string, bool) {
+ account, app, host := r.PathValue("account"), r.PathValue("app"), r.PathValue("host")
+ if !release.ValidAccount(account) || !release.ValidApp(app) || !provision.ValidHostShape(host) {
+ return nil, "", false
+ }
+ name := r.Header.Get("Carlos-Tunnel-Name")
+ fleet, box, ok := strings.Cut(name, "/")
+ if !ok {
+ return nil, "", false
+ }
+ token, bearer := strings.CutPrefix(r.Header.Get("Authorization"), "Bearer ")
+ reg, err := openRegistry(s.cfg.Registry)
+ if err != nil || !bearer || !fleetIdentityOK(reg, name, token, fleet, account) {
+ return nil, "", false
+ }
+ rec, _, err := s.readRecord(r.Context(), account, app, host)
+ if err != nil || rec == nil || rec.Retired || rec.Region != registry.PlacementTarget(fleet) {
+ return nil, "", false
+ }
+ if rec.Seed == nil || rec.Seed.Kind != seeds.KindFile || rec.ReplicaAssignment != nil {
+ return nil, "", false
+ }
+ switch rec.FleetBox {
+ case box:
+ case "":
+ sole, ok := soleActiveFleetBox(reg, fleet)
+ if !ok || sole.Box != box {
+ return nil, "", false
+ }
+ default:
+ return nil, "", false
+ }
+ return rec, box, true
+}
+
+// fleetSeedReport is the door's body. code is only for failed; held only
+// with code copy-in-storage. replicaPayload decodes it: unknown fields
+// refused, one document, at most 8 KiB.
+type fleetSeedReport struct {
+ ID string `json:"id"`
+ Code string `json:"code,omitempty"`
+ Held string `json:"held,omitempty"`
+}
+
+// fleetSeedReason maps a failed report's code to the sentence the record
+// keeps (FS-27 to FS-30); ok is false for anything else.
+func fleetSeedReason(code string) (string, bool) {
+ switch code {
+ case provision.SeedCodeMismatch:
+ return fileSeedBoxMismatchCopy, true
+ case provision.SeedCodeNotADatabase:
+ return fileSeedBoxIntegrityCopy, true
+ case provision.SeedCodeCopyExists:
+ return fileSeedCopyExistsCopy, true
+ case provision.SeedCodeCopyInStorage:
+ return fileSeedCopyInStorageCopy, true
+ }
+ return "", false
+}
+
+// failedReason is the reason a failed report leaves on seed, and ok false
+// for a report the record refuses (409, nothing written). On a seed that is
+// not yet aborted, the code's own sentence (FS-27 to FS-30). On an
+// already-aborted one only copy-in-storage lands (decision D6; review
+// rounds 1 and 2), from the rollback that found a copy, whatever the
+// abort's reason: it records where the copy is held, which the delete
+// door's sentence keys on, and it keeps the reason the seed already has
+// (a console's FS-17 or an upload's failure, a box's earlier code),
+// setting FS-30 only over none. So a later report never overwrites why
+// the seed was abandoned, and never loses where its copy is. Any other
+// code on an aborted seed is refused, so nothing clears Held or FS-30.
+func failedReason(seed *provision.SeedSource, code string) (string, bool) {
+ reason, _ := fleetSeedReason(code)
+ if seed == nil || seed.State != seeds.StateAborted {
+ return reason, true
+ }
+ if code != provision.SeedCodeCopyInStorage {
+ return "", false
+ }
+ if seed.Reason != "" {
+ return seed.Reason, true
+ }
+ return reason, true
+}
+
+// fleetSeedReportValid is the body's grammar for op (plan Task 15): a seed
+// id that passes seeds.Check; for failed, a known code, with held exactly
+// when the code is copy-in-storage and then one of the three places; for
+// placed and rolledback, neither.
+func fleetSeedReportValid(op, host string, b fleetSeedReport) bool {
+ if seeds.Check(host, b.ID) != nil {
+ return false
+ }
+ if op != provision.FleetSeedFailed {
+ return b.Code == "" && b.Held == ""
+ }
+ if _, ok := fleetSeedReason(b.Code); !ok {
+ return false
+ }
+ if b.Code != provision.SeedCodeCopyInStorage {
+ return b.Held == ""
+ }
+ switch b.Held {
+ case provision.SeedHeldReplica, provision.SeedHeldStaging, provision.SeedHeldBoth:
+ return true
+ }
+ return false
+}
+
+func (s *Server) handleFleetSeedPlaced(w http.ResponseWriter, r *http.Request) {
+ s.fleetSeedDoor(w, r, provision.FleetSeedPlaced)
+}
+
+func (s *Server) handleFleetSeedFailed(w http.ResponseWriter, r *http.Request) {
+ s.fleetSeedDoor(w, r, provision.FleetSeedFailed)
+}
+
+func (s *Server) handleFleetSeedRolledBack(w http.ResponseWriter, r *http.Request) {
+ s.fleetSeedDoor(w, r, provision.FleetSeedRolledBack)
+}
+
+// fleetSeedDoor is the three handlers' one body. The answers carry no text
+// a box could show anyone: 200 done (or already done), 400 a body outside
+// the grammar, 404 not this caller's, 409 the record says otherwise, 502
+// the write failed. The box needs only the status (seedfleetdoor.go).
+func (s *Server) fleetSeedDoor(w http.ResponseWriter, r *http.Request, op string) {
+ if _, _, ok := s.fleetSeedRecord(r); !ok {
+ http.NotFound(w, r)
+ return
+ }
+ // A claim console admits no seed (seedFleetReady refuses it first, plan
+ // R3-1), and neither sweeps nor finishes one, so it records no seed's
+ // transition either: the claim sentence, after the owner gate so any
+ // other caller still gets the identical 404, and before anything is
+ // read or written.
+ if s.cfg.HostClaim {
+ ref := seedClaimConsoleRefusal()
+ jsonError(w, ref.Status, ref.Msg)
+ return
+ }
+ var body fleetSeedReport
+ if !replicaPayload(r, &body) || !fleetSeedReportValid(op, r.PathValue("host"), body) {
+ http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
+ return
+ }
+ acct, app, host := r.PathValue("account"), r.PathValue("app"), r.PathValue("host")
+ unauthorized, changed := false, false
+ err := s.withRecordLock(acct, app, func() error {
+ // Ownership again, under the lock: the record and the fleet's
+ // boxes may have moved since the first look.
+ rec, _, ok := s.fleetSeedRecord(r)
+ if !ok {
+ unauthorized = true
+ return nil
+ }
+ var err error
+ changed, err = s.fleetSeedTransition(r.Context(), rec, op, body)
+ return err
+ })
+ switch {
+ case unauthorized:
+ http.NotFound(w, r)
+ return
+ case errors.Is(err, provision.ErrSeedConflict), errors.Is(err, os.ErrNotExist):
+ http.Error(w, http.StatusText(http.StatusConflict), http.StatusConflict)
+ return
+ case err != nil:
+ log.Printf("console: fleet seeds door: %s/%s/%s: seed %s %s: %v", acct, app, host, body.ID, op, err)
+ http.Error(w, http.StatusText(http.StatusBadGateway), http.StatusBadGateway)
+ return
+ }
+ if changed {
+ log.Printf("console: fleet seeds door: %s/%s/%s: seed %s %s", acct, app, host, body.ID, op)
+ }
+ if op == provision.FleetSeedRolledBack {
+ // After the record lock is released (plan R1-2): withRecordLock
+ // holds the app lock, and with lifetimes on the finish retires the
+ // record through withAppHost, which takes the same non-reentrant
+ // mutex. finishSeed checks the seed id and state itself, and its
+ // CAS protects the record; a finish that fails is the seeds sweep's
+ // to retry, and the transition the box reported stands. The finish
+ // deletes the seed's fleet snapshot too (finishSeedOnce): one place
+ // owns that delete.
+ //
+ // Overlapping finishes are safe (review P3-3). The finish runs in
+ // the request, and a store teardown can take storeTeardownTimeout
+ // (60s) while the box's client and the hub give up at 30s. The
+ // box's retry then finds the record rolled-back: the transition is
+ // a no-op, and a second finishSeed runs beside the first (or beside
+ // the sweep's). Every finish step is idempotent, the store teardown
+ // is under its walk lock, and the record goes only by a CAS on the
+ // etag of a read that saw this seed rolled-back, so the second
+ // either finds work done or loses that CAS and stops.
+ if err := s.finishSeed(context.WithoutCancel(r.Context()), acct, app, host, body.ID); err != nil {
+ log.Printf("console: fleet seeds door: %s/%s/%s: finish seed %s: %v (the seeds sweep retries)", acct, app, host, body.ID, err)
+ }
+ }
+ w.WriteHeader(http.StatusOK)
+}
+
+// fleetSeedTransition applies op to rec's seed under the record lock, and
+// answers whether it changed the record. Only the record's own seed id is
+// acted on. A record already where op would put it (the box's answer was
+// lost, or a held copy is re-reported every pass) is a no-op: nothing is
+// written and the serial stays. Otherwise the record CAS decides
+// (provision.ErrSeedConflict when its seed is not in a state op starts
+// from), and a write that lands bumps the serial.
+func (s *Server) fleetSeedTransition(ctx context.Context, rec *provision.Record, op string, b fleetSeedReport) (bool, error) {
+ seed := rec.Seed
+ if seed.ID != b.ID {
+ return false, provision.ErrSeedConflict
+ }
+ var mut func(*provision.Record) error
+ switch op {
+ case provision.FleetSeedPlaced:
+ if seed.State == seeds.StatePlaced {
+ return false, nil
+ }
+ mut = provision.SeedPlace(b.ID)
+ case provision.FleetSeedFailed:
+ // A report the record already says (the same code again, or a held
+ // copy re-reported every pass) is a no-op.
+ if mapped, _ := fleetSeedReason(b.Code); seed.State == seeds.StateAborted && seed.Held == b.Held &&
+ (seed.Reason == mapped || b.Code == provision.SeedCodeCopyInStorage && seed.Reason != "") {
+ return false, nil
+ }
+ mut = func(cur *provision.Record) error {
+ reason, ok := failedReason(cur.Seed, b.Code)
+ if !ok {
+ return provision.ErrSeedConflict
+ }
+ return provision.SeedFail(b.ID, reason, b.Held)(cur)
+ }
+ case provision.FleetSeedRolledBack:
+ if seed.State == seeds.StateRolledBack {
+ return false, nil
+ }
+ mut = provision.SeedRolledBack(b.ID)
+ default:
+ return false, provision.ErrSeedConflict
+ }
+ // The CAS is bound to the ownership the caller was checked against
+ // under the lock: a record that moved fleet or box, or retired, since
+ // that read is refused like any other record that says otherwise.
+ region, box := rec.Region, rec.FleetBox
+ owned := func(cur *provision.Record) error {
+ if cur.Retired || cur.Region != region || cur.FleetBox != box {
+ return provision.ErrSeedConflict
+ }
+ return mut(cur)
+ }
+ if _, err := provision.SetRecordSeed(ctx, s.cfg.Releases, rec.Account, rec.App, rec.Host, owned); err != nil {
+ return false, err
+ }
+ if op == provision.FleetSeedPlaced {
+ // Placed, the seed's snapshot is spent. Absent is fine; a delete
+ // that fails is the seeds sweep's to retry, which deletes a placed
+ // seed's snapshot. A rolled-back seed's goes with its finish.
+ key := seeds.FleetSnapshotKey(rec.Account, rec.App, rec.Host, b.ID)
+ if err := s.cfg.Releases.Delete(ctx, key); err != nil && !errors.Is(err, os.ErrNotExist) {
+ log.Printf("console: fleet seeds door: %s: delete the snapshot of seed %s: %v (the seeds sweep retries)", rec.Host, b.ID, err)
+ }
+ }
+ s.bumpSerial(ctx)
+ return true, nil
+}
diff --git a/internal/console/apifleetseeds_test.go b/internal/console/apifleetseeds_test.go
new file mode 100644
index 000000000..f663bc3e8
--- /dev/null
+++ b/internal/console/apifleetseeds_test.go
@@ -0,0 +1,666 @@
+package console
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "net/http"
+ "os"
+ "strings"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/provision"
+ "github.com/carlosframework/platform/internal/release"
+ "github.com/carlosframework/platform/internal/replicas"
+ "github.com/carlosframework/platform/internal/seeds"
+)
+
+// The fleet seeds door (plan Task 15): a customer-fleet box reports its
+// file seed's placed, failed and rolledback here, because it cannot write
+// records itself.
+
+const fsHost = "seeded.shop.example.com"
+
+// fleetSeedFx is the interactive world's fleets (home: b1 active, b2
+// detached; away: a1), with no data bucket (a fleet file seed's finish
+// needs none, review P3-2), and lifetimes on or off.
+type fleetSeedFx struct {
+ fx *interactiveFx
+ b1, b2, a1 string
+ on bool
+}
+
+func newFleetSeedFx(t *testing.T, lifetimesOn bool) fleetSeedFx {
+ t.Helper()
+ clock := useLifetimesClock(t)
+ fx := newIxFx(t, "code-fleet-seeds")
+ b1, b2, a1 := ixFleetWorld(t, fx, fx.acct)
+ fx.srv.cfg.SeedData = nil
+ if lifetimesOn {
+ turnLifetimesOn(t, fx.srv, clock)
+ }
+ return fleetSeedFx{fx: fx, b1: b1, b2: b2, a1: a1, on: lifetimesOn}
+}
+
+// ctx is a record context as a request admitted now has it.
+func (f fleetSeedFx) ctx(t *testing.T) context.Context {
+ t.Helper()
+ if f.on {
+ return onCtx(t, f.fx.srv)
+ }
+ return context.Background()
+}
+
+// seed creates host's record through the seed doors' own create, on region,
+// with a seed of kind in state, labelled box ("" for none), and puts its
+// fleet snapshot. It answers the seed id.
+func (f fleetSeedFx) seed(t *testing.T, host, region, box, kind, state string) string {
+ t.Helper()
+ id := newSeedID(t)
+ now := time.Now().UTC()
+ rec := provision.Record{Schema: 1, Host: host, Slug: strings.SplitN(host, ".", 2)[0], App: "shop", Account: f.fx.acct,
+ Channel: "stable", Region: region, FleetBox: box, CreatedAt: now,
+ Seed: &provision.SeedSource{ID: id, Kind: kind, State: state, SHA256: strings.Repeat("a", 64), Bytes: 4,
+ By: "alice@keymail.dev", At: now}}
+ life, err := f.fx.st.AppLife(f.fx.acctID, "shop")
+ if err != nil || life == nil {
+ t.Fatalf("app life: %v %v", life, err)
+ }
+ ctx := f.ctx(t)
+ if err := f.fx.srv.createSeedRecord(ctx, seedCreate{lifetime: life.Lifetime}, rec); err != nil {
+ t.Fatal(err)
+ }
+ f.putSnapshot(t, host, id)
+ return id
+}
+
+func (f fleetSeedFx) putSnapshot(t *testing.T, host, id string) {
+ t.Helper()
+ if _, err := f.fx.rel.Put(context.Background(), seeds.FleetSnapshotKey(f.fx.acct, "shop", host, id), []byte("snap"), ""); err != nil {
+ t.Fatal(err)
+ }
+}
+
+// serial is the serial object's etag: it moves with every bump.
+func (f fleetSeedFx) serial(t *testing.T) string {
+ t.Helper()
+ _, etag, err := f.fx.rel.Get(context.Background(), release.SerialKey)
+ if err != nil && !errors.Is(err, os.ErrNotExist) {
+ t.Fatal(err)
+ }
+ return etag
+}
+
+func (f fleetSeedFx) hasSnapshot(t *testing.T, host, id string) bool {
+ t.Helper()
+ _, _, err := f.fx.rel.Get(context.Background(), seeds.FleetSnapshotKey(f.fx.acct, "shop", host, id))
+ if err != nil && !errors.Is(err, os.ErrNotExist) {
+ t.Fatal(err)
+ }
+ return err == nil
+}
+
+// raw is host's record bytes, nil when there is none.
+func (f fleetSeedFx) raw(t *testing.T, host string) []byte {
+ t.Helper()
+ raw, _, err := f.fx.rel.Get(context.Background(), provision.RecordKey(f.fx.acct, "shop", host))
+ if errors.Is(err, os.ErrNotExist) {
+ return nil
+ }
+ if err != nil {
+ t.Fatal(err)
+ }
+ return raw
+}
+
+func (f fleetSeedFx) record(t *testing.T, host string) *provision.Record {
+ t.Helper()
+ rec, _, err := f.fx.srv.readRecord(f.ctx(t), f.fx.acct, "shop", host)
+ if errors.Is(err, os.ErrNotExist) {
+ return nil
+ }
+ if err != nil {
+ t.Fatal(err)
+ }
+ return rec
+}
+
+// post calls the door as the box name with token, bounded so a deadlock
+// fails the test instead of hanging it.
+func (f fleetSeedFx) post(t *testing.T, host, op, name, token string, body any) (int, []byte) {
+ t.Helper()
+ return f.postPath(t, "/api/fleet/seeds/"+f.fx.acct+"/shop/"+host+"/"+op, name, token, body)
+}
+
+func (f fleetSeedFx) postPath(t *testing.T, path, name, token string, body any) (int, []byte) {
+ t.Helper()
+ raw, err := json.Marshal(body)
+ if err != nil {
+ t.Fatal(err)
+ }
+ req, err := http.NewRequest(http.MethodPost, f.fx.ts.URL+path, bytes.NewReader(raw))
+ if err != nil {
+ t.Fatal(err)
+ }
+ req.Header.Set("Authorization", "Bearer "+token)
+ req.Header.Set("Carlos-Tunnel-Name", name)
+ res, err := (&http.Client{Timeout: 30 * time.Second}).Do(req)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer res.Body.Close()
+ out, err := io.ReadAll(res.Body)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return res.StatusCode, out
+}
+
+type fsBody map[string]string
+
+// opBody is a well-formed body for op.
+func opBody(op, id string) fsBody {
+ if op == provision.FleetSeedFailed {
+ return fsBody{"id": id, "code": provision.SeedCodeMismatch}
+ }
+ return fsBody{"id": id}
+}
+
+var fleetSeedOps = []string{provision.FleetSeedPlaced, provision.FleetSeedFailed, provision.FleetSeedRolledBack}
+
+func TestFleetSeedDoorRefusals(t *testing.T) {
+ f := newFleetSeedFx(t, false)
+ id := f.seed(t, fsHost, "fleet/home", "", seeds.KindFile, seeds.StateReady)
+ region := f.seed(t, "region.shop.example.com", "uk", "", seeds.KindFile, seeds.StateReady)
+ imp := f.seed(t, "imported.shop.example.com", "fleet/home", "", seeds.KindImport, seeds.StateReady)
+ from := f.seed(t, "copied.shop.example.com", "fleet/home", "", seeds.KindReplica, seeds.StateReady)
+ notFound := func(t *testing.T, what, path, name, token string, body fsBody, host string) {
+ t.Helper()
+ before := f.raw(t, host)
+ code, raw := f.postPath(t, path, name, token, body)
+ if code != http.StatusNotFound || string(raw) != "404 page not found\n" {
+ t.Errorf("%s: %d %q, want the identical 404", what, code, raw)
+ }
+ if after := f.raw(t, host); !bytes.Equal(before, after) {
+ t.Errorf("%s: the record changed:\n%s\n%s", what, before, after)
+ }
+ }
+ base := func(host string) string { return "/api/fleet/seeds/" + f.fx.acct + "/shop/" + host + "/" }
+ for _, op := range fleetSeedOps {
+ for _, c := range []struct {
+ what, host, id, name, token string
+ path string
+ }{
+ {"another fleet's box", fsHost, id, "away/a1", f.a1, ""},
+ {"another fleet's token", fsHost, id, "home/b1", f.a1, ""},
+ {"a detached box", fsHost, id, "home/b2", f.b2, ""},
+ {"no bearer", fsHost, id, "home/b1", "", ""},
+ {"a region record", "region.shop.example.com", region, "home/b1", f.b1, ""},
+ {"an import seed", "imported.shop.example.com", imp, "home/b1", f.b1, ""},
+ {"a --from seed", "copied.shop.example.com", from, "home/b1", f.b1, ""},
+ {"a malformed host", fsHost, id, "home/b1", f.b1, base("bad!host") + op},
+ {"another account", fsHost, id, "home/b1", f.b1, strings.Replace(base(fsHost), f.fx.acct, "baj", 1) + op},
+ {"no record", "absent.shop.example.com", id, "home/b1", f.b1, ""},
+ } {
+ path := c.path
+ if path == "" {
+ path = base(c.host) + op
+ }
+ notFound(t, op+": "+c.what, path, c.name, c.token, opBody(op, c.id), c.host)
+ }
+ }
+
+ // Ownership: a labelled record answers only its box, and an unlabelled
+ // one only the fleet's sole active box.
+ reg, err := openRegistry(f.fx.regPath)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := reg.SetFleetBoxStatus("home", "b2", "active"); err != nil {
+ t.Fatal(err)
+ }
+ onB1 := f.seed(t, "one.shop.example.com", "fleet/home", "b1", seeds.KindFile, seeds.StateReady)
+ onB2 := f.seed(t, "two.shop.example.com", "fleet/home", "b2", seeds.KindFile, seeds.StateReady)
+ for _, op := range fleetSeedOps {
+ notFound(t, op+": another box", base("one.shop.example.com")+op, "home/b2", f.b2, opBody(op, onB1), "one.shop.example.com")
+ notFound(t, op+": a record labelled for another box", base("two.shop.example.com")+op, "home/b1", f.b1, opBody(op, onB2), "two.shop.example.com")
+ notFound(t, op+": unlabelled, two active boxes", base(fsHost)+op, "home/b1", f.b1, opBody(op, id), fsHost)
+ }
+ if err := reg.SetFleetBoxStatus("home", "b2", "detached"); err != nil {
+ t.Fatal(err)
+ }
+
+ // A stale seed id is the owner's, so it is told: 409, nothing changed.
+ stale := newSeedID(t)
+ for _, op := range fleetSeedOps {
+ before := f.raw(t, fsHost)
+ if code, raw := f.post(t, fsHost, op, "home/b1", f.b1, opBody(op, stale)); code != http.StatusConflict {
+ t.Errorf("%s with a stale id: %d %s, want 409", op, code, raw)
+ }
+ if !bytes.Equal(before, f.raw(t, fsHost)) {
+ t.Errorf("%s with a stale id changed the record", op)
+ }
+ }
+ if !f.hasSnapshot(t, fsHost, id) {
+ t.Fatal("a refused call deleted the snapshot")
+ }
+}
+
+func TestFleetSeedDoorPlacedDeletesSnapshotOnce(t *testing.T) {
+ f := newFleetSeedFx(t, false)
+ id := f.seed(t, fsHost, "fleet/home", "", seeds.KindFile, seeds.StateReady)
+ serial := f.serial(t)
+ if code, raw := f.post(t, fsHost, "placed", "home/b1", f.b1, fsBody{"id": id}); code != http.StatusOK {
+ t.Fatalf("placed: %d %s", code, raw)
+ }
+ if rec := f.record(t, fsHost); rec.Seed.State != seeds.StatePlaced {
+ t.Fatalf("seed %+v, want placed", rec.Seed)
+ }
+ if f.hasSnapshot(t, fsHost, id) {
+ t.Fatal("the snapshot of a placed seed is still there")
+ }
+ if f.serial(t) == serial {
+ t.Fatal("placed did not bump the serial")
+ }
+ // A repeat (the box's answer was lost) is a no-op: the record, the
+ // serial and anything at the snapshot's key stay as they are.
+ f.putSnapshot(t, fsHost, id)
+ before, serial := f.raw(t, fsHost), f.serial(t)
+ if code, raw := f.post(t, fsHost, "placed", "home/b1", f.b1, fsBody{"id": id}); code != http.StatusOK {
+ t.Fatalf("placed again: %d %s", code, raw)
+ }
+ if !bytes.Equal(before, f.raw(t, fsHost)) || !f.hasSnapshot(t, fsHost, id) || f.serial(t) != serial {
+ t.Fatal("a repeated placed changed something")
+ }
+ // A labelled record answers its own box the same way.
+ labelled := f.seed(t, "one.shop.example.com", "fleet/home", "b1", seeds.KindFile, seeds.StateReady)
+ if code, raw := f.post(t, "one.shop.example.com", "placed", "home/b1", f.b1, fsBody{"id": labelled}); code != http.StatusOK {
+ t.Fatalf("placed, labelled: %d %s", code, raw)
+ }
+ // placed from aborted is the record saying otherwise.
+ aborted := f.seed(t, "two.shop.example.com", "fleet/home", "", seeds.KindFile, seeds.StateAborted)
+ before = f.raw(t, "two.shop.example.com")
+ if code, _ := f.post(t, "two.shop.example.com", "placed", "home/b1", f.b1, fsBody{"id": aborted}); code != http.StatusConflict {
+ t.Fatalf("placed from aborted: %d, want 409", code)
+ }
+ if !bytes.Equal(before, f.raw(t, "two.shop.example.com")) || !f.hasSnapshot(t, "two.shop.example.com", aborted) {
+ t.Fatal("a refused placed changed something")
+ }
+}
+
+func TestFleetSeedDoorFailedMapsCodes(t *testing.T) {
+ f := newFleetSeedFx(t, false)
+ n := 0
+ fresh := func(t *testing.T, state string) (string, string) {
+ t.Helper()
+ n++
+ host := "s" + string(rune('a'+n)) + ".shop.example.com"
+ return host, f.seed(t, host, "fleet/home", "", seeds.KindFile, state)
+ }
+ for _, c := range []struct{ code, held, reason string }{
+ {provision.SeedCodeMismatch, "", "the seed file on the box did not match the upload"},
+ {provision.SeedCodeNotADatabase, "", "the seed file on the box failed its integrity check"},
+ {provision.SeedCodeCopyExists, "", "a copy of data already exists for this hostname"},
+ {provision.SeedCodeCopyInStorage, provision.SeedHeldReplica, "a copy of its data is still in the fleet’s storage"},
+ {provision.SeedCodeCopyInStorage, provision.SeedHeldStaging, "a copy of its data is still in the fleet’s storage"},
+ {provision.SeedCodeCopyInStorage, provision.SeedHeldBoth, "a copy of its data is still in the fleet’s storage"},
+ } {
+ host, id := fresh(t, seeds.StateReady)
+ body := fsBody{"id": id, "code": c.code}
+ if c.held != "" {
+ body["held"] = c.held
+ }
+ if code, raw := f.post(t, host, "failed", "home/b1", f.b1, body); code != http.StatusOK {
+ t.Fatalf("%s %s: %d %s", c.code, c.held, code, raw)
+ }
+ rec := f.record(t, host)
+ if rec.Seed.State != seeds.StateAborted || rec.Seed.Reason != c.reason || rec.Seed.Held != c.held {
+ t.Errorf("%s %s: seed %+v", c.code, c.held, rec.Seed)
+ }
+ }
+
+ // The rollback's re-report while a copy is held: an aborted seed takes
+ // the reason and held; the same report again writes nothing.
+ host, id := fresh(t, seeds.StateAborted)
+ held := fsBody{"id": id, "code": provision.SeedCodeCopyInStorage, "held": provision.SeedHeldBoth}
+ if code, raw := f.post(t, host, "failed", "home/b1", f.b1, held); code != http.StatusOK {
+ t.Fatalf("copy-in-storage on aborted: %d %s", code, raw)
+ }
+ if rec := f.record(t, host); rec.Seed.State != seeds.StateAborted || rec.Seed.Held != provision.SeedHeldBoth {
+ t.Fatalf("seed %+v", rec.Seed)
+ }
+ before, serial := f.raw(t, host), f.serial(t)
+ if code, raw := f.post(t, host, "failed", "home/b1", f.b1, held); code != http.StatusOK {
+ t.Fatalf("the same report again: %d %s", code, raw)
+ }
+ if !bytes.Equal(before, f.raw(t, host)) || f.serial(t) != serial {
+ t.Fatal("a repeated copy-in-storage report wrote something")
+ }
+ // A different place is recorded.
+ held["held"] = provision.SeedHeldReplica
+ if code, raw := f.post(t, host, "failed", "home/b1", f.b1, held); code != http.StatusOK {
+ t.Fatalf("copy-in-storage, replica: %d %s", code, raw)
+ }
+ if rec := f.record(t, host); rec.Seed.Held != provision.SeedHeldReplica {
+ t.Fatalf("seed %+v, want held replica", rec.Seed)
+ }
+
+ // Outside the door's vocabulary: 400, nothing changed.
+ host, id = fresh(t, seeds.StateReady)
+ for _, c := range []struct {
+ what, op string
+ body any
+ }{
+ {"an unknown code", "failed", fsBody{"id": id, "code": "melted"}},
+ {"no code", "failed", fsBody{"id": id}},
+ {"copy-in-storage without held", "failed", fsBody{"id": id, "code": provision.SeedCodeCopyInStorage}},
+ {"copy-in-storage held elsewhere", "failed", fsBody{"id": id, "code": provision.SeedCodeCopyInStorage, "held": "elsewhere"}},
+ {"held with mismatch", "failed", fsBody{"id": id, "code": provision.SeedCodeMismatch, "held": provision.SeedHeldReplica}},
+ {"held on placed", "placed", fsBody{"id": id, "held": provision.SeedHeldReplica}},
+ {"held on rolledback", "rolledback", fsBody{"id": id, "held": provision.SeedHeldReplica}},
+ {"a code on placed", "placed", fsBody{"id": id, "code": provision.SeedCodeMismatch}},
+ {"a code on rolledback", "rolledback", fsBody{"id": id, "code": provision.SeedCodeMismatch}},
+ {"text from the box", "failed", fsBody{"id": id, "code": provision.SeedCodeMismatch, "reason": "it broke"}},
+ {"a malformed id", "failed", fsBody{"id": "../x", "code": provision.SeedCodeMismatch}},
+ {"not an object", "failed", "failed"},
+ {"two documents", "failed", nil},
+ } {
+ before := f.raw(t, host)
+ var code int
+ var raw []byte
+ if c.body == nil {
+ code, raw = f.postRaw(t, host, c.op, `{"id":"`+id+`","code":"mismatch"}{}`)
+ } else {
+ code, raw = f.post(t, host, c.op, "home/b1", f.b1, c.body)
+ }
+ if code != http.StatusBadRequest {
+ t.Errorf("%s: %d %s, want 400", c.what, code, raw)
+ }
+ if !bytes.Equal(before, f.raw(t, host)) {
+ t.Errorf("%s: the record changed", c.what)
+ }
+ }
+}
+
+// postRaw sends body verbatim as home/b1.
+func (f fleetSeedFx) postRaw(t *testing.T, host, op, body string) (int, []byte) {
+ t.Helper()
+ req, err := http.NewRequest(http.MethodPost, f.fx.ts.URL+"/api/fleet/seeds/"+f.fx.acct+"/shop/"+host+"/"+op, strings.NewReader(body))
+ if err != nil {
+ t.Fatal(err)
+ }
+ req.Header.Set("Authorization", "Bearer "+f.b1)
+ req.Header.Set("Carlos-Tunnel-Name", "home/b1")
+ res, err := (&http.Client{Timeout: 30 * time.Second}).Do(req)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer res.Body.Close()
+ out, _ := io.ReadAll(res.Body)
+ return res.StatusCode, out
+}
+
+func TestFleetSeedDoorRolledBackFinishes(t *testing.T) {
+ for _, on := range []bool{false, true} {
+ name := "lifetimes off"
+ if on {
+ name = "lifetimes on"
+ }
+ t.Run(name, func(t *testing.T) {
+ f := newFleetSeedFx(t, on)
+ id := f.seed(t, fsHost, "fleet/home", "", seeds.KindFile, seeds.StateAborted)
+ if code, raw := f.post(t, fsHost, "rolledback", "home/b1", f.b1, fsBody{"id": id}); code != http.StatusOK {
+ t.Fatalf("rolledback: %d %s", code, raw)
+ }
+ if raw := f.raw(t, fsHost); raw != nil {
+ t.Fatalf("the record is still there: %s", raw)
+ }
+ if f.hasSnapshot(t, fsHost, id) {
+ t.Fatal("the snapshot is still there")
+ }
+ // The hostname is free: it can be created again.
+ again := f.seed(t, fsHost, "fleet/home", "", seeds.KindFile, seeds.StateReady)
+ if rec := f.record(t, fsHost); rec == nil || rec.Seed.ID != again {
+ t.Fatalf("the hostname was not created again: %+v", rec)
+ }
+ // The app's lock was released: a second mutation does not block.
+ done := make(chan error, 1)
+ go func() {
+ done <- f.fx.srv.withRecordLock(f.fx.acct, "shop", func() error { return nil })
+ }()
+ select {
+ case err := <-done:
+ if err != nil {
+ t.Fatal(err)
+ }
+ case <-time.After(10 * time.Second):
+ t.Fatal("the app lock is still held after the door answered")
+ }
+ // The door answers only for the record's own seed: the old id
+ // is now stale against the new record.
+ before := f.raw(t, fsHost)
+ if code, _ := f.post(t, fsHost, "rolledback", "home/b1", f.b1, fsBody{"id": id}); code != http.StatusConflict {
+ t.Fatalf("rolledback with the finished seed's id: %d, want 409", code)
+ }
+ if !bytes.Equal(before, f.raw(t, fsHost)) {
+ t.Fatal("the new record changed")
+ }
+ })
+ }
+}
+
+func TestFleetSeedDoorRolledBackOnlyFromAborted(t *testing.T) {
+ f := newFleetSeedFx(t, false)
+ for _, state := range []string{seeds.StateReserving, seeds.StateReady, seeds.StatePlaced} {
+ host := state + ".shop.example.com"
+ id := f.seed(t, host, "fleet/home", "", seeds.KindFile, state)
+ before := f.raw(t, host)
+ if code, raw := f.post(t, host, "rolledback", "home/b1", f.b1, fsBody{"id": id}); code != http.StatusConflict {
+ t.Errorf("rolledback from %s: %d %s, want 409", state, code, raw)
+ }
+ if !bytes.Equal(before, f.raw(t, host)) || !f.hasSnapshot(t, host, id) {
+ t.Errorf("rolledback from %s changed something", state)
+ }
+ }
+}
+
+// ---- review fixes ---------------------------------------------------------
+
+// P2-1: ownership is checked again under the record lock, and the CAS is
+// bound to it. reads counts Gets of the record's key: the first is the
+// door's look before the lock, the second its look under it, the third
+// the CAS's own read.
+func TestFleetSeedDoorRechecksOwnershipUnderLock(t *testing.T) {
+ for _, c := range []struct {
+ name string
+ at int32
+ code int
+ }{
+ {"a second active box before the locked look", 2, http.StatusNotFound},
+ {"relabelled before the CAS", 3, http.StatusConflict},
+ } {
+ t.Run(c.name, func(t *testing.T) {
+ f := newFleetSeedFx(t, false)
+ id := f.seed(t, fsHost, "fleet/home", "", seeds.KindFile, seeds.StateReady)
+ before := f.raw(t, fsHost)
+ ds := f.fx.rel.(*deletableStore)
+ key := provision.RecordKey(f.fx.acct, "shop", fsHost)
+ reg, err := openRegistry(f.fx.regPath)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var reads atomic.Int32
+ var after []byte
+ ds.setGetHook(func(ctx context.Context, k string) error {
+ if k != key || reads.Add(1) != c.at {
+ return nil
+ }
+ if c.at == 2 {
+ return reg.SetFleetBoxStatus("home", "b2", "active")
+ }
+ raw, etag, err := ds.Store.Get(ctx, key)
+ if err != nil {
+ return err
+ }
+ var rec provision.Record
+ if err := json.Unmarshal(raw, &rec); err != nil {
+ return err
+ }
+ rec.FleetBox = "b2"
+ if after, err = json.Marshal(rec); err != nil {
+ return err
+ }
+ _, err = ds.Store.Put(ctx, key, after, etag)
+ return err
+ })
+ t.Cleanup(func() { ds.setGetHook(nil) })
+ code, raw := f.post(t, fsHost, "placed", "home/b1", f.b1, fsBody{"id": id})
+ ds.setGetHook(nil)
+ if code != c.code || reads.Load() < c.at {
+ t.Fatalf("%d %q after %d reads, want %d", code, raw, reads.Load(), c.code)
+ }
+ if c.code == http.StatusNotFound && string(raw) != "404 page not found\n" {
+ t.Fatalf("404 body %q", raw)
+ }
+ want := before
+ if after != nil {
+ want = after
+ }
+ if got := f.raw(t, fsHost); !bytes.Equal(got, want) {
+ t.Fatalf("the record changed:\n%s\n%s", want, got)
+ }
+ if !f.hasSnapshot(t, fsHost, id) {
+ t.Fatal("a refused placed deleted the snapshot")
+ }
+ })
+ }
+}
+
+// P3-1 and round 2's P2-B: an aborted seed takes only copy-in-storage,
+// over any reason. It records where the copy is held and keeps the reason
+// the seed has (FS-30 only over none). Any other code is 409, nothing
+// written, so nothing clears Held or FS-30.
+func TestFleetSeedDoorFailedOnAbortedOnlyRefreshesStorage(t *testing.T) {
+ f := newFleetSeedFx(t, false)
+ n := 0
+ aborted := func(t *testing.T, reason, held string) (string, string) {
+ t.Helper()
+ n++
+ host := "ab" + string(rune('a'+n)) + ".shop.example.com"
+ id := f.seed(t, host, "fleet/home", "", seeds.KindFile, seeds.StateReady)
+ if _, err := provision.SetRecordSeed(context.Background(), f.fx.rel, f.fx.acct, "shop", host, provision.SeedFail(id, reason, held)); err != nil {
+ t.Fatal(err)
+ }
+ return host, id
+ }
+ storage := func(held string) func(string) fsBody {
+ return func(id string) fsBody { return fsBody{"id": id, "code": provision.SeedCodeCopyInStorage, "held": held} }
+ }
+ code := func(c string) func(string) fsBody {
+ return func(id string) fsBody { return fsBody{"id": id, "code": c} }
+ }
+ for _, c := range []struct {
+ what, reason, held string
+ body func(id string) fsBody
+ code int
+ wantReason, wantHeld string
+ unchanged bool
+ }{
+ {"copy-in-storage over a member's abort", "", "", storage(provision.SeedHeldBoth), http.StatusOK, fileSeedCopyInStorageCopy, provision.SeedHeldBoth, false},
+ {"copy-in-storage refreshes FS-30", fileSeedCopyInStorageCopy, provision.SeedHeldReplica, storage(provision.SeedHeldStaging), http.StatusOK, fileSeedCopyInStorageCopy, provision.SeedHeldStaging, false},
+ {"copy-in-storage over FS-17", fileSeedMismatchCopy, "", storage(provision.SeedHeldBoth), http.StatusOK, fileSeedMismatchCopy, provision.SeedHeldBoth, false},
+ {"copy-in-storage over an upload failure", importNotADB, "", storage(provision.SeedHeldReplica), http.StatusOK, importNotADB, provision.SeedHeldReplica, false},
+ {"copy-in-storage over a box's FS-29", fileSeedCopyExistsCopy, "", storage(provision.SeedHeldBoth), http.StatusOK, fileSeedCopyExistsCopy, provision.SeedHeldBoth, false},
+ {"the same copy-in-storage again over FS-17", fileSeedMismatchCopy, provision.SeedHeldBoth, storage(provision.SeedHeldBoth), http.StatusOK, fileSeedMismatchCopy, provision.SeedHeldBoth, true},
+ {"mismatch over FS-30", fileSeedCopyInStorageCopy, provision.SeedHeldReplica, code(provision.SeedCodeMismatch), http.StatusConflict, fileSeedCopyInStorageCopy, provision.SeedHeldReplica, true},
+ {"copy-exists over a member's abort", "", "", code(provision.SeedCodeCopyExists), http.StatusConflict, "", "", true},
+ {"mismatch over FS-17 with a held copy", fileSeedMismatchCopy, provision.SeedHeldReplica, code(provision.SeedCodeMismatch), http.StatusConflict, fileSeedMismatchCopy, provision.SeedHeldReplica, true},
+ {"the same mismatch again", fileSeedBoxMismatchCopy, "", code(provision.SeedCodeMismatch), http.StatusOK, fileSeedBoxMismatchCopy, "", true},
+ } {
+ host, id := aborted(t, c.reason, c.held)
+ before := f.raw(t, host)
+ got, raw := f.post(t, host, "failed", "home/b1", f.b1, c.body(id))
+ if got != c.code {
+ t.Errorf("%s: %d %s, want %d", c.what, got, raw, c.code)
+ continue
+ }
+ rec := f.record(t, host)
+ if rec.Seed.State != seeds.StateAborted || rec.Seed.Reason != c.wantReason || rec.Seed.Held != c.wantHeld {
+ t.Errorf("%s: seed %+v, want aborted with %q held %q", c.what, rec.Seed, c.wantReason, c.wantHeld)
+ }
+ if c.unchanged && !bytes.Equal(before, f.raw(t, host)) {
+ t.Errorf("%s: the record changed", c.what)
+ }
+ }
+}
+
+// Round 2 P2-B, both orders: wherever the console's reason and the box's
+// held copy come from first, the delete door names the location.
+func TestFleetSeedHeldLocationSurvivesEitherOrder(t *testing.T) {
+ f := newFleetSeedFx(t, false)
+ ctx := context.Background()
+ where := fmt.Sprintf(fileSeedHeldInStorageCopy, "%s", fmt.Sprintf(fileSeedHeldReplicaCopy, "%s"))
+ // The console aborts first (FS-17), then the box's rollback finds a copy.
+ first := "first.shop.example.com"
+ id := f.seed(t, first, "fleet/home", "", seeds.KindFile, seeds.StateReserving)
+ if _, err := provision.SetRecordSeed(ctx, f.fx.rel, f.fx.acct, "shop", first, provision.SeedAbortFileUploadBecause(id, fileSeedMismatchCopy)); err != nil {
+ t.Fatal(err)
+ }
+ if code, raw := f.post(t, first, "failed", "home/b1", f.b1, fsBody{"id": id, "code": provision.SeedCodeCopyInStorage, "held": provision.SeedHeldReplica}); code != http.StatusOK {
+ t.Fatalf("copy-in-storage after FS-17: %d %s", code, raw)
+ }
+ rec := f.record(t, first)
+ if rec.Seed.Reason != fileSeedMismatchCopy || rec.Seed.Held != provision.SeedHeldReplica {
+ t.Fatalf("after FS-17 then the copy: %+v", rec.Seed)
+ }
+ if got := fleetSeedHeldSentence(first, rec.Seed); got != fmt.Sprintf(where, first, first) {
+ t.Fatalf("FS-17 then the copy: %q", got)
+ }
+ // The box reports the copy first, from ready; a console write after it
+ // (a member's delete) aborts nothing more and changes neither.
+ second := "second.shop.example.com"
+ id = f.seed(t, second, "fleet/home", "", seeds.KindFile, seeds.StateReady)
+ if code, raw := f.post(t, second, "failed", "home/b1", f.b1, fsBody{"id": id, "code": provision.SeedCodeCopyInStorage, "held": provision.SeedHeldReplica}); code != http.StatusOK {
+ t.Fatalf("copy-in-storage from ready: %d %s", code, raw)
+ }
+ if _, err := provision.SetRecordSeed(ctx, f.fx.rel, f.fx.acct, "shop", second, provision.SeedAbortBecause(id, "")); err == nil {
+ t.Fatal("a second abort of an aborted seed landed")
+ }
+ rec = f.record(t, second)
+ if rec.Seed.Reason != fileSeedCopyInStorageCopy || rec.Seed.Held != provision.SeedHeldReplica {
+ t.Fatalf("after the copy then a console abort: %+v", rec.Seed)
+ }
+ if got := fleetSeedHeldSentence(second, rec.Seed); got != fmt.Sprintf(where, second, second) {
+ t.Fatalf("the copy then a console abort: %q", got)
+ }
+}
+
+// P3-4: a fleet file seed's record with a replica assignment is not the
+// door's to own: the identical 404, nothing changed.
+func TestFleetSeedDoorRefusesReplicaAssignment(t *testing.T) {
+ f := newFleetSeedFx(t, false)
+ id := newSeedID(t)
+ now := time.Now().UTC()
+ rec := provision.Record{Schema: 1, Host: fsHost, Slug: "seeded", App: "shop", Account: f.fx.acct, Channel: "stable",
+ Region: "fleet/home", CreatedAt: now, ReplicaAssignment: &replicas.Assignment{Revision: 1, Desired: 1, Boxes: []string{"b1"}},
+ Seed: &provision.SeedSource{ID: id, Kind: seeds.KindFile, State: seeds.StateReady, SHA256: strings.Repeat("a", 64), Bytes: 4,
+ By: "alice@keymail.dev", At: now}}
+ // Written raw: no create path writes this shape (TestFileSeedBeginFleet
+ // WritesDeploymentKey pins that), so only a hand-made record has it.
+ ixPutRecord(t, f.fx, rec)
+ before := f.raw(t, fsHost)
+ for _, op := range fleetSeedOps {
+ code, raw := f.post(t, fsHost, op, "home/b1", f.b1, opBody(op, id))
+ if code != http.StatusNotFound || string(raw) != "404 page not found\n" {
+ t.Errorf("%s: %d %q, want the identical 404", op, code, raw)
+ }
+ }
+ if !bytes.Equal(before, f.raw(t, fsHost)) {
+ t.Fatal("the record changed")
+ }
+}
diff --git a/internal/console/apiinstanceimport.go b/internal/console/apiinstanceimport.go
index d255946f4..1ebea710e 100644
--- a/internal/console/apiinstanceimport.go
+++ b/internal/console/apiinstanceimport.go
@@ -387,8 +387,12 @@ type importUpload struct {
app, host, by string
id string
kind string // the seed's: seeds.KindImport or seeds.KindFile
- dir, spool string
- release func()
+ // store and key are where the snapshot goes (seedSnapshotTarget),
+ // decided from the record before the hand-over.
+ store release.Store
+ key string
+ dir, spool string
+ release func()
// unit is the request's admitted unit, handed over before the
// goroutine starts: the job ends it after its last write
// (lifetimes_cutover.go).
@@ -487,8 +491,9 @@ func (s *Server) handleAPIImportUpload(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusAccepted, map[string]string{"state": "checking"})
handedOver = true
s.seedCopies.Add(1)
+ store, key := s.seedSnapshotTarget(rec)
go s.runImportUpload(&importUpload{ctx: context.WithoutCancel(ctx), acct: acct, app: app, host: host, by: principal,
- id: seed.ID, kind: seed.Kind, dir: dir, spool: spool, release: releaseScratch, unit: detachUnit(ctx)})
+ id: seed.ID, kind: seed.Kind, store: store, key: key, dir: dir, spool: spool, release: releaseScratch, unit: detachUnit(ctx)})
}
// readImportRecord reads host's record under instanceStoreTimeout.
@@ -666,7 +671,7 @@ func (s *Server) runImportUpload(j *importUpload) {
return
}
uctx, ucancel := context.WithTimeout(ctx, seedUploadDeadline)
- err = putSnapshot(uctx, s.cfg.SeedData, j.spool, seeds.SnapshotKey(host, j.id))
+ err = putSnapshot(uctx, j.store, j.spool, j.key)
ucancel()
if errors.Is(err, release.ErrCASConflict) {
// Another writer put this seed's snapshot first, and owns the
@@ -999,7 +1004,10 @@ func (s *Server) abortAnswered(w http.ResponseWriter, r *http.Request, sqid, app
// - any other uncommitted state: 409, abort the import instead (SD-N57).
// - a file seed reserving, aborted or rolled-back: aborted (or left
// aborting) and answered 202 with FS-13, or finished once rolled back
-// (fileSeedDeleteRule); the box's rollback and the finish free it.
+// (fileSeedDeleteRule); the box's rollback and the finish free it. On
+// a customer fleet a ready one is aborted too, and an aborted one is
+// refused (409 FS-33 or FS-34) until its box proves it clean (plan
+// D9, R1-5).
// - committed, a --from seed, any other file seed, an unseeded record,
// or a record that will not decode: the ordinary delete, conditional on the etag read here
// (deleteRead), answered as finished.
@@ -1064,8 +1072,8 @@ func (s *Server) importDeleteRule(w http.ResponseWriter, r *http.Request, acct *
// A file seed not yet ready is aborted, waited for or finished, never
// deleted outright (seedfile.go); a ready or placed one takes the
// ordinary delete, as --from's does.
- if rec != nil && fileSeedUnreadied(rec.Seed) {
- return s.fileSeedDeleteRule(w, r, acct, app, host, rec.Seed, again)
+ if rec != nil && fileSeedUnreadied(rec) {
+ return s.fileSeedDeleteRule(w, r, acct, app, host, rec, again)
}
if rec == nil || !rec.Seed.Import() || rec.Seed.State == seeds.StateCommitted {
return s.deleteRead(w, r, acct, app, host, etag, again)
@@ -1128,6 +1136,10 @@ func (s *Server) importDeleteRule(w http.ResponseWriter, r *http.Request, acct *
// refusal (settling, refused, pending) as itself, anything else main's
// delete sentence.
func (s *Server) deleteRefused(w http.ResponseWriter, sqid, app, host string, err error) (answered, finished bool) {
+ if ref, ok := fleetSeedHoldRefusal(err); ok {
+ jsonError(w, ref.Status, ref.Msg)
+ return true, false
+ }
if ref, ok := lifetimeRetireRefusal(err, msgLifetimeSettling, msgLifetimeDeletePending, http.StatusBadGateway); ok {
if !errors.Is(err, errLifetimeSettling) {
log.Printf("console: api instances delete %s/%s/%s: %v", sqid, app, host, err)
diff --git a/internal/console/apilinks_test.go b/internal/console/apilinks_test.go
index ca9782901..15c5dcf88 100644
--- a/internal/console/apilinks_test.go
+++ b/internal/console/apilinks_test.go
@@ -698,6 +698,9 @@ var linkedWalkBoxDoors = map[string]bool{
"POST /api/fleet/replicas/{account}/{app}/{host}/coordinator": true,
"POST /api/fleet/replicas/{account}/{app}/{host}/release": true,
"POST /api/fleet/replicas/{account}/{app}/{host}/deploy": true,
+ "POST /api/fleet/seeds/{account}/{app}/{host}/placed": true,
+ "POST /api/fleet/seeds/{account}/{app}/{host}/failed": true,
+ "POST /api/fleet/seeds/{account}/{app}/{host}/rolledback": true,
}
// worldSnapshot is what a refused request must not change: every console
diff --git a/internal/console/appsettings.go b/internal/console/appsettings.go
index ccd7b9315..2214bc653 100644
--- a/internal/console/appsettings.go
+++ b/internal/console/appsettings.go
@@ -1450,6 +1450,16 @@ func (s *Server) handleAppDelete(w http.ResponseWriter, r *http.Request) {
back("err", app+" is marked as production, so deleting is refused. Turn the safety delay off first (owner + passkey, on the Releases page; it takes effect after ~72h), then try again.")
return
}
+ // A fleet file seed its box has not proved gone (fleetSeedTrashRefusal):
+ // refused before the marker, so nothing changes.
+ if msg, err := s.fleetSeedTrashRefusal(ctx, acct.Sqid, app); err != nil {
+ log.Printf("console: trash %s/%s: fleet seeds: %v", acct.Sqid, app, err)
+ back("err", "Could not confirm the trash marker. Nothing was changed. Try again.")
+ return
+ } else if msg != "" {
+ back("err", msg)
+ return
+ }
now := time.Now()
if err := release.TrashApp(ctx, s.cfg.Releases, acct.Sqid, app, addr, now); err != nil {
log.Printf("console: trash %s/%s: %v", acct.Sqid, app, err)
diff --git a/internal/console/claim_invariant_fixtures_test.go b/internal/console/claim_invariant_fixtures_test.go
index ccddbe955..5e1f2324b 100644
--- a/internal/console/claim_invariant_fixtures_test.go
+++ b/internal/console/claim_invariant_fixtures_test.go
@@ -747,6 +747,11 @@ var claimFixtures = map[string]claimFixture{
"route POST /api/fleet/replicas/{account}/{app}/{host}/coordinator": {door: claimReplicaDoor("coordinator")},
"route POST /api/fleet/replicas/{account}/{app}/{host}/release": {door: claimReplicaDoor("release")},
"route POST /api/fleet/replicas/{account}/{app}/{host}/deploy": {door: claimReplicaDoor("deploy")},
+ // The fleet seeds door (apifleetseeds.go): refused on a host-claim
+ // console, which admits no seed (claim_invariant_seeds_test.go).
+ "route POST /api/fleet/seeds/{account}/{app}/{host}/placed": {refused: claimSeedsDoorRefusal("placed")},
+ "route POST /api/fleet/seeds/{account}/{app}/{host}/failed": {refused: claimSeedsDoorRefusal("failed")},
+ "route POST /api/fleet/seeds/{account}/{app}/{host}/rolledback": {refused: claimSeedsDoorRefusal("rolledback")},
"route GET /accounts": claimRead("renders only the signed-in person’s account memberships"),
// ---- methodless routes (the handler checks r.Method itself) ----
"route /api/economics/backhaul": claimRead("operator backhaul report (GET only) computed from the economics view; writes nothing"),
diff --git a/internal/console/claim_invariant_seeds_test.go b/internal/console/claim_invariant_seeds_test.go
new file mode 100644
index 000000000..7365d806e
--- /dev/null
+++ b/internal/console/claim_invariant_seeds_test.go
@@ -0,0 +1,69 @@
+package console
+
+import (
+ "context"
+ "encoding/json"
+ "net/http"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/provision"
+ "github.com/carlosframework/platform/internal/registry"
+ "github.com/carlosframework/platform/internal/seeds"
+)
+
+// claimSeedsDoorRefusal is the fleet seeds door's claim fixture: an owning
+// box's valid report, which a host-claim console refuses with the seed
+// doors' claim sentence after its owner gate and before it reads or writes
+// anything. No seed is ever admitted on such a console (seedFleetReady
+// refuses it first), so the setup writes the record a fleet's create would
+// have.
+func claimSeedsDoorRefusal(operation string) *claimRefusalFixture {
+ const host = "seeded.shop.example.com"
+ return &claimRefusalFixture{
+ apps: claimRefs("bab/titogo"),
+ setup: func(t *testing.T, cx *claimCase) {
+ cx.fleet(t)
+ token, hash, err := mintFleetToken()
+ if err != nil {
+ t.Fatal(err)
+ }
+ reg, err := openRegistry(cx.srv.cfg.Registry)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := reg.AddFleetBox(registry.FleetBox{Fleet: "pi", Label: "pi-1", TokenHash: hash}); err != nil {
+ t.Fatal(err)
+ }
+ id, err := seeds.NewID()
+ if err != nil {
+ t.Fatal(err)
+ }
+ now := time.Now().UTC()
+ rec := provision.Record{Schema: 1, Account: "bab", App: "titogo", Host: host, Slug: "seeded", Region: "fleet/pi",
+ FleetBox: "pi-1", Channel: "stable", CreatedAt: now,
+ Seed: &provision.SeedSource{ID: id, Kind: seeds.KindFile, State: seeds.StateReady, SHA256: strings.Repeat("a", 64),
+ Bytes: 4, By: "paul@keymail.dev", At: now}}
+ if err := provision.CreateRecord(context.Background(), cx.rel, rec); err != nil {
+ t.Fatal(err)
+ }
+ cx.vars["seed-token"], cx.vars["seed-id"] = token, id
+ },
+ do: func(t *testing.T, cx *claimCase) (int, string) {
+ body := map[string]string{"id": cx.vars["seed-id"]}
+ if operation == provision.FleetSeedFailed {
+ body["code"] = provision.SeedCodeMismatch
+ }
+ raw, err := json.Marshal(body)
+ if err != nil {
+ t.Fatal(err)
+ }
+ status, _, out := rawReqHeader(t, http.MethodPost, cx.ts.URL+"/api/fleet/seeds/bab/titogo/"+host+"/"+operation,
+ cx.vars["seed-token"], string(raw), map[string]string{"Carlos-Tunnel-Name": "pi/pi-1"})
+ return status, out
+ },
+ status: http.StatusConflict,
+ msg: seedClaimConsoleRefusal().Msg,
+ }
+}
diff --git a/internal/console/demo_expiry.go b/internal/console/demo_expiry.go
index 0989c7399..a2e02d3e4 100644
--- a/internal/console/demo_expiry.go
+++ b/internal/console/demo_expiry.go
@@ -325,6 +325,15 @@ func (s *Server) retireDemoLocked(ctx context.Context, d DemoRow, now time.Time,
} else if estate {
return demo.ErrPolicy
}
+ // The fleet seed hold's purge check, as every purge entrance asks it
+ // (fleetSeedPurgeRefusal). A demo app cannot hold a fleet file seed
+ // today (a file seed's begin refuses a demo record, seedPlacementRefusal),
+ // so this never refuses; it is asked so the rule has no exception.
+ if msg, err := s.fleetSeedPurgeRefusal(ctx, d.AccountSqid, d.App); err != nil {
+ return err
+ } else if msg != "" {
+ return errors.New(msg)
+ }
if err = release.PurgeAppGuards(ctx, s.cfg.Releases, s.cfg.ReleasePub, d.AccountSqid, d.App, at, now); err != nil {
return err
}
diff --git a/internal/console/domainattach.go b/internal/console/domainattach.go
index eff9f536e..765d8f848 100644
--- a/internal/console/domainattach.go
+++ b/internal/console/domainattach.go
@@ -472,6 +472,9 @@ func (s *Server) releaseDomainHost(ctx context.Context, acct *Account, app, host
// attach. A record left behind by a released claim would keep a
// route alive for a host anyone may now claim.
if err := s.retireInstanceRecord(ctx, acct.Sqid, app, host, "domain-detach", claim.RecordIncarnation, retireAny); err != nil {
+ if ref, ok := fleetSeedHoldRefusal(err); ok {
+ return ref
+ }
// The record's delete operation is durable and still running
// (or another operation holds the app): the hostname stays
// claimed until a later detach finds the record gone.
@@ -521,6 +524,9 @@ func (s *Server) detachRetireLocked(ctx context.Context, sqid, app, host string)
if err == nil {
return nil, nil
}
+ if ref, ok := fleetSeedHoldRefusal(err); ok {
+ return ref, nil
+ }
// Settling and pending both leave the route's removal to finish first:
// a later detach finds the record gone and releases the claim.
if ref, ok := lifetimeRetireRefusal(err, claimDetachInProgressMsg, claimDetachInProgressMsg, http.StatusConflict); ok {
diff --git a/internal/console/domainattach_test.go b/internal/console/domainattach_test.go
index 6fa64643c..572989958 100644
--- a/internal/console/domainattach_test.go
+++ b/internal/console/domainattach_test.go
@@ -108,6 +108,14 @@ func (o *opStore) Delete(ctx context.Context, key string) error {
return o.Store.Delete(ctx, key)
}
+// DeleteIfMatch logs a conditional delete as a delete and passes it to the
+// store below: the legacy retire binds its delete to the read it asked the
+// fleet seed hold of (hostclaimops.go).
+func (o *opStore) DeleteIfMatch(ctx context.Context, key, etag string) error {
+ o.ops = append(o.ops, "delete "+key)
+ return release.DeleteIfMatch(ctx, o.Store, key, etag)
+}
+
// opIndex is where an op appears in the log, or -1.
func (o *opStore) opIndex(op string) int {
for i, got := range o.ops {
diff --git a/internal/console/expirypass.go b/internal/console/expirypass.go
index 8053a4684..84f072399 100644
--- a/internal/console/expirypass.go
+++ b/internal/console/expirypass.go
@@ -184,6 +184,16 @@ func (s *Server) expireOne(ctx context.Context, r AppRow, now time.Time, ev evid
s.audit(acct, r.App, expiryActor, "expire-refused", "did not move "+r.App+" to the trash: it is marked as the control plane")
return
}
+ // A fleet file seed its box has not proved gone (fleetSeedTrashRefusal):
+ // not trashed this pass; the next asks again.
+ if msg, err := s.fleetSeedTrashRefusal(ctx, r.Sqid, r.App); err != nil || msg != "" {
+ if err != nil {
+ msg = err.Error()
+ jobFailed(ctx, fmt.Errorf("expiry pass: %s/%s: fleet seeds: %w; not trashing", r.Sqid, r.App, err))
+ }
+ log.Printf("console: expiry pass: %s/%s: %s Not moving it to the trash this pass.", r.Sqid, r.App, msg)
+ return
+ }
if err := release.TrashApp(ctx, s.cfg.Releases, r.Sqid, r.App, expiryActor, now); err != nil {
log.Printf("console: expiry pass: trash %s/%s: %v", r.Sqid, r.App, err)
jobFailed(ctx, fmt.Errorf("expiry pass: trash %s/%s: %w", r.Sqid, r.App, err))
@@ -243,6 +253,16 @@ func (s *Server) purgeOne(ctx context.Context, r AppRow, now time.Time, ev evide
s.audit(acct, r.App, expiryActor, "purge-refused", "did not delete "+r.App+": it has email set up. Delete it from the Trash page")
return
}
+ // A fleet file seed still holding a hostname (plan R1-1): not purged
+ // until its box has proved it clean. The next pass asks again.
+ if msg, err := s.fleetSeedPurgeRefusal(ctx, r.Sqid, r.App); err != nil || msg != "" {
+ if err != nil {
+ msg = err.Error()
+ jobFailed(ctx, fmt.Errorf("expiry pass: %s/%s: fleet seeds: %w; not purging", r.Sqid, r.App, err))
+ }
+ log.Printf("console: expiry pass: %s/%s: %s Not purging it this pass.", r.Sqid, r.App, msg)
+ return
+ }
// The purge's own guards first, at the marker clock this decision was
// made about: a purge they refuse (store estate, a production flag, a
// restore since) retires no media job. Then the app's media jobs,
diff --git a/internal/console/hostclaimops.go b/internal/console/hostclaimops.go
index 344d43a1e..b8c56ba31 100644
--- a/internal/console/hostclaimops.go
+++ b/internal/console/hostclaimops.go
@@ -4,11 +4,13 @@ import (
"context"
"errors"
"log"
+ "os"
"time"
"github.com/carlosframework/platform/internal/hostclaim"
"github.com/carlosframework/platform/internal/hostops"
"github.com/carlosframework/platform/internal/provision"
+ "github.com/carlosframework/platform/internal/release"
)
func (s *Server) retireHostRecord(ctx context.Context, ref provision.RetireRef) error {
@@ -19,6 +21,12 @@ func (s *Server) retireHostRecord(ctx context.Context, ref provision.RetireRef)
// deletes a record does the same.
s.noteRecordDeletion(ref.Account, ref.App, time.Now())
if s.cfg.HostClaim {
+ // The claim chain does not ask the fleet seed hold (fleetSeedHold).
+ // That is safe only because a claim console never admits a seed:
+ // every seed door refuses it (seedClaimConsoleRefusal, and
+ // seedFleetReady asks first), so no fleet file seed's record is
+ // ever retired here. A claim console that admits seeds must add
+ // the hold to this branch first.
return s.retireClaimHostRecord(ctx, ref)
}
if ref.Family == "instance" && lifetimesUnit(ctx) {
@@ -30,8 +38,43 @@ func (s *Server) retireHostRecord(ctx context.Context, ref provision.RetireRef)
if s.cfg.HostClaimOps != nil {
claims = s.cfg.HostClaimOps
}
+ if ref.Family == "instance" {
+ return s.retireLegacyInstanceRecord(ctx, ref)
+ }
return provision.RetireRecord(ctx, s.cfg.Releases, ref, provision.RetireOptions{HostClaim: s.cfg.HostClaim, Claims: claims})
}
+
+// retireLegacyInstanceRecord is a claims-off instance retirement with
+// lifetimes off: the fleet seed hold (fleetSeedHold, Task 16 review P1-1)
+// asked of the record as it reads now, and the delete bound to that read
+// (review round 2, P2-A). With lifetimes off no lock orders it against a
+// create (the create door holds only the account lock, and a detach none),
+// so an unconditional delete could remove a fleet file seed written at the
+// host after the hold was asked. release.DeleteIfMatch on the read's etag
+// deletes only the body the hold saw: a record written since answers
+// release.ErrCASConflict, which every caller's failure branch answers as
+// "try again", and the next try asks the hold of it. An absent key is
+// done, as lifetimes on answers it. A body whose region and seed cannot be
+// read is refused (fleetSeedHoldRaw fails closed, slice 3 review P3-1).
+func (s *Server) retireLegacyInstanceRecord(ctx context.Context, ref provision.RetireRef) error {
+ // The read is the judged reader's (observeRecord): with lifetimes off it
+ // is the plain read, with the stored bytes and their etag.
+ obs := s.observeRecord(ctx, ref.Account, ref.App, ref.Host)
+ switch {
+ case obs.Verdict == provision.LifetimeUnreadable:
+ return obs.Err
+ case !obs.Present:
+ return nil
+ }
+ if err := fleetSeedHoldRaw(ref.Host, obs.Raw); err != nil {
+ return err
+ }
+ key := provision.RecordKey(ref.Account, ref.App, ref.Host)
+ if err := release.DeleteIfMatch(ctx, s.cfg.Releases, key, obs.ETag); err != nil && !errors.Is(err, os.ErrNotExist) {
+ return err
+ }
+ return nil
+}
func (s *Server) adoptHostRecord(ctx context.Context, key string) (hostclaim.Observed, error) {
if !s.cfg.HostClaim || s.cfg.HostClaimOps == nil {
return hostclaim.Observed{}, hostops.ErrContract
diff --git a/internal/console/lifetimes_create_test.go b/internal/console/lifetimes_create_test.go
index db8d30b28..a8adae82f 100644
--- a/internal/console/lifetimes_create_test.go
+++ b/internal/console/lifetimes_create_test.go
@@ -2248,7 +2248,9 @@ func TestDispatchFollowsTheUnit(t *testing.T) {
l.fx.srv.cfg.Releases = bucket
createGate, createHook := pauseNth(t, "put", recKey(ltApp, ltOne), 1)
deleteGate, deleteHook := pauseNth(t, "delete-if-match", recKey(ltApp, ltOld), 1) // deleteRead's conditional delete
- detachGate, detachHook := pauseNth(t, "delete", recKey(ltApp, ltDomain), 1)
+ // The legacy detach's delete is bound to its read (the fleet seed hold,
+ // retireLegacyInstanceRecord), so it is a conditional delete too.
+ detachGate, detachHook := pauseNth(t, "delete-if-match", recKey(ltApp, ltDomain), 1)
bucket.setHook(chain(createHook, deleteHook, detachHook))
// Three units admitted before the marker, each held inside its door.
answers := make(chan string, 3)
diff --git a/internal/console/lifetimes_purge.go b/internal/console/lifetimes_purge.go
index 8913586c4..a37fd0d9b 100644
--- a/internal/console/lifetimes_purge.go
+++ b/internal/console/lifetimes_purge.go
@@ -241,6 +241,15 @@ func (s *Server) sweepTrashedApp(ctx context.Context, a release.TrashedApp, now
s.lifetimeLogHourly("trash-sweep "+a.Account+"/"+a.App, "console: trash sweep: %s/%s has email estate; not purging it. Delete it from the Trash page", a.Account, a.App)
return
}
+ // A fleet file seed still holding a hostname (plan R1-1): not purged
+ // until its box has proved it clean (FS-35 in the log).
+ if msg, err := s.fleetSeedPurgeRefusal(ctx, a.Account, a.App); err != nil {
+ s.lifetimeLogHourly("trash-sweep "+a.Account+"/"+a.App, "console: trash sweep: %s/%s: fleet seeds: %v; not purging", a.Account, a.App, err)
+ return
+ } else if msg != "" {
+ s.lifetimeLogHourly("trash-sweep "+a.Account+"/"+a.App, "console: trash sweep: %s/%s: %s", a.Account, a.App, msg)
+ return
+ }
// The purge's own guards first, at the marker's clock: a purge they
// refuse (store estate, a production flag) retires no media job. Then
// the app's media jobs, before any purge step: while a task is still
diff --git a/internal/console/lifetimes_retire.go b/internal/console/lifetimes_retire.go
index b0746cd16..955f81d23 100644
--- a/internal/console/lifetimes_retire.go
+++ b/internal/console/lifetimes_retire.go
@@ -125,6 +125,16 @@ func (s *Server) retireRecordWithLifetimeLocked(ctx context.Context, acct, app,
owned && slot.Incarnation == expect.Incarnation):
return nil
}
+ // The fleet seed hold (Task 16 review P1-1): a fleet file seed whose box
+ // has not proved it gone is never retired, whichever entrance asked.
+ // Read under both locks, before anything is persisted.
+ // Asked of the stored body, not obs.Rec: a stale or corrupt body has
+ // no Rec, and is held all the same (fleetSeedHoldRaw).
+ if obs.Present {
+ if err := fleetSeedHoldRaw(host, obs.Raw); err != nil {
+ return err
+ }
+ }
liveOwned := owned && slot.State == provision.SlotLive
switch {
case !obs.Present && slot == nil: // (a)
diff --git a/internal/console/linkedpolicy.go b/internal/console/linkedpolicy.go
index 91d0293dc..dee00a86f 100644
--- a/internal/console/linkedpolicy.go
+++ b/internal/console/linkedpolicy.go
@@ -302,6 +302,9 @@ var linkedPolicies = map[string]linkedPolicy{
"POST /api/fleet/replicas/{account}/{app}/{host}/coordinator": linkedRefuse,
"POST /api/fleet/replicas/{account}/{app}/{host}/release": linkedRefuse,
"POST /api/fleet/replicas/{account}/{app}/{host}/deploy": linkedRefuse,
+ "POST /api/fleet/seeds/{account}/{app}/{host}/placed": linkedRefuse,
+ "POST /api/fleet/seeds/{account}/{app}/{host}/failed": linkedRefuse,
+ "POST /api/fleet/seeds/{account}/{app}/{host}/rolledback": linkedRefuse,
}
// refuseLinkedJSON answers an API door's linked refusal, if any, and
diff --git a/internal/console/ownership.go b/internal/console/ownership.go
index 5f4251210..b2fef71b3 100644
--- a/internal/console/ownership.go
+++ b/internal/console/ownership.go
@@ -544,6 +544,19 @@ func (s *Server) handlePurgeApp(w http.ResponseWriter, r *http.Request) {
fail(purgeAdvice(err, app))
return
}
+ // A fleet file seed's hostname is released only once its box has proved
+ // nothing of it is left (fleet seeded create design §3.6, plan R1-1):
+ // the purge would retire its record without that proof. Asked before
+ // any teardown below, and refused (FS-35) while one holds a hostname,
+ // or when the records cannot be read whole.
+ if msg, err := s.fleetSeedPurgeRefusal(r.Context(), acct.Sqid, app); err != nil {
+ log.Printf("console: purge %s/%s: fleet seeds: %v", acct.Sqid, app, err)
+ fail(purgeAdvice(err, app))
+ return
+ } else if msg != "" {
+ fail(msg)
+ return
+ }
if s.cfg.HostClaim {
if s.cfg.ClaimPurge == nil {
s.renderDoorRefusal(w, r, claimResponseRefusal(hostops.ErrContract))
@@ -715,7 +728,12 @@ func (s *Server) trashFailure(w http.ResponseWriter, r *http.Request, acct *Acco
// same sentence the CLI's 409 gives (apicli.go), so an operator who meets both
// doors hears one instruction rather than two.
func purgeAdvice(err error, app string) string {
+ var held *fleetSeedHoldError
switch {
+ case errors.As(err, &held):
+ // The hold's backstop in the retirement primitive (the purge
+ // entrances ask unfinishedFleetFileSeeds first): FS-35.
+ return fmt.Sprintf(fileSeedPurgeHeldCopy, app, held.Host)
case errors.Is(err, release.ErrNotTrashed):
return "“" + app + "” is not in the trash, so nothing was deleted. It may have been " +
"restored, or already deleted, since this page was loaded."
diff --git a/internal/console/routedecls.go b/internal/console/routedecls.go
index faed3a3c7..27b800b18 100644
--- a/internal/console/routedecls.go
+++ b/internal/console/routedecls.go
@@ -465,6 +465,13 @@ var routeDecls = []routeDecl{
{Pattern: "POST /api/fleet/replicas/{account}/{app}/{host}/coordinator", Handler: (*Server).handleReplicaCoordinator},
{Pattern: "POST /api/fleet/replicas/{account}/{app}/{host}/release", Handler: (*Server).handleReplicaRelease},
{Pattern: "POST /api/fleet/replicas/{account}/{app}/{host}/deploy", Handler: (*Server).handleReplicaDeploy},
+ // The fleet seeds door (apifleetseeds.go, fleet seeded create design
+ // §3.5): a customer-fleet box reports its file seed's placement,
+ // failure and rollback, authenticated as the replica doors are. Every
+ // refusal of the caller is the same 404.
+ {Pattern: "POST /api/fleet/seeds/{account}/{app}/{host}/placed", Handler: (*Server).handleFleetSeedPlaced},
+ {Pattern: "POST /api/fleet/seeds/{account}/{app}/{host}/failed", Handler: (*Server).handleFleetSeedFailed},
+ {Pattern: "POST /api/fleet/seeds/{account}/{app}/{host}/rolledback", Handler: (*Server).handleFleetSeedRolledBack},
{Pattern: "POST /auth/cli/start", Handler: (*Server).handleCLIStart},
{Pattern: "POST /auth/cli/poll", Handler: (*Server).handleCLIPoll},
{Pattern: "GET /auth/cli", Handler: (*Server).handleCLIApprovePage},
diff --git a/internal/console/seedfile.go b/internal/console/seedfile.go
index fb9e71b3e..7a0b9977b 100644
--- a/internal/console/seedfile.go
+++ b/internal/console/seedfile.go
@@ -6,26 +6,31 @@
// placed; aborted, rolled-back), not the import's swap, so a region file
// seed is --from-shaped everywhere except how its bytes arrive.
//
-// This file holds the file seed's begin, its readiness rule and the
-// helpers the import door calls when it meets a file seed. Fleet records
-// are refused here until slice 3 of the plan.
+// This file holds the file seed's begin, its readiness rules (a region's,
+// and a customer fleet's, slice 3) and the helpers the import door calls
+// when it meets a file seed.
package console
import (
+ "bytes"
"context"
+ "encoding/json"
"errors"
"fmt"
"log"
"net/http"
"os"
+ "sort"
"strings"
"time"
"github.com/carlosframework/platform/internal/provision"
"github.com/carlosframework/platform/internal/regionlabel"
+ "github.com/carlosframework/platform/internal/registry"
"github.com/carlosframework/platform/internal/release"
"github.com/carlosframework/platform/internal/seeds"
+ "github.com/carlosframework/platform/internal/status"
)
// seedFileReserveTTL is how long a file seed may stay reserving before the
@@ -59,12 +64,14 @@ func (s *Server) createFileSeed(w http.ResponseWriter, r *http.Request, c seedCr
}
// beginFileSeed runs after the create door's own checks, seedOneDoorRefusal
-// and seedCommonRefusal among them. It refuses a pool (FS-20), a fleet
-// (seedPlacementRefusal's sentence, until slice 3) and an HA region
-// (FS-16); a region record must be in this console's region (FS-15), as
-// the import's must, because the snapshot goes to this console's data
-// bucket. Then seedFileReady, the size and sha256, and private storage as
-// the import does. The record is written reserving, kind file, with the
+// and seedCommonRefusal among them. It refuses a pool (FS-20) and an HA
+// region (FS-16); a region record must be in this console's region
+// (FS-15), as the import's must, because the snapshot goes to this
+// console's data bucket. A fleet-placed record skips the region and
+// data-bucket checks: its snapshot goes to the deployment bucket, which the
+// fleet's box reads through the store door (fleet seeded create design
+// §3.3), and its readiness is seedFleetReady's. Then the size and sha256,
+// and private storage as the import does. The record is written reserving, kind file, with the
// sha256 and length the upload must match and no Replaces or VerifyHash,
// before any byte of the snapshot is stored (design §3.2). It answers 201
// with the record view.
@@ -76,6 +83,7 @@ func (s *Server) createFileSeed(w http.ResponseWriter, r *http.Request, c seedCr
func (s *Server) beginFileSeed(w http.ResponseWriter, r *http.Request, c seedCreate, imp seedImportReq) {
ctx := r.Context()
acct, app, host := c.acct, c.app, c.rec.Host
+ fleet, onFleet := registry.FleetPlacement(c.rec.Region)
if ref := fileSeedPlacementRefusal(c); ref != nil {
jsonError(w, ref.Status, ref.Msg)
return
@@ -87,13 +95,17 @@ func (s *Server) beginFileSeed(w http.ResponseWriter, r *http.Request, c seedCre
jsonError(w, ref.Status, ref.Msg)
return
}
- if c.rec.Region != s.cfg.Region {
+ if !onFleet && c.rec.Region != s.cfg.Region {
jsonError(w, http.StatusConflict, fmt.Sprintf(fileSeedRegionCopy, s.dbRegionName(s.cfg.Region), host))
return
}
checks, cancel := context.WithTimeout(ctx, instanceStoreTimeout)
defer cancel()
- if ref := s.seedFileReady(checks, c.rec.Region); ref != nil {
+ ready := func() *doorRefusal { return s.seedFileReady(checks, c.rec.Region) }
+ if onFleet {
+ ready = func() *doorRefusal { return s.seedFleetReady(checks, fleet) }
+ }
+ if ref := ready(); ref != nil {
jsonError(w, ref.Status, ref.Msg)
return
}
@@ -198,17 +210,22 @@ func (s *Server) beginFileSeed(w http.ResponseWriter, r *http.Request, c seedCre
out := s.publicRecordView(ctx, rec)
out.PrivateStoreBucket = privateBucket
out.RegionFrom = c.regionFrom
- out.RegionName = s.placeOf(rec.Region, s.candsOrHome(viewCtx)) // never fleet-placed: refused above
+ // A fleet-placed record's Region is the fleet itself, as the ordinary
+ // create answers it.
+ if !onFleet {
+ out.RegionName = s.placeOf(rec.Region, s.candsOrHome(viewCtx))
+ }
// The region's label (region labels §4), as every create answer has.
out.RegionLabel = regionlabel.ForRecord(rec, s.regionHome(), s.regionNames()).Text
writeJSON(w, http.StatusCreated, out)
}
-// fileSeedPlacementRefusal is a file seed's placement rule. A pool has its
-// own sentence (FS-20), since file seeds will reach a fleet but not a pool.
-// A fleet keeps seedPlacementRefusal's sentence until slice 3 admits it.
+// fileSeedPlacementRefusal is a file seed's placement rule. A customer
+// fleet is admitted (slice 3; its readiness is seedFleetReady's). A pool has
+// its own sentence (FS-20), since file seeds reach a fleet but not a pool.
+// A demo, or a placement that is not a fleet, keeps seedPlacementRefusal's.
func fileSeedPlacementRefusal(c seedCreate) *doorRefusal {
- if c.rec.Demo != nil || c.placed != "" {
+ if _, fleet := registry.FleetPlacement(c.placed); c.rec.Demo != nil || c.placed != "" && !fleet {
return seedPlacementRefusal(c)
}
if c.m.Pool != "" {
@@ -242,19 +259,49 @@ func (s *Server) refuseHASeed(w http.ResponseWriter, rec *provision.Record, kind
// seedStorageRefusal is the one answer to "can this console store this
// seed's snapshot" (plan R2-2), asked by begin and by the upload alike so
-// the two never disagree. placement is the record's Region column.
-// kind and placement are unused until slice 3's fleet branch reads them. An
-// import and a region file seed need this console's data bucket and the
-// hibernation bucket its replicas live in; the refusal is the import's,
-// byte for byte (seedNoDataRefusal). Slice 3 adds the fleet file seed's
-// branch here, which needs the deployment bucket instead.
+// the two never disagree, and nothing else checks storage. placement is
+// the record's Region column. An import and a region file seed need this
+// console's data bucket and the hibernation bucket its replicas live in;
+// the refusal is the import's, byte for byte (seedNoDataRefusal). A fleet
+// file seed needs the deployment bucket and nothing regional: its snapshot
+// goes there (seedSnapshotTarget), and its replica is the fleet's own.
func (s *Server) seedStorageRefusal(kind, placement string) *doorRefusal {
+ if _, fleet := registry.FleetPlacement(placement); fleet && kind == seeds.KindFile {
+ // Defensive only, and unreachable today: every door that reaches
+ // here has passed instanceGate, which already refuses a console
+ // with no deployment bucket (apiinstances.go). The import's
+ // sentence stands in rather than new copy.
+ if s.cfg.Releases == nil {
+ return seedNoDataRefusal()
+ }
+ return nil
+ }
if s.cfg.SeedData == nil || s.cfg.HibernateBucket == "" {
return seedNoDataRefusal()
}
return nil
}
+// seedSnapshotTarget is where rec's seed snapshot lives: a fleet file
+// seed's in the deployment bucket at seeds.FleetSnapshotKey, which the
+// fleet's box reads through the store door (fleet seeded create design
+// §3.3); every other seed's in this console's data bucket at
+// seeds.SnapshotKey. The key is built from the record's own values, never
+// from a request (seeds.Check has passed on them).
+func (s *Server) seedSnapshotTarget(rec *provision.Record) (release.Store, string) {
+ if seedOnFleet(rec) {
+ return s.cfg.Releases, seeds.FleetSnapshotKey(rec.Account, rec.App, rec.Host, rec.Seed.ID)
+ }
+ return s.cfg.SeedData, seeds.SnapshotKey(rec.Host, rec.Seed.ID)
+}
+
+// seedOnFleet reports a fleet file seed: a file seed whose record is
+// placed on a customer fleet.
+func seedOnFleet(rec *provision.Record) bool {
+ _, fleet := registry.FleetPlacement(rec.Region)
+ return fleet && rec.Seed != nil && rec.Seed.Kind == seeds.KindFile
+}
+
// seedFileReady is seedRegionReady with the file protocol: the published
// floor's Min must be at least seeds.FileSeedProtocol (FS-25), and every
// box in the region must report at least max(FileSeedProtocol, floor.Min).
@@ -265,9 +312,13 @@ func (s *Server) seedFileReady(ctx context.Context, region string) *doorRefusal
}
// seedUploadReady is the upload's readiness re-check, by the seed's kind:
-// an import keeps its one-box rule, a file seed asks seedFileReady.
+// an import keeps its one-box rule, a file seed asks seedFileReady, or on a
+// fleet seedFleetReady, as its begin did.
func (s *Server) seedUploadReady(ctx context.Context, rec *provision.Record) *doorRefusal {
if rec.Seed != nil && rec.Seed.Kind == seeds.KindFile {
+ if fleet, ok := registry.FleetPlacement(rec.Region); ok {
+ return s.seedFleetReady(ctx, fleet)
+ }
return s.seedFileReady(ctx, rec.Region)
}
return s.seedRegionReady(ctx, rec.Region, true)
@@ -316,40 +367,55 @@ func (s *Server) abortFileSeed(ctx context.Context, sqid, app, host, id, reason,
}
// fileSeedUnreadied reports a file seed the delete door must not drop
-// outright: reserving (its upload not landed), aborted or rolled-back.
-func fileSeedUnreadied(seed *provision.SeedSource) bool {
+// outright: reserving (its upload not landed), aborted or rolled-back; and
+// on a customer fleet, ready too (plan D9): a fleet file seed's hostname is
+// released only after its box proves nothing of it is left (design §3.6),
+// so nothing before placement may take the ordinary delete.
+func fileSeedUnreadied(rec *provision.Record) bool {
+ seed := rec.Seed
if seed == nil || seed.Kind != seeds.KindFile {
return false
}
switch seed.State {
case seeds.StateReserving, seeds.StateAborted, seeds.StateRolledBack:
return true
+ case seeds.StateReady:
+ return seedOnFleet(rec)
}
return false
}
// fileSeedDeleteRule is the delete door's answer to a file seed that never
// became ready (plan D9's region case, pulled forward at the slice 1
-// review). The ordinary delete would drop the record without the box's
-// rollback or the console's finish, stranding the private store the begin
-// made, so the next --seed-file on the host would meet the store-taken
-// refusal. So:
+// review), or on a customer fleet never placed (slice 3). The ordinary
+// delete would drop the record without the box's rollback or the
+// console's finish, stranding the private store the begin made, so the
+// next --seed-file on the host would meet the store-taken refusal; and on
+// a fleet it would release a hostname nothing has proved free. So:
//
-// - reserving: aborted (SeedAbortFileUploadBecause, a CAS that acts only
-// while it is still reserving), the serial bumped, and 202 with FS-13.
-// - aborted (by this door, the sweep or a failed upload): 202 with FS-13
-// again, writing nothing; the box has its rollback still to do.
+// - reserving (and on a fleet, ready): aborted, the serial bumped, and
+// 202 with FS-13. A region seed's abort acts only while it is still
+// reserving (SeedAbortFileUploadBecause); a fleet seed's from either
+// state (SeedAbort).
+// - aborted, on a region (by this door, the sweep or a failed upload):
+// 202 with FS-13 again, writing nothing; the box has its rollback still
+// to do.
+// - aborted, on a fleet, whatever its reason (plan R1-5): 409, writing
+// nothing. Only the fleet's box can release the hostname, by reporting
+// rolledback to the seeds door once it has proved the seed gone; until
+// then the answer says why it is held (fleetSeedHeldSentence).
// - rolled-back: the console's finish (store, snapshot, replica, then
// the record), answered as a finished delete.
//
-// The record holds the hostname until the finish deletes it. A ready or
-// placed file seed is not here: it takes the ordinary delete, exactly as a
-// --from seed in those states does.
+// The record holds the hostname until the finish deletes it. A region
+// ready or a placed file seed is not here: it takes the ordinary delete,
+// exactly as a --from seed in those states does.
//
// An abort CAS that finds the seed moved on (its upload landed, the sweep
// got there) decides once more from a fresh read when again allows, else
// answers SD-N60.
-func (s *Server) fileSeedDeleteRule(w http.ResponseWriter, r *http.Request, acct *Account, app, host string, seed *provision.SeedSource, again bool) (answered, finished bool) {
+func (s *Server) fileSeedDeleteRule(w http.ResponseWriter, r *http.Request, acct *Account, app, host string, rec *provision.Record, again bool) (answered, finished bool) {
+ seed, onFleet := rec.Seed, seedOnFleet(rec)
if s.cfg.HostClaim {
// No finish runs on a claim console, so nothing there may abort a
// seed whose finish frees the host; no seed door begins one there.
@@ -360,6 +426,10 @@ func (s *Server) fileSeedDeleteRule(w http.ResponseWriter, r *http.Request, acct
aborting := map[string]string{"state": "aborting", "message": fmt.Sprintf(fileSeedDeletingCopy, host)}
switch seed.State {
case seeds.StateAborted:
+ if onFleet {
+ jsonError(w, http.StatusConflict, fleetSeedHeldSentence(host, seed))
+ return true, false
+ }
writeJSON(w, http.StatusAccepted, aborting)
return true, false
case seeds.StateRolledBack:
@@ -370,7 +440,11 @@ func (s *Server) fileSeedDeleteRule(w http.ResponseWriter, r *http.Request, acct
}
ctx, cancel := context.WithTimeout(context.WithoutCancel(r.Context()), instanceStoreTimeout)
defer cancel()
- _, err := provision.SetRecordSeed(ctx, s.cfg.Releases, acct.Sqid, app, host, provision.SeedAbortFileUploadBecause(seed.ID, ""))
+ abort := provision.SeedAbortFileUploadBecause(seed.ID, "")
+ if onFleet {
+ abort = provision.SeedAbort(seed.ID)
+ }
+ _, err := provision.SetRecordSeed(ctx, s.cfg.Releases, acct.Sqid, app, host, abort)
switch {
case errors.Is(err, os.ErrNotExist):
return true, true // gone already: the delete's idempotent answer
@@ -394,3 +468,279 @@ func (s *Server) fileSeedDeleteRule(w http.ResponseWriter, r *http.Request, acct
writeJSON(w, http.StatusAccepted, aborting)
return true, false
}
+
+// seedFleetReady is the fleet file seed's readiness (fleet seeded create
+// design §3.4), asked by begin and by the upload's re-check alike. nil
+// means go ahead. In order:
+//
+// - a claim-enabled console refuses first (plan R3-1), before any fleet
+// check, as seedRegionReadyForEdges does: such a console neither sweeps
+// nor finishes a seed, so it must never admit one;
+// - the seeds floor is published and usable, with Min at least
+// seeds.FleetFileSeedProtocol (FS-25);
+// - the fleet has exactly one active box (decision D8): a file seed's
+// record is created unlabelled, before fleet labelling, so one box must
+// be its owner (FS-21); none is unconfirmed (FS-22);
+// - the fleet's heartbeats read whole, and the box's is fresh and carries
+// Metrics, Layout and SeedsFloor, once (FS-22, a 503, the box logged);
+// - the box's seeds floor is the region check's rule (seedfloor.go):
+// protocol at least max(FleetFileSeedProtocol, floor.Min), the floor's
+// min_release armed, carlos.prev none or vouched for it, and the root
+// floor guard not refusing (FS-23);
+// - no claim control on the box (FS-24);
+// - the box runs nested (FS-26; a flat box is refused, decision D13).
+//
+// Every missing, zero or unreadable fact is not ready. A box with an old
+// heartbeat (no seeds_floor) never reads as ready.
+func (s *Server) seedFleetReady(ctx context.Context, fleet string) *doorRefusal {
+ if s.cfg.HostClaim {
+ return seedClaimConsoleRefusal()
+ }
+ floor, ref := s.publishedSeedsFloor(ctx)
+ if ref != nil {
+ return ref
+ }
+ if floor.Min < seeds.FleetFileSeedProtocol {
+ return &doorRefusal{Status: http.StatusConflict, Msg: fileSeedFloorCopy}
+ }
+ unconfirmed := &doorRefusal{Status: http.StatusServiceUnavailable, Msg: fmt.Sprintf(fileSeedFleetUnconfirmedCopy, fleet)}
+ reg, err := openRegistry(s.cfg.Registry)
+ if err != nil {
+ log.Printf("console: seed file readiness: fleet %s: registry: %v", fleet, err)
+ return unconfirmed
+ }
+ regBoxes, err := reg.ListFleetBoxes(fleet)
+ if err != nil {
+ log.Printf("console: seed file readiness: fleet %s: list its boxes: %v", fleet, err)
+ return unconfirmed
+ }
+ var active []string
+ for _, b := range regBoxes {
+ if b.Status == "active" {
+ active = append(active, b.Label)
+ }
+ }
+ switch {
+ case len(active) == 0:
+ log.Printf("console: seed file readiness: fleet %s has no active box", fleet)
+ return unconfirmed
+ case len(active) > 1:
+ return &doorRefusal{Status: http.StatusConflict, Msg: fmt.Sprintf(fileSeedFleetBoxesCopy, fleet)}
+ }
+ label := active[0]
+ beats, complete, err := status.LoadBoxesComplete(ctx, release.NewPrefixStore(s.cfg.Releases, "fleets/"+fleet+"/"))
+ if err != nil || !complete {
+ log.Printf("console: seed file readiness: fleet %s: heartbeats complete %v: %v", fleet, complete, err)
+ return unconfirmed
+ }
+ var b status.Box
+ seen := 0
+ for _, hb := range beats {
+ if hb.Label == label {
+ b, seen = hb, seen+1
+ }
+ }
+ why := ""
+ switch {
+ case seen == 0:
+ why = "no heartbeat"
+ case seen > 1:
+ why = "more than one heartbeat with this label"
+ case status.BoxStale(b, time.Now(), status.SnapshotPeriod):
+ why = "stale heartbeat, generated " + b.GeneratedAt.UTC().Format(time.RFC3339)
+ case b.Metrics == nil || b.Metrics.Layout == nil:
+ why = "no layout report"
+ case b.Metrics.SeedsFloor == nil:
+ why = "no seeds floor report"
+ }
+ if why != "" {
+ log.Printf("console: seed file readiness: box %q in fleet %s is unconfirmed: %s", label, fleet, why)
+ return unconfirmed
+ }
+ f := b.Metrics.SeedsFloor
+ prevOK := b.Metrics.PrevRelease == "none" || f.PrevAllowedFor == floor.MinRelease
+ rootRefused := (f.MovesFloorState != "" || f.MovesFloorGeneration != 0 || f.FloorState != "" || f.FloorGeneration != 0) &&
+ (f.FloorState != "accepted" || f.FloorGeneration == 0)
+ switch {
+ case f.Protocol < max(seeds.FleetFileSeedProtocol, floor.Min) || rootRefused || f.MinRelease != floor.MinRelease || !prevOK:
+ return &doorRefusal{Status: http.StatusConflict, Msg: fmt.Sprintf(fileSeedFleetBelowFloorCopy, label, fleet)}
+ case b.Metrics.HostClaimEnabled:
+ return &doorRefusal{Status: http.StatusConflict, Msg: fmt.Sprintf(fileSeedFleetClaimCopy, label, fleet)}
+ case b.Metrics.Layout.Mode != "nested":
+ return &doorRefusal{Status: http.StatusConflict, Msg: fmt.Sprintf(fileSeedFleetLayoutCopy, label, fleet)}
+ }
+ return nil
+}
+
+// fleetSeedHeldSentence is the delete door's 409 for an aborted fleet file
+// seed (plan R1-5). A seed with a held place gets FS-34, whose location the
+// console builds from the host and the held enum alone (decision D12;
+// FS-36, FS-37, FS-38): a box never supplies text a member reads. It keys
+// on Held, not on the reason, because a held copy is recorded whatever the
+// abort's reason (review round 2). Every other gets FS-33.
+func fleetSeedHeldSentence(host string, seed *provision.SeedSource) string {
+ replica := fmt.Sprintf(fileSeedHeldReplicaCopy, host)
+ staging := fmt.Sprintf(fileSeedHeldStagingCopy, host)
+ where := ""
+ switch seed.Held {
+ case provision.SeedHeldReplica:
+ where = replica
+ case provision.SeedHeldStaging:
+ where = staging
+ case provision.SeedHeldBoth:
+ where = fmt.Sprintf(fileSeedHeldBothCopy, replica, staging)
+ }
+ if where == "" {
+ return fmt.Sprintf(fileSeedHeldCopy, host)
+ }
+ return fmt.Sprintf(fileSeedHeldInStorageCopy, host, where)
+}
+
+// fleetSeedHoldError is a record retirement refused because the record is
+// a fleet file seed whose box has not proved it gone: the hold (fleet
+// seeded create design §3.6, Task 16 review P1-1). Msg is the delete
+// door's sentence for it (fleetSeedHeldSentence: FS-33, or FS-34 naming
+// where the copy is); each door answers it as its own 409, and the purge
+// as FS-35.
+type fleetSeedHoldError struct {
+ Host, Msg string
+}
+
+func (e *fleetSeedHoldError) Error() string {
+ return "console: " + e.Host + " is held by a fleet file seed: " + e.Msg
+}
+
+// fleetSeedHold is the hold's one predicate: nil unless rec is a fleet file
+// seed in any state but placed or rolled-back. Rolled-back is reached only
+// by the fleet seeds door's rolledback, after the box's proof, so the
+// finish (finishSeedOnce) passes and nothing before that proof does.
+//
+// It is enforced in the record retirement primitives every entrance funnels
+// through (retireRecordWithLifetimeLocked, with lifetimes on, and
+// retireHostRecord's legacy branch with them off), so an entrance nobody
+// listed still cannot release a held hostname. The app purges also ask it
+// first, through unfinishedFleetFileSeeds, so they refuse before any
+// teardown rather than midway.
+func fleetSeedHold(rec *provision.Record) error {
+ if rec == nil {
+ return nil
+ }
+ return fleetSeedHoldOf(rec.Host, rec.Region, rec.Seed)
+}
+
+// fleetSeedHoldRaw is fleetSeedHold asked of a record's body as stored,
+// for the retirement primitives (retireRecordWithLifetimeLocked,
+// retireLegacyInstanceRecord), which must hold even a body the record's
+// own decode rejects (slice 3 review P3-1). It decodes only the two fields
+// the hold reads, so a body that is otherwise stale or corrupt is still
+// classified. One that will not decode even that far is refused
+// (errFleetSeedUnclassified, fail closed) unless it plainly carries no
+// seed: every record with a seed is written with a "seed" member (its json
+// tag), so a body with no such text is no seed's, and the lifetimes'
+// cleanup of a corrupt body (lifetimes_retire.go, cases (d) and (g)) goes
+// on as before.
+func fleetSeedHoldRaw(host string, raw []byte) error {
+ var body struct {
+ Region string `json:"region"`
+ Seed *provision.SeedSource `json:"seed"`
+ }
+ if err := json.Unmarshal(raw, &body); err != nil {
+ if !bytes.Contains(raw, []byte(`"seed"`)) {
+ return nil
+ }
+ return fmt.Errorf("%w: %s: %v", errFleetSeedUnclassified, host, err)
+ }
+ return fleetSeedHoldOf(host, body.Region, body.Seed)
+}
+
+// errFleetSeedUnclassified is a retirement refused because the record's
+// body could not be read far enough to tell whether a fleet file seed holds
+// the hostname. Each door answers it as its ordinary failure.
+var errFleetSeedUnclassified = errors.New("console: the record could not be read to check for a fleet file seed")
+
+// fleetSeedHoldOf is fleetSeedHold asked of a record's three fields.
+func fleetSeedHoldOf(host, region string, seed *provision.SeedSource) error {
+ if _, fleet := registry.FleetPlacement(region); !fleet || seed == nil || seed.Kind != seeds.KindFile ||
+ seed.State == seeds.StatePlaced || seed.State == seeds.StateRolledBack {
+ return nil
+ }
+ return &fleetSeedHoldError{Host: host, Msg: fleetSeedHeldSentence(host, seed)}
+}
+
+// unfinishedFleetFileSeeds names, sorted, the hosts of sqid/app whose record
+// is a fleet file seed in any state but placed or rolled-back (plan R1-1):
+// a hostname its box has not yet proved free (design §3.6). Every entrance
+// that retires the app's records or deletes its keys (the Trash page's
+// purge, the expiry pass's early purge, the trash sweep) asks it before any
+// destructive work, and refuses while it names any host, with FS-35
+// (fleetSeedPurgeRefusal). It reads strictly: a record that will not decode,
+// a listing it cannot finish or one past instanceListMax is an error, and
+// the caller refuses on it too (fail closed). Once the box reports
+// rolledback and the record is finished, the host is no longer named.
+func (s *Server) unfinishedFleetFileSeeds(ctx context.Context, sqid, app string) ([]string, error) {
+ recs, unreadable, err := s.listRecordsStrict(ctx, sqid, app, instanceListMax)
+ if err != nil {
+ return nil, fmt.Errorf("list the instances of %s/%s: %w", sqid, app, err)
+ }
+ if len(unreadable) > 0 {
+ return nil, fmt.Errorf("list the instances of %s/%s: %d records could not be read", sqid, app, len(unreadable))
+ }
+ var hosts []string
+ for i := range recs {
+ rec := &recs[i]
+ if fleetSeedHold(rec) != nil {
+ hosts = append(hosts, rec.Host)
+ }
+ }
+ sort.Strings(hosts)
+ return hosts, nil
+}
+
+// fleetSeedPurgeRefusal is the purge entrances' check, before any
+// destructive work: "" to go ahead, else the sentence that refuses (FS-35,
+// naming the held hosts). An error reading the records refuses too, with
+// err set for the caller to log or answer in its own words.
+func (s *Server) fleetSeedPurgeRefusal(ctx context.Context, sqid, app string) (string, error) {
+ hosts, err := s.unfinishedFleetFileSeeds(ctx, sqid, app)
+ if err != nil {
+ return "", err
+ }
+ if len(hosts) == 0 {
+ return "", nil
+ }
+ return fmt.Sprintf(fileSeedPurgeHeldCopy, app, strings.Join(hosts, ", ")), nil
+}
+
+// fleetSeedHoldRefusal is a door's answer to the hold: a 409 with the held
+// sentence, and ok, when err is a fleetSeedHoldError.
+func fleetSeedHoldRefusal(err error) (*doorRefusal, bool) {
+ var held *fleetSeedHoldError
+ if !errors.As(err, &held) {
+ return nil, false
+ }
+ return &doorRefusal{Status: http.StatusConflict, Msg: held.Msg}, true
+}
+
+// fleetSeedTrashRefusal is the trash entrances' check (slice 3 review
+// P2-1), under the app lock and before anything is written: "" to go
+// ahead, else FS-39 naming the hosts whose fleet file seed is unfinished.
+// A box skips every record of a trashed app (provision reconcile), so a
+// seed trashed before its box proved it gone would never be rolled back,
+// and the app's purge would refuse it (FS-35) for ever. The member deletes
+// the instance first: that aborts it, the box rolls it back, the finish
+// frees it, and then the trash goes through. An error reading the records
+// refuses too, with err set.
+//
+// A trashed app that already holds one cannot exist: fleet file seeds
+// first ship with this check (#1139 slice 3), so no app was trashed
+// holding one before it.
+func (s *Server) fleetSeedTrashRefusal(ctx context.Context, sqid, app string) (string, error) {
+ hosts, err := s.unfinishedFleetFileSeeds(ctx, sqid, app)
+ if err != nil {
+ return "", err
+ }
+ if len(hosts) == 0 {
+ return "", nil
+ }
+ return fmt.Sprintf(fileSeedTrashHeldCopy, app, strings.Join(hosts, ", ")), nil
+}
diff --git a/internal/console/seedfile_copy.go b/internal/console/seedfile_copy.go
index c921b57f1..64d036e1a 100644
--- a/internal/console/seedfile_copy.go
+++ b/internal/console/seedfile_copy.go
@@ -18,9 +18,58 @@ const (
fileSeedMismatchCopy = "the upload does not match the file this create began with, so it was not kept."
// FS-20: %s is the app.
fileSeedPoolCopy = "%s places its instances in a pool, so it cannot take a seeded instance."
+ // FS-21: %s is the fleet. A file seed's record is created unlabelled,
+ // so its fleet must have one active box to own it (decision D8).
+ fileSeedFleetBoxesCopy = "fleet %s has more than one active box. A seeded instance needs a fleet with one active box for now."
+ // FS-22: %s is the fleet. A 503: a box with no fresh, whole heartbeat,
+ // or none active; the log names the box.
+ fileSeedFleetUnconfirmedCopy = "could not confirm every box in fleet %s. Try again in a minute."
+ // FS-23: %s is the boxes, then the fleet.
+ fileSeedFleetBelowFloorCopy = "the platform on %s in fleet %s is below the seeds floor. Update it, then try again."
+ // FS-24: %s is the boxes, then the fleet.
+ fileSeedFleetClaimCopy = "claim control is on for %s in fleet %s. Seeded instances are not supported there yet."
+ // FS-26: %s is the boxes, then the fleet. Shown for any box whose
+ // layout is not nested (decision D13).
+ fileSeedFleetLayoutCopy = "%s in fleet %s keeps all its instances in one shared directory. A seed file needs a box that keeps each instance in its own."
// FS-25: capital T, as its sibling SD-N3.
fileSeedFloorCopy = "This deployment’s seeds floor does not allow seed files yet. An operator publishes it again with carlos system seeds-floor publish."
+ // FS-27 to FS-30: the reason a fleet file seed's record keeps, mapped
+ // from the code its box reports to the fleet seeds door
+ // (apifleetseeds.go; the box sends no text, decision D4).
+ // FS-27, code mismatch.
+ fileSeedBoxMismatchCopy = "the seed file on the box did not match the upload"
+ // FS-28, code not-a-database.
+ fileSeedBoxIntegrityCopy = "the seed file on the box failed its integrity check"
+ // FS-29, code copy-exists.
+ fileSeedCopyExistsCopy = "a copy of data already exists for this hostname"
+ // FS-30, code copy-in-storage; the record keeps where (held) beside it.
+ fileSeedCopyInStorageCopy = "a copy of its data is still in the fleet’s storage"
+
+ // FS-33: %s is the host. The delete door's 409 for an aborted fleet
+ // file seed whose box has not yet proved it clean.
+ fileSeedHeldCopy = "%s was not created. Its hostname is free again once its box has cleaned up."
+ // FS-34: %s is the host, then the location (FS-36, FS-37 or FS-38).
+ // The delete door's 409 for FS-30 with a held place (decision D12).
+ fileSeedHeldInStorageCopy = "%s keeps its hostname while a copy of its data is still in the fleet’s storage, under %s. Remove everything there, and the hostname is free again after the box’s next pass."
+ // FS-36: held replica; %s is the host. The box's CARLOS_HIBERNATE_PREFIX
+ // goes before it, if set: the console never sees that prefix.
+ fileSeedHeldReplicaCopy = "%s/ (after the box’s CARLOS_HIBERNATE_PREFIX, if set)"
+ // FS-37: held staging; %s is the host.
+ fileSeedHeldStagingCopy = "moves/%s/"
+ // FS-38: held both; FS-36, then FS-37.
+ fileSeedHeldBothCopy = "%s and %s"
+ // FS-35: %s is the app, then the hosts. The Trash page's "Delete now"
+ // and the trash sweeps' log, while a fleet file seed holds a hostname.
+ fileSeedPurgeHeldCopy = "%s can’t be deleted permanently until its fleet box has cleaned up %s."
+
+ // FS-39 (approved, Paul 2026-11-20; slice 3 review P2-1): %s is the app,
+ // then the hosts. The trash doors' refusal, and the expiry pass's log,
+ // while a fleet file seed holds a hostname: a trashed app's records are
+ // skipped by its box, so a seed trashed unfinished could never be
+ // rolled back, and the app never purged.
+ fileSeedTrashHeldCopy = "%s can’t be moved to the trash until its fleet box has cleaned up %s. Delete each with carlos instances delete, then try again."
+
// FS-41: an import object whose kind is neither absent nor "file". Only a hand-written API call reaches it; the CLI sends one or
// the other.
fileSeedKindCopy = "kind must be file, or left out for an import"
diff --git a/internal/console/seedfile_test.go b/internal/console/seedfile_test.go
index 7ec5a2768..511f408c5 100644
--- a/internal/console/seedfile_test.go
+++ b/internal/console/seedfile_test.go
@@ -139,6 +139,7 @@ func TestFileSeedUploadMismatchAborts(t *testing.T) {
mk func(*testing.T) fromFixture
}{
{"region", newFileSeedFixture},
+ {"fleet", newFleetFileFixture},
} {
t.Run(row.name, func(t *testing.T) {
f := row.mk(t)
@@ -154,6 +155,7 @@ func TestFileSeedUploadMismatchAborts(t *testing.T) {
}
requireFileState(t, rec, begun.Seed.ID, seeds.StateAborted, fileSeedMismatchCopy)
f.requireNothingUploaded(t)
+ f.requireNoFleetSnapshot(t)
f.requireClean(t)
// The right file now is refused: the seed has gone.
if code, out := uploadImport(t, f, fileHost, body); code != http.StatusConflict ||
@@ -196,7 +198,8 @@ func TestFileSeedRefusesPool(t *testing.T) {
}
// fleetSeedCreate posts body for shop on a fleet-placed world and requires
-// the --from and import placement refusal, with nothing written.
+// the --from and import placement refusal, with nothing written. A file
+// seed is admitted on a fleet since slice 3 (seedfilefleet_test.go).
func fleetSeedCreate(t *testing.T, body string) {
t.Helper()
fx, token, reg := d1World(t, "code-fs-fleet", "pi-1")
@@ -211,10 +214,6 @@ func fleetSeedCreate(t *testing.T, body string) {
}
}
-func TestFileSeedRefusesFleetUntilSlice3(t *testing.T) {
- fleetSeedCreate(t, fileSeedBody("b.example.com", importSHA, 10))
-}
-
func TestFromOnFleetStillRefuses(t *testing.T) {
fleetSeedCreate(t, `{"host":"b.example.com","from":{"host":"a.example.com"}}`)
}
diff --git a/internal/console/seedfilefleet_test.go b/internal/console/seedfilefleet_test.go
new file mode 100644
index 000000000..6eb365be0
--- /dev/null
+++ b/internal/console/seedfilefleet_test.go
@@ -0,0 +1,602 @@
+package console
+
+import (
+ "bytes"
+ "context"
+ "errors"
+ "fmt"
+ "net/http"
+ "os"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/provision"
+ "github.com/carlosframework/platform/internal/registry"
+ "github.com/carlosframework/platform/internal/release"
+ "github.com/carlosframework/platform/internal/seeds"
+ "github.com/carlosframework/platform/internal/status"
+)
+
+// File seeds on a customer fleet (#1139 slice 3, plan Task 16): begin,
+// upload, readiness, sweep, finish, delete and every retirement entrance.
+
+const seedFleet = "pi"
+
+// newFleetFileFixture is the file seed world with shop placed on bab's
+// fleet pi: one active box pi-1, whose fresh, nested heartbeat reports the
+// fleet protocol, and the seeds floor at the fleet protocol.
+func newFleetFileFixture(t *testing.T) fromFixture {
+ t.Helper()
+ f := newImportFixture(t)
+ if err := seeds.PublishFloor(context.Background(), f.fx.rel, seeds.Floor{Min: seeds.FleetFileSeedProtocol, MinRelease: "v0.27.0"}); err != nil {
+ t.Fatal(err)
+ }
+ reg, err := openRegistry(f.fx.regPath)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if ok, err := reg.CreateFleet(registry.Fleet{Name: seedFleet, Account: "bab", Bucket: "pi-data"}); err != nil || !ok {
+ t.Fatalf("create fleet: %v %v", ok, err)
+ }
+ if err := reg.AddFleetBox(registry.FleetBox{Fleet: seedFleet, Label: "pi-1", TokenHash: strings.Repeat("a", 64)}); err != nil {
+ t.Fatal(err)
+ }
+ fleetSeedBeat(t, f.fx, "pi-1", nil)
+ if err := f.fx.st.SetAppPlacement(OpsAccountID, fromApp, "fleet/"+seedFleet); err != nil {
+ t.Fatal(err)
+ }
+ return f
+}
+
+// fleetSeedBeat writes label's heartbeat on fleet pi: fresh, nested, at the
+// fleet protocol and the floor's min_release, then mut.
+func fleetSeedBeat(t *testing.T, fx *consoleFixture, label string, mut func(*status.Box)) {
+ t.Helper()
+ b := status.Box{GeneratedAt: time.Now(), Label: label, Metrics: &status.BoxMetrics{
+ Layout: &status.LayoutReport{Mode: "nested"}, Release: "v0.27.0", PrevRelease: "none",
+ SeedsFloor: &status.SeedsFloorReport{Protocol: seeds.FleetFileSeedProtocol, MinRelease: "v0.27.0"}}}
+ if mut != nil {
+ mut(&b)
+ }
+ if err := status.WriteBox(context.Background(), release.NewPrefixStore(fx.rel, "fleets/"+seedFleet+"/"), b); err != nil {
+ t.Fatal(err)
+ }
+}
+
+func fleetSnapshotOf(host, id string) string { return seeds.FleetSnapshotKey("bab", fromApp, host, id) }
+
+func (f fromFixture) hasKey(t *testing.T, key string) bool {
+ t.Helper()
+ _, _, err := f.fx.srv.cfg.Releases.Get(context.Background(), key)
+ if err != nil && !errors.Is(err, os.ErrNotExist) {
+ t.Fatal(err)
+ }
+ return err == nil
+}
+
+// requireNoFleetSnapshot: nothing under shop's fleet seeds prefix.
+func (f fromFixture) requireNoFleetSnapshot(t *testing.T) {
+ t.Helper()
+ if keys, err := f.fx.rel.List(context.Background(), seeds.FleetSnapshotsPrefix("bab", fromApp)); err != nil || len(keys) != 0 {
+ t.Fatalf("fleet seeds = %v, %v; want none", keys, err)
+ }
+}
+
+// fleetSeedRecord writes a fleet-placed record of shop on host whose file
+// seed is in state, with reason and held, and puts its fleet snapshot. It
+// answers the id.
+func (f fromFixture) fleetSeedRecord(t *testing.T, host, state, reason, held string, at time.Time) string {
+ t.Helper()
+ id := newSeedID(t)
+ rec := provision.Record{Schema: 1, Host: host, Slug: strings.SplitN(host, ".", 2)[0], App: fromApp, Account: "bab",
+ Channel: "stable", Region: "fleet/" + seedFleet, CreatedAt: time.Now().UTC(),
+ Seed: &provision.SeedSource{ID: id, Kind: seeds.KindFile, State: state, Reason: reason, Held: held,
+ SHA256: strings.Repeat("a", 64), Bytes: 4, By: "alice@keymail.dev", At: at}}
+ if err := provision.CreateRecord(context.Background(), f.fx.rel, rec); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := f.fx.rel.Put(context.Background(), fleetSnapshotOf(host, id), []byte("snap"), ""); err != nil {
+ t.Fatal(err)
+ }
+ return id
+}
+
+func (f fromFixture) rawRecord(t *testing.T, host string) []byte {
+ t.Helper()
+ raw, _, err := f.fx.rel.Get(context.Background(), provision.RecordKey("bab", fromApp, host))
+ if err != nil && !errors.Is(err, os.ErrNotExist) {
+ t.Fatal(err)
+ }
+ return raw
+}
+
+func TestFileSeedBeginFleetWritesDeploymentKey(t *testing.T) {
+ f := newFleetFileFixture(t)
+ body, _ := sqliteBytes(t)
+ begun := f.beginFile(t, fileHost, body)
+ // No replica assignment either (review P3-4): the seeds door refuses a
+ // file seed's record that carries one, so the create must never write
+ // one.
+ if begun.Region != "fleet/"+seedFleet || begun.FleetBox != "" || begun.ReplicaAssignment != nil {
+ t.Fatalf("record placed %q labelled %q assigned %+v; want fleet/pi, unlabelled, unassigned", begun.Region, begun.FleetBox, begun.ReplicaAssignment)
+ }
+ id := begun.Seed.ID
+ requireFileState(t, begun, id, seeds.StateReserving, "")
+ rec := f.uploaded(t, fileHost, body)
+ requireFileState(t, rec, id, seeds.StateReady, "")
+ if rec.ReplicaAssignment != nil {
+ t.Fatalf("the upload assigned replicas: %+v", rec.ReplicaAssignment)
+ }
+ got, _, err := f.fx.rel.Get(context.Background(), seeds.FleetSnapshotKey("bab", fromApp, fileHost, id))
+ if err != nil || !bytes.Equal(got, body) {
+ t.Fatalf("fleet snapshot = %d bytes, %v; want the upload", len(got), err)
+ }
+ f.requireNothingUploaded(t) // nothing in the data bucket
+ f.requireClean(t)
+}
+
+// R2-2: one storage prerequisite. Begin and upload agree for every kind and
+// storage shape, and a fleet file seed needs nothing regional.
+func TestSeedStoragePrereqBeginMatchesUpload(t *testing.T) {
+ f := newImportFixture(t)
+ s := f.fx.srv
+ data, rel := s.cfg.SeedData, s.cfg.Releases
+ for _, c := range []struct {
+ kind, placement string
+ data, bucket bool
+ want bool // refused
+ }{
+ {seeds.KindImport, "", true, true, false},
+ {seeds.KindImport, "", false, true, true},
+ {seeds.KindImport, "", true, false, true},
+ {seeds.KindFile, "", true, true, false},
+ {seeds.KindFile, "", false, true, true},
+ {seeds.KindFile, "", true, false, true},
+ {seeds.KindFile, "fleet/pi", true, true, false},
+ {seeds.KindFile, "fleet/pi", false, false, false},
+ {seeds.KindImport, "fleet/pi", false, true, true},
+ } {
+ s.cfg.SeedData, s.cfg.HibernateBucket = nil, ""
+ if c.data {
+ s.cfg.SeedData = data
+ }
+ if c.bucket {
+ s.cfg.HibernateBucket = "data-test"
+ }
+ // Begin and the upload both ask seedStorageRefusal, and nothing
+ // else asks about storage: the same question, the same answer.
+ ref := s.seedStorageRefusal(c.kind, c.placement)
+ if (ref != nil) != c.want {
+ t.Errorf("%s on %q (data %v, bucket %v): refused %v, want %v", c.kind, c.placement, c.data, c.bucket, ref != nil, c.want)
+ }
+ if ref != nil && *ref != *seedNoDataRefusal() {
+ t.Errorf("%s on %q: %+v, want the import's refusal", c.kind, c.placement, ref)
+ }
+ }
+ s.cfg.Releases = nil
+ if s.seedStorageRefusal(seeds.KindFile, "fleet/pi") == nil {
+ t.Error("a fleet file seed with no deployment bucket was admitted")
+ }
+ s.cfg.Releases, s.cfg.SeedData, s.cfg.HibernateBucket = rel, data, "data-test"
+
+ // End to end: a fleet file seed goes from begin through its PUT to
+ // ready with no data bucket at all.
+ g := newFleetFileFixture(t)
+ g.fx.srv.cfg.SeedData, g.fx.srv.cfg.HibernateBucket = nil, ""
+ body, _ := sqliteBytes(t)
+ begun := g.beginFile(t, fileHost, body)
+ requireFileState(t, g.uploaded(t, fileHost, body), begun.Seed.ID, seeds.StateReady, "")
+ if !g.hasKey(t, fleetSnapshotOf(fileHost, begun.Seed.ID)) {
+ t.Fatal("no fleet snapshot")
+ }
+}
+
+// R3-1: a claim-enabled console admits no fleet file seed, at begin or PUT.
+func TestFileSeedFleetClaimConsoleRefuses(t *testing.T) {
+ f := newFleetFileFixture(t)
+ body, _ := sqliteBytes(t)
+ begun := f.beginFile(t, fileHost, body)
+ claim := seedClaimConsoleRefusal().Msg
+ f.fx.srv.cfg.HostClaim = true
+ if code, out := uploadImport(t, f, fileHost, body); code != http.StatusConflict || str(t, out, "error") != claim {
+ t.Fatalf("PUT on a claim console = %d %v", code, out)
+ }
+ rec, _ := f.record(t, fileHost)
+ requireFileState(t, rec, begun.Seed.ID, seeds.StateReserving, "")
+ f.requireNoFleetSnapshot(t)
+ // Asked first, before any fleet check: a fleet that is not ready at
+ // all still gets the claim sentence.
+ if ref := f.fx.srv.seedFleetReady(context.Background(), "nowhere"); ref == nil || ref.Msg != claim {
+ t.Fatalf("seedFleetReady on a claim console = %+v", ref)
+ }
+ if code, out := f.create(t, fileSeedBody("other.shop.example.com", importSHA, 10)); code != http.StatusConflict || str(t, out, "error") != claim {
+ t.Fatalf("begin on a claim console = %d %v", code, out)
+ }
+ f.requireNoRecord(t, "other.shop.example.com")
+ f.requireNoFleetSnapshot(t)
+}
+
+func TestSeedFleetReadyNamesBoxes(t *testing.T) {
+ f := newFleetFileFixture(t)
+ ctx := context.Background()
+ if ref := f.fx.srv.seedFleetReady(ctx, seedFleet); ref != nil {
+ t.Fatalf("a ready fleet: %+v", ref)
+ }
+ unconfirmed := fmt.Sprintf(fileSeedFleetUnconfirmedCopy, seedFleet)
+ below := fmt.Sprintf(fileSeedFleetBelowFloorCopy, "pi-1", seedFleet)
+ for _, c := range []struct {
+ what string
+ mut func(*status.Box)
+ status int
+ msg string
+ }{
+ {"no seeds_floor", func(b *status.Box) { b.Metrics.SeedsFloor = nil }, http.StatusServiceUnavailable, unconfirmed},
+ {"no layout", func(b *status.Box) { b.Metrics.Layout = nil }, http.StatusServiceUnavailable, unconfirmed},
+ {"no metrics", func(b *status.Box) { b.Metrics = nil }, http.StatusServiceUnavailable, unconfirmed},
+ {"protocol 3", func(b *status.Box) { b.Metrics.SeedsFloor.Protocol = seeds.FileSeedProtocol }, http.StatusConflict, below},
+ {"another min_release", func(b *status.Box) { b.Metrics.SeedsFloor.MinRelease = "v0.26.0" }, http.StatusConflict, below},
+ {"carlos.prev not vouched", func(b *status.Box) { b.Metrics.PrevRelease = "v0.20.0" }, http.StatusConflict, below},
+ {"root floor refused", func(b *status.Box) { b.Metrics.SeedsFloor.FloorState = "refused" }, http.StatusConflict, below},
+ {"flat", func(b *status.Box) { b.Metrics.Layout.Mode = "flat" }, http.StatusConflict, fmt.Sprintf(fileSeedFleetLayoutCopy, "pi-1", seedFleet)},
+ {"layout unknown", func(b *status.Box) { b.Metrics.Layout.Mode = "" }, http.StatusConflict, fmt.Sprintf(fileSeedFleetLayoutCopy, "pi-1", seedFleet)},
+ } {
+ fleetSeedBeat(t, f.fx, "pi-1", c.mut)
+ if ref := f.fx.srv.seedFleetReady(ctx, seedFleet); ref == nil || ref.Status != c.status || ref.Msg != c.msg {
+ t.Errorf("%s: %+v, want %d %q", c.what, ref, c.status, c.msg)
+ }
+ }
+ // carlos.prev vouched for the floor's release is fine.
+ fleetSeedBeat(t, f.fx, "pi-1", func(b *status.Box) { b.Metrics.PrevRelease, b.Metrics.SeedsFloor.PrevAllowedFor = "v0.20.0", "v0.27.0" })
+ if ref := f.fx.srv.seedFleetReady(ctx, seedFleet); ref != nil {
+ t.Fatalf("a vouched carlos.prev: %+v", ref)
+ }
+ // A floor below the fleet protocol is FS-25.
+ fleetSeedBeat(t, f.fx, "pi-1", nil)
+ _, etag, err := f.fx.rel.Get(ctx, seeds.FloorKey)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := f.fx.rel.Put(ctx, seeds.FloorKey, []byte(`{"min":3,"min_release":"v0.27.0"}`), etag); err != nil {
+ t.Fatal(err)
+ }
+ if ref := f.fx.srv.seedFleetReady(ctx, seedFleet); ref == nil || ref.Status != http.StatusConflict || ref.Msg != fileSeedFloorCopy {
+ t.Fatalf("a floor at the region file protocol: %+v", ref)
+ }
+}
+
+func TestSeedFleetReadyStaleHeartbeat(t *testing.T) {
+ f := newFleetFileFixture(t)
+ fleetSeedBeat(t, f.fx, "pi-1", func(b *status.Box) { b.GeneratedAt = time.Now().Add(-time.Hour) })
+ if ref := f.fx.srv.seedFleetReady(context.Background(), seedFleet); ref == nil || ref.Status != http.StatusServiceUnavailable ||
+ ref.Msg != fmt.Sprintf(fileSeedFleetUnconfirmedCopy, seedFleet) {
+ t.Fatalf("a stale heartbeat: %+v", ref)
+ }
+}
+
+func TestSeedFleetReadyRefusesTwoActiveBoxes(t *testing.T) {
+ f := newFleetFileFixture(t)
+ reg, _ := openRegistry(f.fx.regPath)
+ if err := reg.AddFleetBox(registry.FleetBox{Fleet: seedFleet, Label: "pi-2", TokenHash: strings.Repeat("b", 64)}); err != nil {
+ t.Fatal(err)
+ }
+ fleetSeedBeat(t, f.fx, "pi-2", nil)
+ ctx := context.Background()
+ if ref := f.fx.srv.seedFleetReady(ctx, seedFleet); ref == nil || ref.Status != http.StatusConflict || ref.Msg != fmt.Sprintf(fileSeedFleetBoxesCopy, seedFleet) {
+ t.Fatalf("two active boxes: %+v", ref)
+ }
+ // A detached box does not count; no active box at all is FS-22.
+ if err := reg.SetFleetBoxStatus(seedFleet, "pi-2", "detached"); err != nil {
+ t.Fatal(err)
+ }
+ if ref := f.fx.srv.seedFleetReady(ctx, seedFleet); ref != nil {
+ t.Fatalf("one active box and one detached: %+v", ref)
+ }
+ if err := reg.SetFleetBoxStatus(seedFleet, "pi-1", "detached"); err != nil {
+ t.Fatal(err)
+ }
+ if ref := f.fx.srv.seedFleetReady(ctx, seedFleet); ref == nil || ref.Status != http.StatusServiceUnavailable {
+ t.Fatalf("no active box: %+v", ref)
+ }
+ // And the begin refuses before writing anything.
+ if err := reg.SetFleetBoxStatus(seedFleet, "pi-1", "active"); err != nil {
+ t.Fatal(err)
+ }
+ if err := reg.SetFleetBoxStatus(seedFleet, "pi-2", "active"); err != nil {
+ t.Fatal(err)
+ }
+ if code, out := f.create(t, fileSeedBody(fileHost, importSHA, 10)); code != http.StatusConflict || str(t, out, "error") != fmt.Sprintf(fileSeedFleetBoxesCopy, seedFleet) {
+ t.Fatalf("begin on a two-box fleet = %d %v", code, out)
+ }
+ f.requireNoRecord(t, fileHost)
+}
+
+func TestSeedFleetReadyRefusesClaimControl(t *testing.T) {
+ f := newFleetFileFixture(t)
+ fleetSeedBeat(t, f.fx, "pi-1", func(b *status.Box) { b.Metrics.HostClaimEnabled = true })
+ if ref := f.fx.srv.seedFleetReady(context.Background(), seedFleet); ref == nil || ref.Status != http.StatusConflict ||
+ ref.Msg != fmt.Sprintf(fileSeedFleetClaimCopy, "pi-1", seedFleet) {
+ t.Fatalf("a claim-control box: %+v", ref)
+ }
+}
+
+// Decision D13: a flat fleet box takes no file seed. (The plan's
+// TestSeedFleetReadyAdmitsFlat predates D13; this is its replacement.)
+func TestSeedFleetReadyRefusesFlat(t *testing.T) {
+ f := newFleetFileFixture(t)
+ fleetSeedBeat(t, f.fx, "pi-1", func(b *status.Box) { b.Metrics.Layout.Mode = "flat" })
+ if code, out := f.create(t, fileSeedBody(fileHost, importSHA, 10)); code != http.StatusConflict ||
+ str(t, out, "error") != fmt.Sprintf(fileSeedFleetLayoutCopy, "pi-1", seedFleet) {
+ t.Fatalf("begin on a flat box = %d %v", code, out)
+ }
+ f.requireNoRecord(t, fileHost)
+}
+
+// D9: a delete before placement aborts; then, while the record holds the
+// hostname, every delete is refused.
+func TestDeleteFleetFileSeedBeforePlacementAborts(t *testing.T) {
+ for _, ready := range []bool{false, true} {
+ f := newFleetFileFixture(t)
+ body, _ := sqliteBytes(t)
+ begun := f.beginFile(t, fileHost, body)
+ if ready {
+ f.uploaded(t, fileHost, body)
+ }
+ code, out := deleteInstance(t, f, fileHost)
+ if code != http.StatusAccepted || out["state"] != "aborting" || out["message"] != fmt.Sprintf(fileSeedDeletingCopy, fileHost) {
+ t.Fatalf("ready %v: delete = %d %v, want 202 FS-13", ready, code, out)
+ }
+ rec, err := f.record(t, fileHost)
+ if err != nil {
+ t.Fatalf("ready %v: the record went: %v", ready, err)
+ }
+ requireFileState(t, rec, begun.Seed.ID, seeds.StateAborted, "")
+ before := f.rawRecord(t, fileHost)
+ if code, out := deleteInstance(t, f, fileHost); code != http.StatusConflict || str(t, out, "error") != fmt.Sprintf(fileSeedHeldCopy, fileHost) {
+ t.Fatalf("ready %v: second delete = %d %v, want 409 FS-33", ready, code, out)
+ }
+ if !bytes.Equal(before, f.rawRecord(t, fileHost)) {
+ t.Fatalf("ready %v: the second delete changed the record", ready)
+ }
+ }
+}
+
+func TestDeleteHeldFleetFileSeedRefuses(t *testing.T) {
+ f := newFleetFileFixture(t)
+ held := func(where string) string {
+ return fmt.Sprintf(fileSeedHeldInStorageCopy, fileHost, where)
+ }
+ replica := fmt.Sprintf(fileSeedHeldReplicaCopy, fileHost)
+ staging := fmt.Sprintf(fileSeedHeldStagingCopy, fileHost)
+ for _, c := range []struct {
+ what, reason, held, want string
+ }{
+ {"no reason", "", "", fmt.Sprintf(fileSeedHeldCopy, fileHost)},
+ {"FS-27", fileSeedBoxMismatchCopy, "", fmt.Sprintf(fileSeedHeldCopy, fileHost)},
+ {"FS-28", fileSeedBoxIntegrityCopy, "", fmt.Sprintf(fileSeedHeldCopy, fileHost)},
+ {"FS-29", fileSeedCopyExistsCopy, "", fmt.Sprintf(fileSeedHeldCopy, fileHost)},
+ {"FS-30 replica", fileSeedCopyInStorageCopy, provision.SeedHeldReplica, held(replica)},
+ {"FS-30 staging", fileSeedCopyInStorageCopy, provision.SeedHeldStaging, held(staging)},
+ {"FS-30 both", fileSeedCopyInStorageCopy, provision.SeedHeldBoth, held(fmt.Sprintf(fileSeedHeldBothCopy, replica, staging))},
+ {"FS-30 with no held", fileSeedCopyInStorageCopy, "", fmt.Sprintf(fileSeedHeldCopy, fileHost)},
+ {"an upload failure", importNotADB, "", fmt.Sprintf(fileSeedHeldCopy, fileHost)},
+ {"FS-17", fileSeedMismatchCopy, "", fmt.Sprintf(fileSeedHeldCopy, fileHost)},
+ {"FS-17 with a held copy", fileSeedMismatchCopy, provision.SeedHeldReplica, held(replica)},
+ {"an upload failure with a held copy", importNotADB, provision.SeedHeldBoth, held(fmt.Sprintf(fileSeedHeldBothCopy, replica, staging))},
+ } {
+ f.fleetSeedRecord(t, fileHost, seeds.StateAborted, c.reason, c.held, time.Now())
+ before := f.rawRecord(t, fileHost)
+ if code, out := deleteInstance(t, f, fileHost); code != http.StatusConflict || str(t, out, "error") != c.want {
+ t.Errorf("%s: delete = %d %v, want 409 %q", c.what, code, out, c.want)
+ }
+ if !bytes.Equal(before, f.rawRecord(t, fileHost)) {
+ t.Errorf("%s: the record changed", c.what)
+ }
+ if err := f.fx.rel.Delete(context.Background(), provision.RecordKey("bab", fromApp, fileHost)); err != nil {
+ t.Fatal(err)
+ }
+ }
+ // The examples' wording, end to end, for the reviewer's eye.
+ if got := held(replica); got != "push.shop.example.com keeps its hostname while a copy of its data is still in the fleet’s storage, under push.shop.example.com/ (after the box’s CARLOS_HIBERNATE_PREFIX, if set). Remove everything there, and the hostname is free again after the box’s next pass." {
+ t.Fatalf("FS-34 with FS-36 = %q", got)
+ }
+}
+
+// Rolled back (the door's word, after the box's proof) the delete finishes
+// it; placed, it is the ordinary delete.
+func TestDeleteFleetFileSeedRolledBackFinishesPlacedIsOrdinary(t *testing.T) {
+ f := newFleetFileFixture(t)
+ f.fx.srv.cfg.SeedData = nil
+ id := f.fleetSeedRecord(t, fileHost, seeds.StateRolledBack, "", "", time.Now())
+ if code, out := deleteInstance(t, f, fileHost); code != http.StatusOK || out["result"] != "deleted" {
+ t.Fatalf("rolled back: delete = %d %v", code, out)
+ }
+ f.requireNoRecord(t, fileHost)
+ if f.hasKey(t, fleetSnapshotOf(fileHost, id)) {
+ t.Fatal("the finish left the fleet snapshot")
+ }
+ f.fleetSeedRecord(t, "placed.shop.example.com", seeds.StatePlaced, "", "", time.Now())
+ if code, out := deleteInstance(t, f, "placed.shop.example.com"); code != http.StatusOK || out["result"] != "deleted" {
+ t.Fatalf("placed: delete = %d %v", code, out)
+ }
+ f.requireNoRecord(t, "placed.shop.example.com")
+}
+
+func TestDeleteRegionFileSeedIsOrdinary(t *testing.T) {
+ f := newFileSeedFixture(t)
+ body, _ := sqliteBytes(t)
+ f.beginFile(t, fileHost, body)
+ f.uploaded(t, fileHost, body)
+ if code, out := deleteInstance(t, f, fileHost); code != http.StatusOK || out["result"] != "deleted" {
+ t.Fatalf("delete = %d %v, want the ordinary 200", code, out)
+ }
+ f.requireNoRecord(t, fileHost)
+}
+
+func TestFinishFleetFileSeedUsesDeploymentKey(t *testing.T) {
+ f := newFleetFileFixture(t)
+ f.fx.srv.cfg.SeedData, f.fx.srv.cfg.HibernateBucket = nil, ""
+ id := f.fleetSeedRecord(t, fileHost, seeds.StateRolledBack, "", "", time.Now())
+ if err := f.fx.srv.finishSeed(context.Background(), "bab", fromApp, fileHost, id); err != nil {
+ t.Fatal(err)
+ }
+ f.requireNoRecord(t, fileHost)
+ if f.hasKey(t, fleetSnapshotOf(fileHost, id)) {
+ t.Fatal("the fleet snapshot survived the finish")
+ }
+}
+
+// ---- the sweep ----------------------------------------------------------
+
+// modReleases gives the fixture's deployment store last-modified listings:
+// every key is as old as mods says, or new.
+type modReleases struct {
+ release.Store
+ mu sync.Mutex
+ mods map[string]time.Time
+}
+
+func (m *modReleases) ListMod(ctx context.Context, prefix string) ([]release.KeyMod, error) {
+ keys, err := m.Store.List(ctx, prefix)
+ if err != nil {
+ return nil, err
+ }
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ out := make([]release.KeyMod, 0, len(keys))
+ for _, k := range keys {
+ mod, ok := m.mods[k]
+ if !ok {
+ mod = time.Now()
+ }
+ out = append(out, release.KeyMod{Key: k, Mod: mod})
+ }
+ return out, nil
+}
+
+// sweepable arms the fixture's deployment store for the sweep's fleet half.
+func (f fromFixture) sweepable() {
+ f.fx.srv.cfg.Releases = &modReleases{Store: f.fx.srv.cfg.Releases, mods: map[string]time.Time{}}
+}
+
+func (f fromFixture) state(t *testing.T, host string) string {
+ t.Helper()
+ rec, err := f.record(t, host)
+ if errors.Is(err, os.ErrNotExist) {
+ return "gone"
+ }
+ if err != nil {
+ t.Fatal(err)
+ }
+ return rec.Seed.State
+}
+
+// R3-3: the snapshot goes on abandonment, the record stays.
+func TestSeedsPassDeletesAbortedFleetFileSnapshotKeepsRecord(t *testing.T) {
+ f := newFleetFileFixture(t)
+ f.sweepable()
+ id := f.fleetSeedRecord(t, fileHost, seeds.StateAborted, fileSeedCopyInStorageCopy, provision.SeedHeldReplica, time.Now())
+ f.fx.srv.seedsPass(context.Background(), time.Now())
+ if f.hasKey(t, fleetSnapshotOf(fileHost, id)) {
+ t.Fatal("an aborted fleet file seed's snapshot survived the sweep")
+ }
+ if got := f.state(t, fileHost); got != seeds.StateAborted {
+ t.Fatalf("record = %s, want it kept aborted", got)
+ }
+}
+
+// R1-4: a trashed app's snapshots are swept too.
+func TestSeedsPassDeletesAbortedFleetFileSnapshotInTrashedApp(t *testing.T) {
+ f := newFleetFileFixture(t)
+ f.sweepable()
+ id := f.fleetSeedRecord(t, fileHost, seeds.StateAborted, "", "", time.Now())
+ if err := release.TrashApp(context.Background(), f.fx.rel, "bab", fromApp, "paul@keymail.dev", time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ if err := f.fx.st.TrashAppRow(OpsAccountID, fromApp, time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ f.fx.srv.seedsPass(context.Background(), time.Now())
+ if f.hasKey(t, fleetSnapshotOf(fileHost, id)) {
+ t.Fatal("a trashed app's aborted fleet snapshot survived the sweep")
+ }
+ if got := f.state(t, fileHost); got != seeds.StateAborted {
+ t.Fatalf("record = %s, want it kept aborted", got)
+ }
+}
+
+func TestSeedsPassAbortsStuckFleetFileReservation(t *testing.T) {
+ f := newFleetFileFixture(t)
+ f.sweepable()
+ now := time.Now()
+ stuck := f.fleetSeedRecord(t, fileHost, seeds.StateReserving, "", "", now.Add(-seedFileReserveTTL-time.Minute))
+ live := f.fleetSeedRecord(t, "live.shop.example.com", seeds.StateReserving, "", "", now.Add(-time.Minute))
+ f.fx.srv.seedsPass(context.Background(), now)
+ if got := f.state(t, fileHost); got != seeds.StateAborted || f.hasKey(t, fleetSnapshotOf(fileHost, stuck)) {
+ t.Fatalf("a stuck fleet reservation = %s, snapshot kept %v", got, f.hasKey(t, fleetSnapshotOf(fileHost, stuck)))
+ }
+ if got := f.state(t, "live.shop.example.com"); got != seeds.StateReserving || !f.hasKey(t, fleetSnapshotOf("live.shop.example.com", live)) {
+ t.Fatalf("a live fleet reservation = %s", got)
+ }
+ // The sweep never rolls a fleet file seed back: only the door does.
+ f.fx.srv.seedsPass(context.Background(), now.Add(time.Hour))
+ if got := f.state(t, fileHost); got != seeds.StateAborted {
+ t.Fatalf("after a second pass = %s, want aborted", got)
+ }
+}
+
+func TestSeedsPassDeletesOrphanFleetSnapshotAfterAnHour(t *testing.T) {
+ f := newFleetFileFixture(t)
+ f.sweepable()
+ id := newSeedID(t)
+ key := fleetSnapshotOf(fileHost, id)
+ if _, err := f.fx.rel.Put(context.Background(), key, []byte("snap"), ""); err != nil {
+ t.Fatal(err)
+ }
+ now := time.Now()
+ f.fx.srv.seedsPass(context.Background(), now)
+ if !f.hasKey(t, key) {
+ t.Fatal("a fresh orphan was deleted")
+ }
+ f.fx.srv.seedsPass(context.Background(), now.Add(2*time.Hour))
+ if f.hasKey(t, key) {
+ t.Fatal("an orphan past the hour survived")
+ }
+}
+
+func TestSeedsPassFleetHalfRunsWithoutSeedData(t *testing.T) {
+ f := newFleetFileFixture(t)
+ f.sweepable()
+ f.fx.srv.cfg.SeedData = nil
+ id := f.fleetSeedRecord(t, fileHost, seeds.StateAborted, "", "", time.Now())
+ f.fx.srv.seedsPass(context.Background(), time.Now())
+ if f.hasKey(t, fleetSnapshotOf(fileHost, id)) {
+ t.Fatal("the fleet half did not run without a data bucket")
+ }
+}
+
+// An aborted fleet file seed whose fleet has no active box: nothing proves
+// it gone, so nothing finishes it and the hostname stays held.
+func TestFleetFileSeedNoOwnerNeverFinished(t *testing.T) {
+ f := newFleetFileFixture(t)
+ f.sweepable()
+ reg, _ := openRegistry(f.fx.regPath)
+ if err := reg.SetFleetBoxStatus(seedFleet, "pi-1", "detached"); err != nil {
+ t.Fatal(err)
+ }
+ id := f.fleetSeedRecord(t, fileHost, seeds.StateAborted, "", "", time.Now())
+ now := time.Now()
+ for i := 0; i < 2; i++ {
+ f.fx.srv.seedsPass(context.Background(), now.Add(time.Duration(i)*2*time.Hour))
+ }
+ if err := f.fx.srv.finishSeed(context.Background(), "bab", fromApp, fileHost, id); err != nil {
+ t.Fatal(err)
+ }
+ if got := f.state(t, fileHost); got != seeds.StateAborted {
+ t.Fatalf("record = %s, want it kept aborted", got)
+ }
+ if code, _ := deleteInstance(t, f, fileHost); code != http.StatusConflict {
+ t.Fatalf("delete = %d, want 409", code)
+ }
+}
diff --git a/internal/console/seedfinish.go b/internal/console/seedfinish.go
index 24378a9d4..3805273d3 100644
--- a/internal/console/seedfinish.go
+++ b/internal/console/seedfinish.go
@@ -33,7 +33,9 @@ import (
// when no other instance names that environment (M10), read strictly:
// a record of the app that will not decode counts as one (Plan 8 M7).
// A store with another seed, or none, is never touched.
-// 2. The seed's snapshot, seeds/<host>/<id>/snapshot.db.
+// 2. The seed's snapshot, seeds/<host>/<id>/snapshot.db; for a fleet file
+// seed, apps/<sqid>/<app>/seeds/<host>/<id>/snapshot.db in the
+// deployment bucket (seedSnapshotTarget), which needs no data bucket.
// 3. For a --from seed, every key under the host's replica prefix in the
// data bucket (M11). It is this seed's: the record is create-only and
// the create door's leftover-replica rail refused the host if anything
@@ -109,21 +111,27 @@ func (s *Server) finishSeedOnce(ctx context.Context, sqid, app, host, seedID str
}
ctx = withDemoClaimOperation(ctx, op.ID)
}
+ // A fleet file seed's snapshot is in the deployment bucket, and its
+ // replica is the fleet's own, which this console never deletes: its
+ // box proved it gone before it reported rolledback (design §3.6).
+ onFleet := seedOnFleet(rec)
+ snapshots, snapshot := s.seedSnapshotTarget(rec)
// Checked before anything is destroyed: without it the store would be
// torn down and every later finish fail with the record holding the
// host.
- if s.cfg.SeedData == nil {
+ if snapshots == nil {
return fmt.Errorf("finish seed %s of %s: this console has no data bucket to delete its snapshot from", seedID, host)
}
if err := s.finishSeedStore(ctx, sqid, app, host, seedID, rec.Environment); err != nil {
return err
}
- if err := s.cfg.SeedData.Delete(ctx, seeds.SnapshotKey(host, seedID)); err != nil && !errors.Is(err, os.ErrNotExist) {
+ if err := snapshots.Delete(ctx, snapshot); err != nil && !errors.Is(err, os.ErrNotExist) {
return fmt.Errorf("delete the snapshot of seed %s of %s: %w", seedID, host, err)
}
- // A file seed places as a --from seed does, so its rollback may leave a
- // replica too.
- if rec.Seed.Kind == seeds.KindReplica || rec.Seed.Kind == seeds.KindFile || rec.Seed.DemoClaim() {
+ // A region file seed places as a --from seed does, so its rollback may
+ // leave a replica too. A fleet one's replica is never this console's
+ // (deleteSeedReplica would refuse it anyway, leftoverCheckApplies).
+ if !onFleet && (rec.Seed.Kind == seeds.KindReplica || rec.Seed.Kind == seeds.KindFile || rec.Seed.DemoClaim()) {
var gone bool
if etag, gone, err = s.deleteSeedReplica(ctx, rec, etag); err != nil {
return err
diff --git a/internal/console/seedfloor.go b/internal/console/seedfloor.go
index d93671e46..80cfbcb15 100644
--- a/internal/console/seedfloor.go
+++ b/internal/console/seedfloor.go
@@ -54,21 +54,9 @@ func (s *Server) seedRegionReadyForEdges(ctx context.Context, region string, one
if s.cfg.HostClaim {
return seedClaimConsoleRefusal()
}
- floor, err := seeds.ReadFloor(ctx, s.cfg.Releases)
- if err == nil && floor != nil {
- // A floor PublishFloor would never write (a hand-edited or
- // truncated object) is as good as unreadable: an empty min_release
- // would match every box that could not read its own floor.
- if ok, perr := seeds.ReleaseAtOrAbove(floor.MinRelease, floor.MinRelease); !ok || perr != nil {
- err = fmt.Errorf("published floor has no usable min_release %q", floor.MinRelease)
- }
- }
- if err != nil {
- log.Printf("console: seeds floor: %v", err)
- return &doorRefusal{Status: http.StatusServiceUnavailable, Msg: "could not read the seeds floor. Try again."}
- }
- if floor == nil {
- return &doorRefusal{Status: http.StatusConflict, Msg: "This deployment has no seeds floor yet. An operator publishes it with carlos system seeds-floor publish."}
+ floor, ref := s.publishedSeedsFloor(ctx)
+ if ref != nil {
+ return ref
}
minProtocol := max(seeds.RequiredProtocol, floor.Min)
if rule != nil {
@@ -175,6 +163,28 @@ func (s *Server) seedRegionReadyForEdges(ctx context.Context, region string, one
return nil
}
+// publishedSeedsFloor reads the published seeds floor for a seed door's
+// readiness check: the floor, or the refusal when it is absent or not
+// usable. A floor PublishFloor would never write (a hand-edited or
+// truncated object) is as good as unreadable: an empty min_release would
+// match every box that could not read its own floor.
+func (s *Server) publishedSeedsFloor(ctx context.Context) (*seeds.Floor, *doorRefusal) {
+ floor, err := seeds.ReadFloor(ctx, s.cfg.Releases)
+ if err == nil && floor != nil {
+ if ok, perr := seeds.ReleaseAtOrAbove(floor.MinRelease, floor.MinRelease); !ok || perr != nil {
+ err = fmt.Errorf("published floor has no usable min_release %q", floor.MinRelease)
+ }
+ }
+ if err != nil {
+ log.Printf("console: seeds floor: %v", err)
+ return nil, &doorRefusal{Status: http.StatusServiceUnavailable, Msg: "could not read the seeds floor. Try again."}
+ }
+ if floor == nil {
+ return nil, &doorRefusal{Status: http.StatusConflict, Msg: "This deployment has no seeds floor yet. An operator publishes it with carlos system seeds-floor publish."}
+ }
+ return floor, nil
+}
+
// seedClaimConsoleRefusal is the seed doors' answer on a console with claim
// control on. The --from door also gives it for a source whose claim could
// not be read, which seedRegionReady's own check makes unreachable today.
diff --git a/internal/console/seedholdreview_test.go b/internal/console/seedholdreview_test.go
new file mode 100644
index 000000000..3b2a06445
--- /dev/null
+++ b/internal/console/seedholdreview_test.go
@@ -0,0 +1,294 @@
+package console
+
+import (
+ "context"
+ "errors"
+ "net/http"
+ "net/url"
+ "os"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/domains"
+ "github.com/carlosframework/platform/internal/provision"
+ "github.com/carlosframework/platform/internal/release"
+ "github.com/carlosframework/platform/internal/seeds"
+)
+
+// Task 16 review: the fleet seed hold in one place (P1-1), and the sweep's
+// two halves (P2-1, P3-1).
+
+const holdHost = "woodstar.app"
+
+// holdWorld is titogo (bab) with lifetimes on or off, a first-route claim on
+// woodstar.app (the claim `domains attach` makes), and a fleet file seed's
+// record at the same host, created through the seed doors' own create and
+// aborted with FS-30 held in the replica: the hostname its box has not yet
+// proved free.
+func holdWorld(t *testing.T, on bool) (*consoleFixture, string, func(*testing.T) context.Context) {
+ t.Helper()
+ clock := useLifetimesClock(t)
+ fx, member := instanceFixture(t, "code-hold")
+ if on {
+ turnLifetimesOn(t, fx.srv, clock)
+ }
+ ctxOf := func(t *testing.T) context.Context {
+ if on {
+ return onCtx(t, fx.srv)
+ }
+ return context.Background()
+ }
+ if _, _, err := domains.AttachClaim(context.Background(), fx.rel, domains.Claim{
+ Host: holdHost, Account: "bab", App: "titogo", CreatedAt: time.Now().UTC().Format(time.RFC3339),
+ }); err != nil {
+ t.Fatal(err)
+ }
+ life, err := fx.st.AppLife(OpsAccountID, "titogo")
+ if err != nil || life == nil {
+ t.Fatalf("app life: %v %v", life, err)
+ }
+ now := time.Now().UTC()
+ rec := provision.Record{Schema: 1, Host: holdHost, Slug: "woodstar", App: "titogo", Account: "bab", Channel: "edge",
+ Region: "fleet/pi", CreatedAt: now,
+ Seed: &provision.SeedSource{ID: newSeedID(t), Kind: seeds.KindFile, State: seeds.StateReady,
+ SHA256: strings.Repeat("a", 64), Bytes: 4, By: "alice@keymail.dev", At: now}}
+ if err := fx.srv.createSeedRecord(ctxOf(t), seedCreate{lifetime: life.Lifetime}, rec); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := provision.SetRecordSeed(ctxOf(t), fx.rel, "bab", "titogo", holdHost,
+ provision.SeedFail(rec.Seed.ID, fileSeedCopyInStorageCopy, provision.SeedHeldReplica)); err != nil {
+ t.Fatal(err)
+ }
+ return fx, member, ctxOf
+}
+
+func holdRecord(t *testing.T, fx *consoleFixture) []byte {
+ t.Helper()
+ raw, _, err := fx.rel.Get(context.Background(), provision.RecordKey("bab", "titogo", holdHost))
+ if err != nil && !errors.Is(err, os.ErrNotExist) {
+ t.Fatal(err)
+ }
+ return raw
+}
+
+func TestDomainDetachRefusesHeldFleetFileSeed(t *testing.T) {
+ held := fleetSeedHeldSentence(holdHost, &provision.SeedSource{Reason: fileSeedCopyInStorageCopy, Held: provision.SeedHeldReplica})
+ for _, on := range []bool{false, true} {
+ mode := map[bool]string{false: "lifetimes off", true: "lifetimes on"}[on]
+ t.Run(mode+", the CLI door", func(t *testing.T) {
+ fx, member, _ := holdWorld(t, on)
+ code, _, out := rawReq(t, http.MethodDelete, domainsURL(fx, "bab", "titogo")+"/"+holdHost, member, "")
+ if code != http.StatusConflict || errorOf(t, out) != held {
+ t.Fatalf("detach = %d %s, want 409 %q", code, out, held)
+ }
+ if holdRecord(t, fx) == nil {
+ t.Fatal("the detach retired the held seed's record")
+ }
+ if _, err := domains.GetClaim(context.Background(), fx.rel, holdHost); err != nil {
+ t.Fatalf("the claim went: %v", err)
+ }
+ })
+ t.Run(mode+", the browser door", func(t *testing.T) {
+ fx, _, _ := holdWorld(t, on)
+ // The owner: instanceFixture's cliToken left alice signed in.
+ fx.setUser("paul@keymail.dev")
+ c := newBrowser(t)
+ signUp(t, fx, c, "code-paul-detach")
+ csrf := sessionToken(t, fx, c)
+ status, _, body := postForm(t, c, fx.ts.URL+"/a/bab/apps/titogo/domains/detach",
+ url.Values{"csrf": {csrf}, "host": {holdHost}, "confirm": {holdHost}})
+ if status != http.StatusConflict || !strings.Contains(body, "woodstar.app keeps its hostname") {
+ t.Fatalf("detach = %d, want 409 with the held sentence:\n%s", status, body)
+ }
+ if holdRecord(t, fx) == nil {
+ t.Fatal("the detach retired the held seed's record")
+ }
+ if _, err := domains.GetClaim(context.Background(), fx.rel, holdHost); err != nil {
+ t.Fatalf("the claim went: %v", err)
+ }
+ })
+ }
+}
+
+// The primitive itself: retiring a held fleet file seed refuses, whoever
+// asks; once the seeds door has moved it to rolled-back (after the box's
+// proof), the finish retires it.
+func TestRetireRefusesHeldFleetFileSeed(t *testing.T) {
+ for _, on := range []bool{false, true} {
+ t.Run(map[bool]string{false: "lifetimes off", true: "lifetimes on"}[on], func(t *testing.T) {
+ fx, _, ctxOf := holdWorld(t, on)
+ var held *fleetSeedHoldError
+ err := fx.srv.retireInstanceRecord(ctxOf(t), "bab", "titogo", holdHost, "test", "", retireAny)
+ if !errors.As(err, &held) || held.Host != holdHost {
+ t.Fatalf("retireInstanceRecord = %v, want the hold", err)
+ }
+ if on {
+ err := fx.srv.retireRecordWithLifetime(ctxOf(t), "bab", "titogo", holdHost, retireAny)
+ if !errors.As(err, &held) {
+ t.Fatalf("retireRecordWithLifetime = %v, want the hold", err)
+ }
+ }
+ if holdRecord(t, fx) == nil {
+ t.Fatal("a refused retirement removed the record")
+ }
+ rec, _, err := fx.srv.readRecord(ctxOf(t), "bab", "titogo", holdHost)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := provision.SetRecordSeed(ctxOf(t), fx.rel, "bab", "titogo", holdHost, provision.SeedRolledBack(rec.Seed.ID)); err != nil {
+ t.Fatal(err)
+ }
+ if err := fx.srv.finishSeed(ctxOf(t), "bab", "titogo", holdHost, rec.Seed.ID); err != nil {
+ t.Fatal(err)
+ }
+ if holdRecord(t, fx) != nil {
+ t.Fatal("the finish did not retire the rolled-back seed")
+ }
+ })
+ }
+}
+
+// failingFleetList is the deployment store with a fleet listing that fails.
+type failingFleetList struct{ release.Store }
+
+func (failingFleetList) ListMod(context.Context, string) ([]release.KeyMod, error) {
+ return nil, errors.New("listing unavailable")
+}
+
+// jobCtx is a context whose jobFailed calls are collected.
+func jobCtx() (context.Context, *jobRun) {
+ run := &jobRun{}
+ return context.WithValue(context.Background(), jobRunKey{}, run), run
+}
+
+// P2-1: a fleet listing that fails costs only the fleet half.
+func TestSeedsPassRegionHalfSurvivesFleetListingFailure(t *testing.T) {
+ f := newFleetFileFixture(t)
+ f.fx.srv.cfg.Releases = failingFleetList{Store: f.fx.srv.cfg.Releases}
+ fleetID := f.fleetSeedRecord(t, fileHost, seeds.StateAborted, "", "", time.Now())
+ // A region seed of another app at another host, aborted, with its
+ // snapshot in the data bucket.
+ regionID := newSeedID(t)
+ const regionHost = "region.other.example.com"
+ if err := provision.CreateRecord(context.Background(), f.fx.rel, provision.Record{Schema: 1, Host: regionHost, Slug: "region",
+ App: "other", Account: "bab", Channel: "stable", CreatedAt: time.Now().UTC(),
+ Seed: &provision.SeedSource{ID: regionID, Kind: seeds.KindFile, State: seeds.StateAborted, By: "bob@example.com", At: time.Now()}}); err != nil {
+ t.Fatal(err)
+ }
+ regionKey := seeds.SnapshotKey(regionHost, regionID)
+ if _, err := f.data.Put(context.Background(), regionKey, []byte("snap"), ""); err != nil {
+ t.Fatal(err)
+ }
+ ctx, run := jobCtx()
+ f.fx.srv.seedsPass(ctx, time.Now())
+ if _, _, err := f.data.Get(context.Background(), regionKey); !errors.Is(err, os.ErrNotExist) {
+ t.Fatalf("the region snapshot: %v, want it swept", err)
+ }
+ if !f.hasKey(t, fleetSnapshotOf(fileHost, fleetID)) {
+ t.Fatal("a fleet snapshot was deleted with its listing failed")
+ }
+ if run.err == nil || !strings.Contains(run.err.Error(), "fleet seed snapshots") {
+ t.Fatalf("job error = %v, want the fleet listing's", run.err)
+ }
+}
+
+// P3-1: a console with no data bucket leaves region seeds alone in steps 4
+// and 6, rather than failing on them every pass.
+func TestSeedsPassWithoutSeedDataLeavesRegionSeeds(t *testing.T) {
+ f := newFleetFileFixture(t)
+ f.sweepable()
+ f.fx.srv.cfg.SeedData = nil
+ now := time.Now()
+ put := func(host, state string, at time.Time) {
+ t.Helper()
+ if err := provision.CreateRecord(context.Background(), f.fx.rel, provision.Record{Schema: 1, Host: host, Slug: "r",
+ App: "other", Account: "bab", Channel: "stable", CreatedAt: now.UTC(),
+ Seed: &provision.SeedSource{ID: newSeedID(t), Kind: seeds.KindFile, State: state, By: "bob@example.com", At: at}}); err != nil {
+ t.Fatal(err)
+ }
+ }
+ put("stuck.other.example.com", seeds.StateReserving, now.Add(-seedFileReserveTTL-time.Minute))
+ put("back.other.example.com", seeds.StateRolledBack, now)
+ ctx, run := jobCtx()
+ f.fx.srv.seedsPass(ctx, now)
+ if run.err != nil {
+ t.Fatalf("job error = %v, want none", run.err)
+ }
+ for host, want := range map[string]string{"stuck.other.example.com": seeds.StateReserving, "back.other.example.com": seeds.StateRolledBack} {
+ rec, err := provision.GetRecord(context.Background(), f.fx.rel, "bab", "other", host)
+ if err != nil || rec.Seed.State != want {
+ t.Fatalf("%s = %+v %v, want %s", host, rec.Seed, err, want)
+ }
+ }
+}
+
+// readThenWrite is the deployment store with one write slipped in just
+// after the first Get of key: a record written between the legacy
+// retire's read and its delete.
+type readThenWrite struct {
+ release.Store
+ key string
+ write func(ctx context.Context, s release.Store)
+ done bool
+}
+
+func (r *readThenWrite) Get(ctx context.Context, key string) ([]byte, string, error) {
+ raw, etag, err := r.Store.Get(ctx, key)
+ if key == r.key && !r.done {
+ r.done = true
+ r.write(ctx, r.Store)
+ }
+ return raw, etag, err
+}
+
+func (r *readThenWrite) DeleteIfMatch(ctx context.Context, key, etag string) error {
+ return release.DeleteIfMatch(ctx, r.Store, key, etag)
+}
+
+// Round 2 P2-A: with lifetimes off the retire's delete is bound to the read
+// the hold was asked of. A record written in between survives, and the
+// detach answers "try again".
+func TestLegacyRetireBindsDeleteToItsRead(t *testing.T) {
+ fx, member := firstRouteFixture(t, "code-legacy-race")
+ key := provision.RecordKey("bab", "titogo", holdHost)
+ var written []byte
+ fx.srv.cfg.Releases = &readThenWrite{Store: fx.rel, key: key, write: func(ctx context.Context, s release.Store) {
+ raw, etag, err := s.Get(ctx, key)
+ if err != nil {
+ t.Error(err)
+ return
+ }
+ written = []byte(strings.Replace(string(raw), `"channel":"edge"`, `"channel":"stable"`, 1))
+ if _, err := s.Put(ctx, key, written, etag); err != nil {
+ t.Error(err)
+ }
+ }}
+ code, _, out := rawReq(t, http.MethodDelete, domainsURL(fx, "bab", "titogo")+"/"+holdHost, member, "")
+ if code != http.StatusBadGateway || errorOf(t, out) != "could not detach the hostname — try again" {
+ t.Fatalf("detach = %d %s, want 502 try again", code, out)
+ }
+ raw, _, err := fx.rel.Get(context.Background(), key)
+ if err != nil || written == nil || string(raw) != string(written) {
+ t.Fatalf("record = %s, %v; want the one written between the read and the delete", raw, err)
+ }
+ if _, err := domains.GetClaim(context.Background(), fx.rel, holdHost); err != nil {
+ t.Fatalf("the claim went: %v", err)
+ }
+ // The primitive answers the conflict itself.
+ fx.srv.cfg.Releases = &readThenWrite{Store: fx.rel, key: key, write: func(ctx context.Context, s release.Store) {
+ _, etag, _ := s.Get(ctx, key)
+ changed := []byte(strings.Replace(string(raw), `"channel":"stable"`, `"channel":"edge"`, 1))
+ if _, err := s.Put(ctx, key, changed, etag); err != nil {
+ t.Error(err)
+ }
+ }}
+ if err := fx.srv.retireInstanceRecord(context.Background(), "bab", "titogo", holdHost, "test", "", retireAny); !errors.Is(err, release.ErrCASConflict) {
+ t.Fatalf("retireInstanceRecord = %v, want ErrCASConflict", err)
+ }
+ // Absent is done.
+ fx.srv.cfg.Releases = fx.rel
+ if err := fx.srv.retireInstanceRecord(context.Background(), "bab", "titogo", "absent.example.com", "test", "", retireAny); err != nil {
+ t.Fatalf("an absent record = %v, want nil", err)
+ }
+}
diff --git a/internal/console/seedpurgehold_test.go b/internal/console/seedpurgehold_test.go
new file mode 100644
index 000000000..9aba358f3
--- /dev/null
+++ b/internal/console/seedpurgehold_test.go
@@ -0,0 +1,173 @@
+package console
+
+import (
+ "context"
+ "errors"
+ "net/http"
+ "net/url"
+ "os"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/provision"
+ "github.com/carlosframework/platform/internal/release"
+ "github.com/carlosframework/platform/internal/seeds"
+)
+
+// Every retirement entrance waits for a fleet file seed's box (plan R1-1):
+// the Trash page's purge (lifetimes on and off), the expiry pass's early
+// purge and the trash sweep. The fleet's box is offline throughout, and its
+// replica objects (in the fleet's own bucket, which the console never sees)
+// are left: only the box's rolledback report frees the app.
+
+const fleetHeldHost = "held.shop.example.com"
+
+// purgeHoldWorld is shop (bab) with lifetimes on or off, a fleet-placed
+// file seed at fleetHeldHost in state, and shop trashed at trashedAt.
+func purgeHoldWorld(t *testing.T, on bool, state string, trashedAt time.Time) lifetimesFx {
+ t.Helper()
+ var l lifetimesFx
+ if on {
+ l = newLtOn(t).lifetimesFx
+ } else {
+ l = newLifetimesFx(t)
+ }
+ rec := provision.Record{Schema: 1, Host: fleetHeldHost, Slug: "held", App: ltApp, Account: "bab", Channel: "stable",
+ Region: "fleet/pi", CreatedAt: time.Now().UTC(),
+ Seed: &provision.SeedSource{ID: newSeedID(t), Kind: seeds.KindFile, State: state, Reason: fileSeedCopyInStorageCopy,
+ Held: provision.SeedHeldReplica, SHA256: strings.Repeat("a", 64), Bytes: 4, By: "alice@keymail.dev", At: time.Now().UTC()}}
+ if state != seeds.StateAborted {
+ rec.Seed.Reason, rec.Seed.Held = "", ""
+ }
+ if err := provision.CreateRecord(context.Background(), l.fx.rel, rec); err != nil {
+ t.Fatal(err)
+ }
+ if err := release.TrashApp(context.Background(), l.fx.rel, "bab", ltApp, "paul@keymail.dev", trashedAt); err != nil {
+ t.Fatal(err)
+ }
+ if err := l.fx.st.TrashAppRow(OpsAccountID, ltApp, trashedAt); err != nil {
+ t.Fatal(err)
+ }
+ return l
+}
+
+func heldRecordStands(t *testing.T, l lifetimesFx) bool {
+ t.Helper()
+ _, _, err := l.fx.rel.Get(context.Background(), provision.RecordKey("bab", ltApp, fleetHeldHost))
+ if err != nil && !errors.Is(err, os.ErrNotExist) {
+ t.Fatal(err)
+ }
+ return err == nil
+}
+
+func shopMarkerStands(t *testing.T, l lifetimesFx) bool {
+ t.Helper()
+ tomb, err := release.ReadAppTombstone(context.Background(), l.fx.rel, "bab", ltApp)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return tomb != nil
+}
+
+// browserPurge runs the Trash page's "Delete now" for shop through its
+// passkey step-up, and answers the flash it set ("kind|message").
+func browserPurge(t *testing.T, l lifetimesFx, code string) string {
+ t.Helper()
+ c := newBrowser(t)
+ signUp(t, l.fx, c, code)
+ csrf := sessionToken(t, l.fx, c)
+ status, loc, _ := postForm(t, c, l.fx.u("/trash/delete"), urlValues("csrf", csrf, "app", ltApp, "confirm", ltApp))
+ if status != http.StatusSeeOther {
+ t.Fatalf("purge = %d", status)
+ }
+ if status, _, body := completeStepUp(t, l.fx, c, loc); status != http.StatusSeeOther {
+ t.Fatalf("resumed purge = %d %s", status, body)
+ }
+ u, _ := url.Parse(l.fx.ts.URL)
+ for _, ck := range c.Jar.Cookies(u) {
+ if ck.Name == flashCookie {
+ v, err := url.QueryUnescape(ck.Value)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return v
+ }
+ }
+ return ""
+}
+
+func TestPurgeAppRefusesHeldFleetFileSeed(t *testing.T) {
+ for _, on := range []bool{false, true} {
+ name := map[bool]string{false: "lifetimes off", true: "lifetimes on"}[on]
+ t.Run(name, func(t *testing.T) {
+ for _, state := range []string{seeds.StateReserving, seeds.StateReady, seeds.StateAborted} {
+ l := purgeHoldWorld(t, on, state, time.Now())
+ want := "err|shop can’t be deleted permanently until its fleet box has cleaned up " + fleetHeldHost + "."
+ if got := browserPurge(t, l, "code-held-"+state); got != want {
+ t.Fatalf("%s: flash = %q, want %q", state, got, want)
+ }
+ if !heldRecordStands(t, l) || !shopMarkerStands(t, l) {
+ t.Fatalf("%s: the purge removed something: record %v, marker %v", state, heldRecordStands(t, l), shopMarkerStands(t, l))
+ }
+ if life, _ := l.fx.st.AppLife(OpsAccountID, ltApp); life == nil {
+ t.Fatalf("%s: the app row went", state)
+ }
+ }
+ })
+ }
+}
+
+func TestPurgeAppProceedsAfterRolledBack(t *testing.T) {
+ for _, on := range []bool{false, true} {
+ name := map[bool]string{false: "lifetimes off", true: "lifetimes on"}[on]
+ t.Run(name, func(t *testing.T) {
+ for _, state := range []string{seeds.StateRolledBack, seeds.StatePlaced} {
+ l := purgeHoldWorld(t, on, state, time.Now())
+ if got := browserPurge(t, l, "code-proceeds-"+state); !strings.HasPrefix(got, "ok|") {
+ t.Fatalf("%s: flash = %q, want the purge done", state, got)
+ }
+ if heldRecordStands(t, l) || shopMarkerStands(t, l) {
+ t.Fatalf("%s: the purge left the record (%v) or the marker (%v)", state, heldRecordStands(t, l), shopMarkerStands(t, l))
+ }
+ }
+ })
+ }
+}
+
+func TestTrashExpirySkipsAppWithHeldFleetFileSeed(t *testing.T) {
+ ctx := context.Background()
+ for _, on := range []bool{false, true} {
+ name := map[bool]string{false: "lifetimes off", true: "lifetimes on"}[on]
+ t.Run(name+", the expiry pass's early purge", func(t *testing.T) {
+ l := purgeHoldWorld(t, on, seeds.StateAborted, time.Now())
+ tomb, _ := release.ReadAppTombstone(ctx, l.fx.rel, "bab", ltApp)
+ if _, err := l.fx.st.db.Exec(`UPDATE apps SET purge_for = ?, purge_after = ? WHERE app = ?`, tomb.DeletedAt.Unix(), tomb.DeletedAt.Unix()+1, ltApp); err != nil {
+ t.Fatal(err)
+ }
+ now := tomb.DeletedAt.Add(time.Hour)
+ if !l.fx.srv.lifetimesIteration(ctx, "expiry pass", true, false, func(ctx context.Context) { l.fx.srv.expiryPass(ctx, now) }) {
+ t.Fatal("the expiry pass did not run")
+ }
+ if !heldRecordStands(t, l) || !shopMarkerStands(t, l) {
+ t.Fatal("the early purge removed something")
+ }
+ if life, _ := l.fx.st.AppLife(OpsAccountID, ltApp); life == nil {
+ t.Fatal("the early purge released the name")
+ }
+ })
+ t.Run(name+", the trash sweep", func(t *testing.T) {
+ old := time.Now().Add(-31 * 24 * time.Hour)
+ l := purgeHoldWorld(t, on, seeds.StateAborted, old)
+ if err := l.fx.st.PurgeAppRow(OpsAccountID, ltApp); err != nil {
+ t.Fatal(err)
+ }
+ if !l.fx.srv.lifetimesIteration(ctx, "expiry pass", true, false, func(ctx context.Context) { l.fx.srv.expiryPass(ctx, time.Now()) }) {
+ t.Fatal("the expiry pass did not run")
+ }
+ if !heldRecordStands(t, l) || !shopMarkerStands(t, l) {
+ t.Fatal("the trash sweep removed something")
+ }
+ })
+ }
+}
diff --git a/internal/console/seedslice3review_test.go b/internal/console/seedslice3review_test.go
new file mode 100644
index 000000000..b48bd5e26
--- /dev/null
+++ b/internal/console/seedslice3review_test.go
@@ -0,0 +1,180 @@
+package console
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "net/http"
+ "os"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/provision"
+ "github.com/carlosframework/platform/internal/release"
+ "github.com/carlosframework/platform/internal/seeds"
+)
+
+// Slice 3's whole-branch review fixes.
+
+// P2-1: an app holding an unfinished fleet file seed is not trashed (its
+// box skips a trashed app's records, so the seed could never be rolled
+// back and the app never purged). Deleting the instance first, then the
+// box's rollback and the finish, lets the trash through.
+func TestTrashAppRefusesHeldFleetFileSeed(t *testing.T) {
+ f := newFleetFileFixture(t)
+ ctx := context.Background()
+ id := f.fleetSeedRecord(t, fileHost, seeds.StateAborted, "", "", time.Now())
+ trash := func() (int, string) {
+ code, _, out := rawReq(t, http.MethodPost, f.fx.ts.URL+"/api/cli/apps/bab/"+fromApp+"/delete", f.token, "")
+ return code, out
+ }
+ want := fmt.Sprintf(fileSeedTrashHeldCopy, fromApp, fileHost)
+ if want != "shop can’t be moved to the trash until its fleet box has cleaned up push.shop.example.com. Delete each with carlos instances delete, then try again." {
+ t.Fatalf("FS-39 = %q", want)
+ }
+ if code, out := trash(); code != http.StatusConflict || errorOf(t, out) != want {
+ t.Fatalf("trash = %d %s, want 409 FS-39", code, out)
+ }
+ if tomb, err := release.ReadAppTombstone(ctx, f.fx.rel, "bab", fromApp); err != nil || tomb != nil {
+ t.Fatalf("marker = %+v %v, want none", tomb, err)
+ }
+ if life, _ := f.fx.st.AppLife(OpsAccountID, fromApp); life == nil || life.Trashed() {
+ t.Fatalf("app row = %+v, want it live", life)
+ }
+ // The expiry pass's trash asks the same.
+ if _, err := f.fx.st.db.Exec(`UPDATE apps SET expires_at = ? WHERE app = ?`, time.Now().Add(-time.Hour).Unix(), fromApp); err != nil {
+ t.Fatal(err)
+ }
+ f.fx.srv.expiryPass(ctx, time.Now())
+ if tomb, _ := release.ReadAppTombstone(ctx, f.fx.rel, "bab", fromApp); tomb != nil {
+ t.Fatal("the expiry pass trashed an app holding a fleet file seed")
+ }
+ if _, err := f.fx.st.db.Exec(`UPDATE apps SET expires_at = 0 WHERE app = ?`, fromApp); err != nil {
+ t.Fatal(err)
+ }
+ // The box rolls it back (through the seeds door), and the finish frees
+ // the host: the trash goes through.
+ if _, err := provision.SetRecordSeed(ctx, f.fx.rel, "bab", fromApp, fileHost, provision.SeedRolledBack(id)); err != nil {
+ t.Fatal(err)
+ }
+ if err := f.fx.srv.finishSeed(ctx, "bab", fromApp, fileHost, id); err != nil {
+ t.Fatal(err)
+ }
+ if code, out := trash(); code != http.StatusOK {
+ t.Fatalf("trash after the finish = %d %s", code, out)
+ }
+ if tomb, err := release.ReadAppTombstone(ctx, f.fx.rel, "bab", fromApp); err != nil || tomb == nil {
+ t.Fatalf("marker = %+v %v, want it written", tomb, err)
+ }
+}
+
+// failingDataList is a data bucket whose listing fails.
+type failingDataList struct{ release.Store }
+
+func (failingDataList) ListMod(context.Context, string) ([]release.KeyMod, error) {
+ return nil, errors.New("listing unavailable")
+}
+
+// P2-2: a region listing that fails costs only the region half.
+func TestSeedsPassFleetHalfSurvivesRegionListingFailure(t *testing.T) {
+ f := newFleetFileFixture(t)
+ f.sweepable()
+ f.fx.srv.cfg.SeedData = failingDataList{Store: f.data}
+ fleetID := f.fleetSeedRecord(t, fileHost, seeds.StateAborted, "", "", time.Now())
+ now := time.Now()
+ // A region reservation long stale: with the region half off it is left.
+ if err := provision.CreateRecord(context.Background(), f.fx.rel, provision.Record{Schema: 1, Host: "stuck.other.example.com", Slug: "stuck",
+ App: "other", Account: "bab", Channel: "stable", CreatedAt: now.UTC(),
+ Seed: &provision.SeedSource{ID: newSeedID(t), Kind: seeds.KindFile, State: seeds.StateReserving, By: "bob@example.com", At: now.Add(-seedFileReserveTTL - time.Minute)}}); err != nil {
+ t.Fatal(err)
+ }
+ ctx, run := jobCtx()
+ f.fx.srv.seedsPass(ctx, now)
+ if f.hasKey(t, fleetSnapshotOf(fileHost, fleetID)) {
+ t.Fatal("the fleet half did not run past a region listing failure")
+ }
+ if run.err == nil || !strings.Contains(run.err.Error(), "list snapshots") {
+ t.Fatalf("job error = %v, want the region listing's", run.err)
+ }
+ rec, err := provision.GetRecord(context.Background(), f.fx.rel, "bab", "other", "stuck.other.example.com")
+ if err != nil || rec.Seed.State != seeds.StateReserving {
+ t.Fatalf("region reservation = %+v %v, want it left reserving", rec, err)
+ }
+}
+
+// P3-2: a placed or aborted fleet file seed's snapshot is deleted by its
+// record's own key even when its app is no longer listed on a fleet.
+func TestSeedsPassCondemnsFleetSnapshotByRecord(t *testing.T) {
+ f := newFleetFileFixture(t)
+ f.sweepable()
+ ctx := context.Background()
+ put := func(host, state string) string {
+ t.Helper()
+ id := newSeedID(t)
+ if err := provision.CreateRecord(ctx, f.fx.rel, provision.Record{Schema: 1, Host: host, Slug: "x", App: "other", Account: "bab",
+ Channel: "stable", Region: "fleet/" + seedFleet, CreatedAt: time.Now().UTC(),
+ Seed: &provision.SeedSource{ID: id, Kind: seeds.KindFile, State: state, By: "bob@example.com", At: time.Now()}}); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := f.fx.rel.Put(ctx, seeds.FleetSnapshotKey("bab", "other", host, id), []byte("snap"), ""); err != nil {
+ t.Fatal(err)
+ }
+ return id
+ }
+ placed := put("placed.other.example.com", seeds.StatePlaced)
+ aborted := put("aborted.other.example.com", seeds.StateAborted)
+ ready := put("ready.other.example.com", seeds.StateReady)
+ f.fx.srv.seedsPass(ctx, time.Now())
+ for host, c := range map[string]struct {
+ id string
+ gone bool
+ }{"placed.other.example.com": {placed, true}, "aborted.other.example.com": {aborted, true}, "ready.other.example.com": {ready, false}} {
+ _, _, err := f.fx.rel.Get(ctx, seeds.FleetSnapshotKey("bab", "other", host, c.id))
+ if gone := errors.Is(err, os.ErrNotExist); gone != c.gone {
+ t.Errorf("%s: snapshot gone %v, want %v (%v)", host, gone, c.gone, err)
+ }
+ }
+}
+
+// P3-1: the hold is asked of the stored body, so a body the record's own
+// decode rejects is still held; one the hold cannot classify while it
+// carries a seed is refused, and one with no seed at all is not.
+func TestRetireHoldsAnUndecodableSeedRecord(t *testing.T) {
+ for _, on := range []bool{false, true} {
+ t.Run(map[bool]string{false: "lifetimes off", true: "lifetimes on"}[on], func(t *testing.T) {
+ fx, _, ctxOf := holdWorld(t, on)
+ key := provision.RecordKey("bab", "titogo", holdHost)
+ put := func(body string) {
+ t.Helper()
+ _, etag, err := fx.rel.Get(context.Background(), key)
+ if err != nil && !errors.Is(err, os.ErrNotExist) {
+ t.Fatal(err)
+ }
+ if _, err := fx.rel.Put(context.Background(), key, []byte(body), etag); err != nil {
+ t.Fatal(err)
+ }
+ }
+ // A held seed in a body the full decode rejects (schema 0, no
+ // account) is still the hold's.
+ put(`{"host":"` + holdHost + `","region":"fleet/pi","seed":{"id":"sd_x","kind":"file","state":"aborted"}}`)
+ var held *fleetSeedHoldError
+ if err := fx.srv.retireInstanceRecord(ctxOf(t), "bab", "titogo", holdHost, "test", "", retireAny); !errors.As(err, &held) {
+ t.Fatalf("an undecodable held seed = %v, want the hold", err)
+ }
+ // A seed the hold cannot read: refused.
+ put(`{"host":"` + holdHost + `","seed":"garbled"}`)
+ if err := fx.srv.retireInstanceRecord(ctxOf(t), "bab", "titogo", holdHost, "test", "", retireAny); !errors.Is(err, errFleetSeedUnclassified) {
+ t.Fatalf("an unclassifiable seed = %v, want errFleetSeedUnclassified", err)
+ }
+ if holdRecord(t, fx) == nil {
+ t.Fatal("a refused retirement removed the record")
+ }
+ // No seed at all: corrupt, and retired as before.
+ put(`not json`)
+ if err := fx.srv.retireInstanceRecord(ctxOf(t), "bab", "titogo", holdHost, "test", "", retireAny); err != nil {
+ t.Fatalf("a corrupt body with no seed = %v, want it retired", err)
+ }
+ })
+ }
+}
diff --git a/internal/console/seedsweep.go b/internal/console/seedsweep.go
index 0ee41ddbd..699b8b67d 100644
--- a/internal/console/seedsweep.go
+++ b/internal/console/seedsweep.go
@@ -69,12 +69,18 @@ func (s *Server) StartSeedsPass(ctx context.Context) {
log.Printf("console: seeds pass: off on a host-claim console, where every seed door refuses")
return
}
- if s.cfg.Releases == nil || s.cfg.SeedData == nil {
+ // The region half needs the data bucket; the fleet half (fleet file
+ // seeds, slice 3) needs only the deployment bucket, so a console with
+ // no data bucket still sweeps its fleets' seeds.
+ if s.cfg.Releases == nil {
return
}
- if _, ok := s.cfg.SeedData.(release.ModLister); !ok {
+ if _, ok := s.cfg.SeedData.(release.ModLister); s.cfg.SeedData != nil && !ok {
log.Printf("console: seeds pass: the data bucket cannot list last-modified times, so this sweep deletes no unreferenced snapshot")
}
+ if _, ok := s.cfg.Releases.(release.ModLister); !ok {
+ log.Printf("console: seeds pass: the deployment bucket cannot list last-modified times, so this sweep deletes no fleet seed's snapshot")
+ }
lifetimesWorker(ctx, seedsPassInterval, s.seedsIteration)
}
@@ -115,10 +121,12 @@ func seedStale(seed *provision.SeedSource, now time.Time) bool {
// seedsPass is one sweep. In order:
//
-// 1. The snapshots under seeds/, with their last-modified times. Listed
-// first: every door writes its record before its snapshot (spec §4
-// step 7, §5.1), so a snapshot in this listing whose seed is live has
-// its record in the next one. A seed begun after this listing has no
+// 1. The snapshots under seeds/ in the data bucket, and every fleet file
+// seed's under apps/<sqid>/<app>/seeds/ in the deployment bucket
+// (fleetSeedSnapshots), with their last-modified times. Listed first:
+// every door writes its record before its snapshot (spec §4 step 7,
+// §5.1), so a snapshot in this listing whose seed is live has its
+// record in the next one. A seed begun after this listing has no
// snapshot in it, so nothing below can reach it.
// 2. Every record, strictly: from the bucket, or, with the record view
// armed and step 1 empty (so nothing can be deleted), from the view.
@@ -134,8 +142,12 @@ func seedStale(seed *provision.SeedSource, now time.Time) bool {
// seed's own once its CAS has landed.
// 6. Each rolled-back seed finished (finishSeed re-reads its record).
//
-// Every delete names one exact seeds/<host>/<id>/snapshot.db, so it never
-// reaches another seed's.
+// Every delete names one exact seeds/<host>/<id>/snapshot.db, or one
+// fleet seed's apps/<sqid>/<app>/seeds/<host>/<id>/snapshot.db, so it never
+// reaches another seed's. A fleet file seed is never rolled back here:
+// step 4 aborts a stuck one and step 5 deletes its snapshot (R3-3), and the
+// record stays, holding the hostname, until its box reports rolledback to
+// the fleet seeds door.
//
// The pass is bounded by seedsPassTimeout. Cutting it anywhere is safe and
// the next pass resumes: a listing cut short is an error, so nothing is
@@ -145,7 +157,7 @@ func seedStale(seed *provision.SeedSource, now time.Time) bool {
// a finish cut short leaves its record rolled-back, and every finish step
// is idempotent.
func (s *Server) seedsPass(ctx context.Context, now time.Time) {
- if s.cfg.HostClaim || s.cfg.Releases == nil || s.cfg.SeedData == nil {
+ if s.cfg.HostClaim || s.cfg.Releases == nil {
return
}
ctx, cancel := context.WithTimeout(ctx, seedsPassTimeout)
@@ -155,16 +167,36 @@ func (s *Server) seedsPass(ctx context.Context, now time.Time) {
log.Printf("console: seeds pass: cut short: %v (the next pass resumes)", ctx.Err())
}
}()
- var snaps []release.KeyMod
- ml, walk := s.cfg.SeedData.(release.ModLister)
- if walk {
- var err error
- if snaps, err = ml.ListMod(ctx, seeds.Prefix); err != nil {
- log.Printf("console: seeds pass: list snapshots: %v (nothing swept this pass)", err)
- jobFailed(ctx, fmt.Errorf("seeds pass: list snapshots: %w (nothing swept this pass)", err))
- return
+ var snaps []seedSnapshot
+ // The two halves are independent: a console with no data bucket runs the
+ // fleet half alone (Task 16 review P3-1), and a listing that fails costs
+ // only its own half this pass (Task 16 review P2-1, slice 3 review
+ // P2-2). With the region half off, no region snapshot is decided on,
+ // and steps 4 and 6 leave region seeds alone: their abandonment and
+ // finish need that bucket and that listing.
+ regionHalf := s.cfg.SeedData != nil
+ if ml, walk := s.cfg.SeedData.(release.ModLister); regionHalf && walk {
+ listed, err := ml.ListMod(ctx, seeds.Prefix)
+ if err != nil {
+ log.Printf("console: seeds pass: list snapshots: %v (no region seed swept this pass)", err)
+ jobFailed(ctx, fmt.Errorf("seeds pass: list snapshots: %w (no region seed swept this pass)", err))
+ regionHalf = false
+ listed = nil
+ }
+ for _, o := range listed {
+ if host, id, ok := seeds.ParseSnapshotKey(o.Key); ok {
+ snaps = append(snaps, seedSnapshot{store: s.cfg.SeedData, key: o.Key, mod: o.Mod, host: host, id: id})
+ }
}
}
+ fleet, fleetApps, err := s.fleetSeedSnapshots(ctx)
+ fleetListed := err == nil
+ if err != nil && !errors.Is(err, errNoFleetListing) {
+ log.Printf("console: seeds pass: list fleet seed snapshots: %v (no fleet seed's snapshot swept this pass)", err)
+ jobFailed(ctx, fmt.Errorf("seeds pass: list fleet seed snapshots: %w (no fleet seed's snapshot swept this pass)", err))
+ fleet = nil
+ }
+ snaps = append(snaps, fleet...)
if seedsPassBetweenListings != nil {
seedsPassBetweenListings()
}
@@ -207,23 +239,43 @@ func (s *Server) seedsPass(ctx context.Context, now time.Time) {
return true
}
- // Step 3: the decisions.
- var condemned []string
- waiting := map[[2]string]string{} // host, id -> key: deleted only if this pass abandons the seed
+ // Step 3: the decisions. A fleet snapshot's key names its account and
+ // app, so only that app's record of the host names it.
+ var condemned []seedSnapshot
+ waiting := map[[2]string]seedSnapshot{} // host, id -> snapshot: deleted only if this pass abandons the seed
for _, o := range snaps {
- host, id, ok := seeds.ParseSnapshotKey(o.Key)
- if !ok || held(host) {
+ if held(o.host) {
continue
}
var rec *provision.Record
- if rs := byHost[host]; len(rs) == 1 {
+ if rs := byHost[o.host]; len(rs) == 1 && (o.acct == "" || rs[0].Account == o.acct && rs[0].App == o.app) {
rec = &rs[0]
}
- switch snapshotDecision(rec, id, now, o.Mod) {
+ switch snapshotDecision(rec, o.id, now, o.mod) {
case snapshotDelete:
- condemned = append(condemned, o.Key)
+ condemned = append(condemned, o)
case snapshotIfAbandoned:
- waiting[[2]string{host, id}] = o.Key
+ waiting[[2]string{o.host, o.id}] = o
+ }
+ }
+
+ // Step 3, by record (slice 3 review P3-2): a placed or aborted fleet
+ // file seed's record names its own snapshot's exact key, so that key is
+ // deleted even when the listing above did not reach it (the app is no
+ // longer placed on that fleet, or no longer on any). Only for an app the
+ // listing did not cover, and only after a listing that did not fail, so
+ // a pass never re-deletes what it listed or guesses on a partial one.
+ if fleetListed {
+ for i := range recs {
+ rec := &recs[i]
+ if !seedOnFleet(rec) || fleetApps[rec.Account+"/"+rec.App] || held(rec.Host) ||
+ seeds.Check(rec.Host, rec.Seed.ID) != nil ||
+ (rec.Seed.State != seeds.StatePlaced && rec.Seed.State != seeds.StateAborted) {
+ continue
+ }
+ condemned = append(condemned, seedSnapshot{store: s.cfg.Releases,
+ key: seeds.FleetSnapshotKey(rec.Account, rec.App, rec.Host, rec.Seed.ID),
+ acct: rec.Account, app: rec.App, host: rec.Host, id: rec.Seed.ID})
}
}
@@ -232,28 +284,30 @@ func (s *Server) seedsPass(ctx context.Context, now time.Time) {
if ctx.Err() != nil {
return
}
- if !seedStale(rec.Seed, now) || held(rec.Host) {
+ if !seedStale(rec.Seed, now) || held(rec.Host) || !regionHalf && !seedOnFleet(&rec) {
continue
}
if s.abandonSeed(ctx, rec) {
- if key, ok := waiting[[2]string{rec.Host, rec.Seed.ID}]; ok {
- condemned = append(condemned, key)
+ if o, ok := waiting[[2]string{rec.Host, rec.Seed.ID}]; ok {
+ condemned = append(condemned, o)
}
}
}
// Step 5: the snapshot deletes.
- sort.Strings(condemned)
- for _, key := range condemned {
+ sort.Slice(condemned, func(i, j int) bool { return condemned[i].key < condemned[j].key })
+ for _, o := range condemned {
if ctx.Err() != nil {
return
}
- if err := s.cfg.SeedData.Delete(ctx, key); err != nil && !errors.Is(err, os.ErrNotExist) {
- log.Printf("console: seeds pass: delete %s: %v", key, err)
- jobFailed(ctx, fmt.Errorf("seeds pass: delete %s: %w", key, err))
+ if err := o.store.Delete(ctx, o.key); errors.Is(err, os.ErrNotExist) {
+ continue // gone already (a by-record key, or another pass)
+ } else if err != nil {
+ log.Printf("console: seeds pass: delete %s: %v", o.key, err)
+ jobFailed(ctx, fmt.Errorf("seeds pass: delete %s: %w", o.key, err))
continue
}
- log.Printf("console: seeds pass: deleted %s", key)
+ log.Printf("console: seeds pass: deleted %s", o.key)
}
// Step 6: the finishes.
@@ -261,7 +315,7 @@ func (s *Server) seedsPass(ctx context.Context, now time.Time) {
if ctx.Err() != nil {
return
}
- if rec.Seed == nil || rec.Seed.State != seeds.StateRolledBack || held(rec.Host) {
+ if rec.Seed == nil || rec.Seed.State != seeds.StateRolledBack || held(rec.Host) || !regionHalf && !seedOnFleet(&rec) {
continue
}
if err := s.finishSeed(ctx, rec.Account, rec.App, rec.Host, rec.Seed.ID); err != nil {
@@ -271,6 +325,83 @@ func (s *Server) seedsPass(ctx context.Context, now time.Time) {
}
}
+// seedSnapshot is one listed snapshot: the store it is in, its key and
+// last-modified time, and what its key names. acct and app are set only for
+// a fleet seed's, whose key names them.
+type seedSnapshot struct {
+ store release.Store
+ key string
+ mod time.Time
+ acct, app string
+ host, id string
+}
+
+// errNoFleetListing is fleetSeedSnapshots on a deployment bucket that
+// cannot list last-modified times: no fleet half this pass, and nothing to
+// report each pass (StartSeedsPass logged it once).
+var errNoFleetListing = errors.New("console: the deployment bucket cannot list last-modified times")
+
+// fleetSeedSnapshots lists every fleet file seed's snapshot in the
+// deployment bucket: for each customer fleet, each app of its owning
+// account placed on it, trashed apps included (plan R1-4: a trashed app's
+// abandoned seed still has its snapshot to go), under
+// seeds.FleetSnapshotsPrefix. A key that does not parse as that app's is
+// skipped. Any error is the whole listing's: the pass decides nothing on a
+// partial set. A deployment bucket that cannot list last-modified times
+// answers errNoFleetListing, so nothing of the fleet half is deleted. It
+// also answers the "<sqid>/<app>" of every app it listed, so the pass can
+// condemn by record only what the listing did not cover.
+func (s *Server) fleetSeedSnapshots(ctx context.Context) ([]seedSnapshot, map[string]bool, error) {
+ listed := map[string]bool{} // "<sqid>/<app>" for every app listed
+ ml, ok := s.cfg.Releases.(release.ModLister)
+ if !ok {
+ return nil, nil, errNoFleetListing
+ }
+ reg, err := openRegistry(s.cfg.Registry)
+ if err != nil {
+ return nil, nil, fmt.Errorf("open the registry: %w", err)
+ }
+ owners, err := reg.FleetOwners()
+ if err != nil {
+ return nil, nil, fmt.Errorf("list the fleets: %w", err)
+ }
+ fleets := make([]string, 0, len(owners))
+ for f := range owners {
+ fleets = append(fleets, f)
+ }
+ sort.Strings(fleets)
+ var out []seedSnapshot
+ for _, fleet := range fleets {
+ sqid := owners[fleet]
+ acct, err := s.store.AccountBySqid(sqid)
+ if err != nil {
+ return nil, nil, fmt.Errorf("fleet %s: account %s: %w", fleet, sqid, err)
+ }
+ if acct == nil {
+ continue // an account this console does not hold: no app of it to list
+ }
+ apps, err := s.fleetPlacedAppsIn(acct, fleet, true)
+ if err != nil {
+ return nil, nil, fmt.Errorf("fleet %s: its apps: %w", fleet, err)
+ }
+ for _, app := range apps {
+ objs, err := ml.ListMod(ctx, seeds.FleetSnapshotsPrefix(sqid, app))
+ if err != nil {
+ return nil, nil, fmt.Errorf("fleet %s: %s/%s: %w", fleet, sqid, app, err)
+ }
+ listed[sqid+"/"+app] = true
+ for _, o := range objs {
+ a, ap, host, id, ok := seeds.ParseFleetSnapshotKey(o.Key)
+ if !ok || a != sqid || ap != app {
+ continue
+ }
+ out = append(out, seedSnapshot{store: s.cfg.Releases, key: o.Key, mod: o.Mod, acct: a, app: ap, host: host, id: id})
+ }
+ }
+ }
+ return out, listed, nil
+}
+
type snapshotVerdict int
const (
diff --git a/internal/console/temphook_test.go b/internal/console/temphook_test.go
index 96e0d4074..c6139c3c9 100644
--- a/internal/console/temphook_test.go
+++ b/internal/console/temphook_test.go
@@ -52,6 +52,22 @@ func (h *hookStore) Put(ctx context.Context, key string, body []byte, ifMatch st
return h.Store.Put(ctx, key, body, ifMatch)
}
+// DeleteIfMatch is Delete's hooks and failures for the conditional delete
+// (the delete door's deleteRead, and the claims-off legacy retire, bound to
+// the read the fleet seed hold was asked of), passed to the store below.
+func (h *hookStore) DeleteIfMatch(ctx context.Context, key, etag string) error {
+ if h.onDelete != nil {
+ h.onDelete(key)
+ }
+ if h.fails(h.failDelete, key) {
+ return errors.New("hookStore: delete refused")
+ }
+ h.mu.Lock()
+ h.deletes = append(h.deletes, key)
+ h.mu.Unlock()
+ return release.DeleteIfMatch(ctx, h.Store, key, etag)
+}
+
func (h *hookStore) Delete(ctx context.Context, key string) error {
if h.onDelete != nil {
h.onDelete(key)
diff --git a/internal/console/testdata/claim-routes.txt b/internal/console/testdata/claim-routes.txt
index 1b4bb0fa8..ccd8272a9 100644
--- a/internal/console/testdata/claim-routes.txt
+++ b/internal/console/testdata/claim-routes.txt
@@ -388,6 +388,9 @@ route POST /api/fleet/enrol
route POST /api/fleet/replicas/{account}/{app}/{host}/coordinator
route POST /api/fleet/replicas/{account}/{app}/{host}/release
route POST /api/fleet/replicas/{account}/{app}/{host}/deploy
+route POST /api/fleet/seeds/{account}/{app}/{host}/placed
+route POST /api/fleet/seeds/{account}/{app}/{host}/failed
+route POST /api/fleet/seeds/{account}/{app}/{host}/rolledback
route POST /api/link/publications
route POST /api/link/rotate
route POST /api/ses/events
diff --git a/internal/provision/fleet_seeded_create_3_census_test.go b/internal/provision/fleet_seeded_create_3_census_test.go
new file mode 100644
index 000000000..f04a893bb
--- /dev/null
+++ b/internal/provision/fleet_seeded_create_3_census_test.go
@@ -0,0 +1,116 @@
+package provision
+
+// fleetSeededCreate3WriteCensusInventory is the record-write census for
+// slice 3 of seeded instances on a customer fleet (#1139, branch
+// fleet-seeded-create-3: the console's fleet path), layered on
+// fleetSeededCreate2WriteCensusInventory (main's newest at origin/main
+// 772aabbb0, the slice 2 merge).
+// Reviewed by the branch author against the source. No class or site kind
+// changes; two units are new, two tables, four seed units and one
+// retirement primitive are re-pinned.
+//
+// New (Task 15, the fleet seeds door):
+//
+// - Server.fleetSeedTransition (internal/console/apifleetseeds.go): the
+// one record write behind the door's three handlers
+// (handleFleetSeedPlaced, handleFleetSeedFailed,
+// handleFleetSeedRolledBack, through fleetSeedDoor, which hold no site
+// of their own). Under the app's record lock, after the caller's
+// ownership is checked again there, it moves the record's own file seed
+// by provision.SetRecordSeed: SeedPlace, SeedFail (with the reason the
+// code maps to and held) or SeedRolledBack, each bound to the record's
+// region and box as read under the lock. A record already where the op
+// would put it is not written; an aborted seed takes only
+// copy-in-storage, over any reason, recording where the copy is held
+// and keeping the reason it has (FS-30 only over none; Task 16 review
+// round 2, P2-B). It then
+// deletes the seed's fleet snapshot on placed (a rolled-back seed's
+// goes with its finish) and bumps the serial. The finish that
+// follows rolled-back runs after the lock is released, through
+// finishSeed, whose own entry (finishSeedOnce) is unchanged.
+// record-writer / key:SetRecordSeed, as the other seed doors' writers.
+//
+// Re-pinned (route tables, no record write):
+// - var routeDecls: the door's three POST routes beside the replica doors.
+// - var linkedPolicies: the same three as linkedRefuse, beside the replica
+// doors' rows.
+//
+// Re-pinned (Task 16, file seeds on a customer fleet):
+// - Server.runImportUpload (console): the snapshot's store and key come
+// from the record (seedSnapshotTarget, decided before the hand-over): a
+// fleet file seed's to the deployment bucket at
+// seeds.FleetSnapshotKey, create-only, every other to the data bucket
+// as before. The same SetRecordSeed abort and publish writes.
+// - Server.importDeleteRule (console): fileSeedUnreadied now takes the
+// record, so a fleet file seed that is ready also reaches
+// fileSeedDeleteRule. Its own writes are unchanged.
+// - Server.fileSeedDeleteRule (console, plan D9, R1-5): a fleet file seed
+// reserving or ready is aborted by SetRecordSeed with SeedAbort (from
+// either state), a region one as before with SeedAbortFileUploadBecause;
+// an aborted fleet one is refused 409 (FS-33, or FS-34 from its held
+// place) with no write. Rolled-back still finishes.
+// - Server.finishSeedOnce (console): a fleet file seed's snapshot is
+// deleted from the deployment bucket at its fleet key (no data bucket
+// needed), and its replica is never touched (the fleet's own, proved
+// gone by its box). The record delete, by CAS or retirement, as before.
+//
+// The fleet seed hold in one place (Task 16 review P1-1):
+// - Server.retireRecordWithLifetimeLocked (console, re-pinned): before
+// any retirement step, under the app and hostname locks, a record that
+// is a fleet file seed neither placed nor rolled-back is refused with
+// fleetSeedHoldError (fleetSeedHold). Its record-key sites are
+// unchanged. key-site / key:RecordKey, as before.
+// - Server.retireLegacyInstanceRecord (console, new): retireHostRecord's
+// claims-off, lifetimes-off instance branch. It reads the record's body
+// (a Get of RecordKey), asks the same hold of its region and seed, and
+// deletes by release.DeleteIfMatch on the etag of that read (review
+// round 2, P2-A): a record written since answers ErrCASConflict, an
+// absent key is done. key-site / key:RecordKey, as deleteRead, its
+// sibling delete bound to a read.
+// - Slice 3 review P3-1, both re-pinned again: the hold is asked of the
+// stored body (fleetSeedHoldRaw: its region and seed alone), so a body
+// the full decode rejects is still held, and one carrying a seed the
+// hold cannot read is refused. No site changes.
+// - Slice 3 CI: retireLegacyInstanceRecord reads through the judged
+// reader (observeRecord) the lifetimes audit requires, in place of a
+// raw Get of RecordKey; the bound delete is unchanged.
+//
+// Not in the inventory, because they write no record: seedFleetReady,
+// fleetSeedSnapshots (the sweep's fleet listing; the sweep's own record
+// write stays in abandonSeed), unfinishedFleetFileSeeds and
+// fleetSeedPurgeRefusal (a read and a refusal ahead of every purge
+// entrance), and beginFileSeed's fleet branch (its record write is
+// createSeedRecord's, as in slice 1).
+//
+// provision.SeedFail gains held (decision D12); it is a transition passed
+// to SetRecordSeed, not a census unit, and SetRecordSeed's digest stands.
+func fleetSeededCreate3WriteCensusInventory() []censusEntry {
+ entries := append([]censusEntry(nil), fleetSeededCreate2WriteCensusInventory()...)
+ for _, r := range []censusEntry{
+ {"internal/console/routedecls.go", "var routeDecls", "key-site", "lit:instances,lit:sidecars", "e25fb0d3dbac6d7886d05636ae0a3fc09180e3ed699e1a9b2a7dc7b1c8e8d328"},
+ {"internal/console/linkedpolicy.go", "var linkedPolicies", "key-site", "lit:instances,lit:sidecars", "c4139a1a2795e47d76f3c49bb761c15a849035942a4dcfa5a9ea631be61708b9"},
+ {"internal/console/apiinstanceimport.go", "Server.importDeleteRule", "record-writer", "key:SetRecordSeed", "da79f5bcda6ded08d92693d997fa6c8dbe2fe0eedfdd52dbd083f18a184768fe"},
+ {"internal/console/apiinstanceimport.go", "Server.runImportUpload", "record-writer", "key:SetRecordSeed", "051483202bca1a0af137b0181cf5c7e59c71c0c79511ef501e0f35ea1428e805"},
+ {"internal/console/seedfile.go", "Server.fileSeedDeleteRule", "record-writer", "key:SetRecordSeed", "c3872951d6f0f0a469eb93828843153c023a408df8672a7e11c08cb1c8937d6b"},
+ {"internal/console/seedfinish.go", "Server.finishSeedOnce", "key-site", "key:RecordKey", "f5da4e619ec229aef9ae9559cf347b62dbd6e0556b325d5ca6ad8f56c09f859d"},
+ {"internal/console/lifetimes_retire.go", "Server.retireRecordWithLifetimeLocked", "key-site", "key:RecordKey", "c3e439af5d9b34811cba7b3576f86f734e6741e4e3aad20ec0665f893e84b1d4"},
+ } {
+ replaced := false
+ for i, e := range entries {
+ if e.File == r.File && e.Unit == r.Unit {
+ if e.Class != r.Class || e.Kinds != r.Kinds {
+ panic("fleet-seeded-create-3 census: classification changed for " + r.File + ":" + r.Unit)
+ }
+ entries[i], replaced = r, true
+ break
+ }
+ }
+ if !replaced {
+ panic("fleet-seeded-create-3 census: re-pin of an unlisted unit " + r.File + ":" + r.Unit)
+ }
+ }
+ return append(entries,
+ censusEntry{"internal/console/hostclaimops.go", "Server.retireLegacyInstanceRecord", "key-site", "key:RecordKey", "c6a7984498ee546052b3220e766cbb1a75ca7df69c60fd73cbf3b7f3baf21e3c"},
+ censusEntry{"internal/console/apifleetseeds.go", "Server.fleetSeedTransition", "record-writer", "key:SetRecordSeed", "44b66548aa5c3cafd85d240edbd4bd48e7f3ccd66dfce76facd5d20561738265"},
+ )
+}
diff --git a/internal/provision/plan9_b8_census_test.go b/internal/provision/plan9_b8_census_test.go
index 359db1a97..f91fcf000 100644
--- a/internal/provision/plan9_b8_census_test.go
+++ b/internal/provision/plan9_b8_census_test.go
@@ -366,7 +366,7 @@ func TestPlan9B8RecordWriteCensus(t *testing.T) {
if len(got) < 100 {
t.Fatalf("census found only %d units under %s; the walk is broken", len(got), root)
}
- inventory := fleetSeededCreate2WriteCensusInventory()
+ inventory := fleetSeededCreate3WriteCensusInventory()
problems := append(censusDiff(inventory, got), censusPolicy(inventory)...)
if len(problems) > 0 {
t.Fatalf("record-write census rejected %d site(s); update the explicit inventory only after reviewing the source:\n %s", len(problems), strings.Join(problems, "\n "))
diff --git a/internal/provision/seed.go b/internal/provision/seed.go
index d48289422..cda366afa 100644
--- a/internal/provision/seed.go
+++ b/internal/provision/seed.go
@@ -14,17 +14,23 @@ import (
// SeedSource is a record's seed (seeded-instances spec §3.2). The run series
// declared its Kind and State; those keep their json tags.
type SeedSource struct {
- ClaimID string `json:"claim_id,omitempty"`
- ID string `json:"id"` // random, minted with the seed; never reused
- Kind string `json:"kind"` // seeds.KindReplica | seeds.KindImport | seeds.KindDemoClaim
- From string `json:"from,omitempty"` // replica: the source host
- TXID string `json:"txid,omitempty"` // replica: the TXID actually restored
- SHA256 string `json:"sha256"` // of snapshot.db
- Bytes int64 `json:"bytes"`
- State string `json:"state"` // seeds.State*
- Reason string `json:"reason,omitempty"` // set with refused, and with aborted when the abort names why
- By string `json:"by"` // the caller
- At time.Time `json:"at"`
+ ClaimID string `json:"claim_id,omitempty"`
+ ID string `json:"id"` // random, minted with the seed; never reused
+ Kind string `json:"kind"` // seeds.KindReplica | seeds.KindImport | seeds.KindDemoClaim
+ From string `json:"from,omitempty"` // replica: the source host
+ TXID string `json:"txid,omitempty"` // replica: the TXID actually restored
+ SHA256 string `json:"sha256"` // of snapshot.db
+ Bytes int64 `json:"bytes"`
+ State string `json:"state"` // seeds.State*
+ Reason string `json:"reason,omitempty"` // set with refused, and with aborted when the abort names why
+ // Held is where a fleet file seed's copy still is, when its box could
+ // not prove it gone (decision D12): SeedHeldReplica, SeedHeldStaging
+ // or SeedHeldBoth, set only beside the copy-in-storage reason. The
+ // console builds the location a member reads from it and the host,
+ // never from text a box sent.
+ Held string `json:"held,omitempty"`
+ By string `json:"by"` // the caller
+ At time.Time `json:"at"`
// Replaces is import-only. VerifyHash also gates a fresh demo claim.
Replaces string `json:"replaces,omitempty"` // the addr the swap replaces
VerifyHash string `json:"verify_hash,omitempty"` // sha256 of the verify token (§5.4)
@@ -188,15 +194,25 @@ func SeedAbortFileUploadBecause(id, reason string) func(*Record) error {
// SeedFail is a box's terminal placement failure (design §3.6): a file seed
// from ready to aborted, with Reason. Never an import (SeedRefuse is
-// unchanged). It also accepts an aborted file seed and sets only Reason
-// (Decision D6), so a rollback that finds a copy can say so.
-func SeedFail(id, reason string) func(*Record) error {
+// unchanged). It also accepts an aborted file seed and sets only Reason and
+// Held (Decision D6), so a rollback that finds a copy can say so. held is
+// "", "replica", "staging" or "both" (Decision D12): which of the host's
+// two storage locations still holds a copy. It is set, or cleared, on every
+// call; only copy-in-storage passes a non-empty one. Any other held is
+// refused and changes nothing.
+func SeedFail(id, reason, held string) func(*Record) error {
return func(rec *Record) error {
+ switch held {
+ case "", SeedHeldReplica, SeedHeldStaging, SeedHeldBoth:
+ default:
+ return fmt.Errorf("provision: seed %s: held %q is not a place", id, held)
+ }
if err := seedIn(rec, id, seeds.KindFile, seeds.StateReady, seeds.StateAborted); err != nil {
return err
}
rec.Seed.State = seeds.StateAborted
rec.Seed.Reason = reason
+ rec.Seed.Held = held
return nil
}
}
diff --git a/internal/provision/seed_test.go b/internal/provision/seed_test.go
index 9da835c01..7ee290c0f 100644
--- a/internal/provision/seed_test.go
+++ b/internal/provision/seed_test.go
@@ -311,7 +311,7 @@ func TestSeedTransitionTable(t *testing.T) {
{seeds.KindFile, seeds.StateReady}: seeds.StatePlaced,
{seeds.KindImport, seeds.StateSwapped}: seeds.StatePlaced}},
"publish file": {SeedPublishFile, map[cell]string{{seeds.KindFile, seeds.StateReserving}: seeds.StateReady}},
- "fail": {func(id string) func(*Record) error { return SeedFail(id, "x") }, map[cell]string{
+ "fail": {func(id string) func(*Record) error { return SeedFail(id, "x", "") }, map[cell]string{
{seeds.KindFile, seeds.StateReady}: seeds.StateAborted,
{seeds.KindFile, seeds.StateAborted}: seeds.StateAborted}},
"abort file upload": {func(id string) func(*Record) error { return SeedAbortFileUploadBecause(id, "no") },
@@ -767,22 +767,36 @@ func TestUnfinishedFilePlacedIsFinished(t *testing.T) {
func TestSeedFailFileOnly(t *testing.T) {
seed := testSeed(t, seeds.KindFile, seeds.StateReady)
rec := Record{Seed: seed}
- if err := SeedFail(seed.ID, "placing-failed")(&rec); err != nil || rec.Seed.State != seeds.StateAborted || rec.Seed.Reason != "placing-failed" {
+ if err := SeedFail(seed.ID, "placing-failed", "")(&rec); err != nil || rec.Seed.State != seeds.StateAborted || rec.Seed.Reason != "placing-failed" || rec.Seed.Held != "" {
t.Fatalf("ready: %v %+v", err, rec.Seed)
}
- if err := SeedFail(seed.ID, "copy-in-storage")(&rec); err != nil || rec.Seed.State != seeds.StateAborted || rec.Seed.Reason != "copy-in-storage" {
+ // An aborted file seed keeps its state and takes the new Reason and
+ // Held (decisions D6, D12).
+ if err := SeedFail(seed.ID, "copy-in-storage", SeedHeldBoth)(&rec); err != nil || rec.Seed.State != seeds.StateAborted || rec.Seed.Reason != "copy-in-storage" || rec.Seed.Held != SeedHeldBoth {
t.Fatalf("aborted: %v %+v", err, rec.Seed)
}
+ // Held is set, or cleared, on every call.
+ if err := SeedFail(seed.ID, "copy-in-storage", SeedHeldReplica)(&rec); err != nil || rec.Seed.Held != SeedHeldReplica {
+ t.Fatalf("held replica: %v %+v", err, rec.Seed)
+ }
+ if err := SeedFail(seed.ID, "not-kept", "")(&rec); err != nil || rec.Seed.Held != "" || rec.Seed.Reason != "not-kept" {
+ t.Fatalf("held cleared: %v %+v", err, rec.Seed)
+ }
+ // A held outside the four values is refused, and changes nothing.
+ before := *rec.Seed
+ if err := SeedFail(seed.ID, "copy-in-storage", "elsewhere")(&rec); err == nil || *rec.Seed != before {
+ t.Fatalf("held elsewhere: %v %+v", err, rec.Seed)
+ }
for _, c := range []struct{ kind, state string }{
{seeds.KindImport, seeds.StateReady}, {seeds.KindImport, seeds.StateAborted},
{seeds.KindFile, seeds.StateReserving}, {seeds.KindFile, seeds.StatePlaced},
} {
other := testSeed(t, c.kind, c.state)
- if err := SeedFail(other.ID, "x")(&Record{Seed: other}); !errors.Is(err, ErrSeedConflict) {
+ if err := SeedFail(other.ID, "x", "")(&Record{Seed: other}); !errors.Is(err, ErrSeedConflict) {
t.Errorf("%s %s: %v", c.kind, c.state, err)
}
}
- if err := SeedFail("sd_other", "x")(&Record{Seed: testSeed(t, seeds.KindFile, seeds.StateReady)}); !errors.Is(err, ErrSeedConflict) {
+ if err := SeedFail("sd_other", "x", "")(&Record{Seed: testSeed(t, seeds.KindFile, seeds.StateReady)}); !errors.Is(err, ErrSeedConflict) {
t.Errorf("another id: %v", err)
}
}
diff --git a/internal/provision/testdata/plan14-root-reads-chain.tsv b/internal/provision/testdata/plan14-root-reads-chain.tsv
index 0af9c5c7a..15eb27557 100644
--- a/internal/provision/testdata/plan14-root-reads-chain.tsv
+++ b/internal/provision/testdata/plan14-root-reads-chain.tsv
@@ -267,3 +267,4 @@ plan14-root-reads-plan-domains-2a.tsv 89f2b0e097f2de04bcef403f0b4aaa7a56a17dc7d0
plan14-root-reads-edge-held-cap.tsv f06c832e5595b5a0c256639131d094a94da4505d0e64586813c357cb7eea8f33
plan14-root-reads-fleet-seeded-create-1.tsv 5ce0990b80e0447439484d36a7a87af70708aa5ce113491aecc09d87167277f0
plan14-root-reads-fleet-seeded-create-2.tsv 8a0a9cca336d3e695b79990a9aeda17f5ee8d74908752944f7dcd129918c80fc
+plan14-root-reads-fleet-seeded-create-3.tsv 8a0a9cca336d3e695b79990a9aeda17f5ee8d74908752944f7dcd129918c80fc
diff --git a/internal/provision/testdata/plan14-root-reads-fleet-seeded-create-3.tsv b/internal/provision/testdata/plan14-root-reads-fleet-seeded-create-3.tsv
new file mode 100644
index 000000000..e50973291
--- /dev/null
+++ b/internal/provision/testdata/plan14-root-reads-fleet-seeded-create-3.tsv
@@ -0,0 +1,3 @@
+# Census overlay fleet-seeded-create-3, written by census-propose (#369). census-ruling-fleet-seeded-create-3, approved on #280 before the merge; the approval card is docs/superpowers/notes/census-proposal-fleet-seeded-create-3.md.
+# 0 body, 0 sites, 1 envelope: each changed unit re-frozen at its existing disposition with its claim appended.
+@coverage internal/provision 73245afe0bd5cf07ba7f8aeac19fbddc6eeac4bf0a95168e99486aeda1a86922
diff --git a/parity/parity.tsv b/parity/parity.tsv
index c9c4bb66b..4c33283a1 100644
--- a/parity/parity.tsv
+++ b/parity/parity.tsv
@@ -268,5 +268,5 @@ alert-signing-key platform internal GET /alerts/signing-key The public key al
legacy-apps platform internal GET /apps ; GET /apps/{app} Old URLs kept as redirects into the account.
billing-webhook platform internal POST /billing/webhook Stripe calls it.
ses-events platform internal POST /api/ses/events Amazon SES delivery events.
-box-doors platform internal POST /api/fleet/enrol ; GET /api/box/interactive/{id} ; GET /api/box/runs/{id} ; POST /api/fleet/replicas/{account}/{app}/{host}/coordinator ; POST /api/fleet/replicas/{account}/{app}/{host}/release ; POST /api/fleet/replicas/{account}/{app}/{host}/deploy Doors boxes and managed fleets call, not people.
+box-doors platform internal POST /api/fleet/enrol ; GET /api/box/interactive/{id} ; GET /api/box/runs/{id} ; POST /api/fleet/replicas/{account}/{app}/{host}/coordinator ; POST /api/fleet/replicas/{account}/{app}/{host}/release ; POST /api/fleet/replicas/{account}/{app}/{host}/deploy ; POST /api/fleet/seeds/{account}/{app}/{host}/placed ; POST /api/fleet/seeds/{account}/{app}/{host}/failed ; POST /api/fleet/seeds/{account}/{app}/{host}/rolledback Doors boxes and managed fleets call, not people.
plumbing platform internal __demo-snapshot ; __registry-child ; __rootfs-check-probe ; __rootfs-check-prepare ; __cgexec ; __cgprobe Words the binary runs itself as, dispatched before the command switch.
diff --git a/scripts/gitleaks-gate/notscanned.go b/scripts/gitleaks-gate/notscanned.go
index 20d1efbd7..7050970e6 100644
--- a/scripts/gitleaks-gate/notscanned.go
+++ b/scripts/gitleaks-gate/notscanned.go
@@ -30,6 +30,7 @@ var notScanned = []string{
"internal/provision/fleet_public_routes_census_test.go",
"internal/provision/fleet_seeded_create_1_census_test.go",
"internal/provision/fleet_seeded_create_2_census_test.go",
+ "internal/provision/fleet_seeded_create_3_census_test.go",
"internal/provision/instance_egress_sizes_census_test.go",
"internal/provision/instance_restore_658_census_test.go",
"internal/provision/linked_deployments_slice1_census_test.go",