feat: place replica copies on eligible fleet boxes
Reconcile opted-in apps through stable, distinct assignment sets under the fleet and publication locks. Preserve desired counts during loss, drain and detach, retain termination obligations, and retry incomplete writes. Keep legacy fleet bucket reads unchanged and pin placement read counts. The box-side verified-manifest carrier and latest-count start fence remain unresolved. Production activation stays blocked; details and validation are in the slice 3a SDD report. No push or deployment is included.
Co-Authored-By: Codex (gpt-6-astra) <noreply@openai.com>
internal/console/appcopies.go+5 −0internal/console/applocks.go+28 −0internal/console/fleetbox.go+31 −7internal/console/fleetrelabel.go+19 −2internal/console/fleets.go+11 −1internal/console/replicaplacement.go+341 −0internal/console/replicaplacement_test.go+443 −0internal/console/store.go+4 −2
Intent
<task-notification> <task-id>bs2a9gfzw</task-id> <tool-use-id>toolu_018GjgaeWNhkTrF85HZLi3G8</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/7c5a7d70-0e28-42b9-896c-5d73b2d2a05d/tasks/bs2a9gfzw.output</output-file> <status>completed</status> <summary>Background command "Wait for Task 2 fix round 2 to finish" completed (exit code 0)</summary> </task-notification>
<task-notification> <task-id>biihgjvjf</task-id> <tool-use-id>toolu_01FN63uWn6PbkeHfz2cbX7Ar</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/7c5a7d70-0e28-42b9-896c-5d73b2d2a05d/tasks/biihgjvjf.output</output-file> <status>completed</status> <summary>Background command "Wait for CI verdict on 1e81aefe" completed (exit code 0)</summary> </task-notification>
<task-notification> <task-id>af4e2cb86adca7908</task-id> <tool-use-id>toolu_01K1AN8PLY3LRfLKxmQcgRm2</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/7c5a7d70-0e28-42b9-896c-5d73b2d2a05d/tasks/af4e2cb86adca7908.output</output-file> <status>completed</status> <summary>Agent "Re-review Task 2 fix round 2" finished</summary> <note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note> <result>### Finding Verdicts - **Route-writer inventory missing the three replica writers.** ADDRESSED. `internal/registry/forward_writers_test.go` adds `replicaWriterCase` for Set, Seed, Delete and Replace. Set and Seed enclose `setReplicaAssignment`, and Delete and Replace are listed in `boolWriters`. Set and Seed refuse a forward row with `ErrForwardRow` at `replicas.go:81-83`. Delete and Replace return false with no change, because of the whole-row equality checks at `replicas.go:~114` and `~143`. Each positive fixture changes a row. - **PutForward `fleet_box` conflict arm: test or SQL?** ADDRESSED, the test was the thing to change. `forward_test.go:~278` now pins `CASE WHEN excluded.fleet_boxes <> '' THEN '' WHEN excluded.fleet_label <> '' ...`. A legacy forward row has `fleet_boxes = ''`, so it falls through to exactly the old two arms. The new arm only changes rows that carry a replica set, and clearing the single-box binding there is correct. - **SnapshotFingerprint changed for legacy rows.** ADDRESSED. In `registry.go:~4283-4313`, `fleet_boxes` and `replica_incarnation` move into `snapshotWhenSetCols`, which hashes them only when non-empty (`:4409-4413`). `copies` and `replica_revision` move into `snapshotPairCols`, which hashes them only when non-zero (`:4416-4420`). The diff edits no pinned digest test: only `forward_test`, `forward_writers_test` and `replicas_test` change in the registry. The new `TestReplicaSnapshotColumnsOnlyWhenSet` checks each column both ways: setting it changes the digest, clearing it restores the original. - **Activator and release failures: environment or branch?** ADDRESSED. - The seven activator tests pass three times each in isolation and in the full activator run. - The socket failures name an over-long `$HOME/.cache/sr2-hang/tmp` path, which points to the environment. - `TestPlan14GenerationPinsPrivateMount` fails identically on afbdc02. - The 21 host failures (55 events) reproduce name for name on the base. - `git diff afbdc02 --stat` over the affected activator and release files is empty. - The classification is reasonable. - **CI timed out silently; find and fix any branch-caused hang.** ADDRESSED. The hang is found and fixed: `TestAllocationBoundToAppLifetime` deadlocked on the branch's name lock. It reproduced at HEAD with a 30s timeout and passes on afbdc02. The pause deadline then exposed a second wait that could block forever, the `TestLateSlotWriteDoesNotAbandonTheAllocation` race. It is fixed with an explicit handoff (`lifetimes_create_test.go:~1170-1172`). The final full console run passed in 822s on tmpfs. ### New Breakage in the Fix Diff None Critical or Important. Your four questions: - **(a) Production deadlock: none. This was a fixture problem.** - Every production purge that can run beside a create takes `s.lockApp` first: `sweepTrashedApp` (`lifetimes_purge.go:~190`), `purgeOne` and `expireOne` (`expirypass.go`), and the ownership door. A create holds that same app lock for all of `createRecordWithLifetimeLocked` (`lifetimes_create.go:44`, `withAppHost`). So on main an in-process purge already waited for the in-flight create. The name lock adds no new wait. - The lock order is app lock then name lock on both sides (`copiespublication.go:76-77`, `:256-261`), so the locks cannot wait on each other in a cycle. - The only purge without the app lock is legacy `MaterializeApps` (`materialize.go:431`). Its wait is bounded by the create finishing, and the create never waits on anything materialize holds. - A slow bucket write blocks a purge only as long as it did on main. - The test's `purgeShop` calls `Store.PurgeAppRow` directly, with no app lock, to model another console process. Sharing the `*Store` gave that "other process" the first console's in-memory name locks. Opening a second `Store` (`lifetimes_create_test.go:~238-247`) is the faithful model, and all assertions are kept. - **(b) The three expectation changes are each backed by an authorized change.** - S3 cap 415 to 416: the matched base run differs only at promote, 18 to 19 requests. Ruling P7 (`task-1b-resume.md:3`) allows one default-config GET per mutation, and `perfwrites_test.go:339` already pins promote at 19. - Door count 76 to 77: the copies door is registered with `svcrole.Set{}` (`authcli.go:1022`), so it is closed to service credentials, and it is already listed (`svcroutes_test.go:262`). - Lock table: `finishCopiesClaimCreate` (`copiespublication.go:335`) is the private-storage wrapper from fix round 1 around `finishClaimCreate`. Pinning its single caller and adding a negative fixture tightens the guard rather than loosening it. - **(c) The `kind <> 'forward'` conditions are correct but cannot actually fire.** They sit on the UPDATE in `setReplicaAssignment` and the DELETEs in Delete/Replace (`replicas.go:~93, ~117, ~145`). Every one is preceded by a check that already rules out a forward row: `IsForward()` in setReplicaAssignment, and a pre-check `observed.Kind == "instance"` plus row equality in Delete/Replace. That is harmless, with one minor caveat: `DeleteReplicaAssignment` sets `deleted = true` without checking rows affected. If the SQL guard ever did filter the row, the call would report true while deleting nothing. - **(d) The reordered copy admission keeps every refusal.** `copiesCreateCheck` moved from just after the name lock to just after `lifetimeAppCheck` (`lifetimes_create.go:~80`). It is still under both locks and still before `regionalRecheck`, `admit`, `BeginAllocation` and any write. The only effect is that the purged-app 404 wins again, as on the base. Its one side effect is stamping `rec.Hibernate`, and none of the checks it now follows reads that field (`firstKindRecheck` reads `Runtime` and `DerivesPaths`). `createRecordMarked` (`hostsused.go:565-568`) keeps the old order, but it has no lifetime check that could be overtaken. ### Out-of-Scope Observations - The console run with an on-disk TMPDIR took 1227s and hit the 20-minute limit; the tmpfs run took 822s. The partial CI weight sum is 305s. If any CI worker runs console tests without tmpfs, it will still time out at the package level. That is not a hang, but worth watching. - Test runs used `TMPDIR=/tmp/g`, which follows the project's socket-test convention. On docs-t1, `/tmp` is the shared RAM disk, so its cleanup matters. The report says the owned roots were removed. - The census seal, the registry coverage hash and the record-write digest (`9ced0ee0…`) are still pending independent approval, as the report says. ### Verdict **Fix round:** All findings addressed, no new Critical/Important breakage</result> <usage><subagent_tokens>104284</subagent_tokens><tool_uses>29</tool_uses><duration_ms>300927</duration_ms></usage> </task-notification>
Attributed to this commit: 13.6 g CO₂e (1,631,469 tokens). This is an attribution, not a measurement — usage counted from this commit's own marker forward to the next one on stateless-replicas-2-placement, never backward from it. A turn that produced more than one commit books all of its tokens to the last one, and a concurrent session on this branch can add to the same figure. Some of it was priced using the shared default rate, because no model-specific factor row exists yet for at least one model involved. The Carbon view has the repo total, which is never derived from this attribution.
diff --git a/internal/console/appcopies.go b/internal/console/appcopies.go| index c192753cd..d2b97e2c4 100644 |
| --- a/internal/console/appcopies.go |
| +++ b/internal/console/appcopies.go |
| @@ -96,6 +96,11 @@ func (s *Server) handleAPICopies(w http.ResponseWriter, r *http.Request) { |
| if ref != nil { |
| return &statelessSelectionError{ref} |
| } |
| + if *req.Copies > 1 { |
| + if err := s.store.markReplicaApp(ctx, acct.ID, app, true); err != nil { |
| + return err |
| + } |
| + } |
| var err error |
| got, err = appconfig.SetCopies(ctx, s.cfg.Releases, acct.Sqid, app, *req.Copies) |
| return err |
diff --git a/internal/console/applocks.go b/internal/console/applocks.go| index b374ad017..2820ec0a3 100644 |
| --- a/internal/console/applocks.go |
| +++ b/internal/console/applocks.go |
| @@ -69,3 +69,31 @@ func (s *Server) lockApp(sqid, app string) func() { |
| unlock() |
| } |
| } |
| + |
| +// tryLock avoids reversing app-before-fleet order in a background pass. |
| +// A busy app is retried on the existing fleet pass. |
| +func (l *keyedLocks) tryLock(key string) (func(), bool) { |
| + l.mu.Lock() |
| + defer l.mu.Unlock() |
| + if l.m == nil { |
| + l.m = make(map[string]*keyedLock) |
| + } |
| + e := l.m[key] |
| + if e == nil { |
| + e = &keyedLock{} |
| + l.m[key] = e |
| + } |
| + if !e.mu.TryLock() { |
| + return nil, false |
| + } |
| + e.refs++ |
| + return func() { |
| + e.mu.Unlock() |
| + l.mu.Lock() |
| + e.refs-- |
| + if e.refs == 0 { |
| + delete(l.m, key) |
| + } |
| + l.mu.Unlock() |
| + }, true |
| +} |
diff --git a/internal/console/fleetbox.go b/internal/console/fleetbox.go| index a443d334f..749cceeb0 100644 |
| --- a/internal/console/fleetbox.go |
| +++ b/internal/console/fleetbox.go |
| @@ -41,7 +41,7 @@ import ( |
| // deployment, platform and fleet, and the console itself report a release |
| // at or above release.FleetBoxLabelFloor, from a complete listing, and |
| // every active box of the fleet has a heartbeat (gates c and d). Unmovable: some record on the fleet fails movable (rule 11). |
| -// Load counts the fleet's records by the box they are labelled to. Static |
| +// Load counts assigned copies, or one for a legacy box label. Static |
| // records count toward neither (fleetLabelsRecord). Records is the |
| // inventory the view was built from (every record placed on the fleet, |
| // static ones included), read only when the fleet has two or more active |
| @@ -52,6 +52,11 @@ type fleetView struct { |
| Unmovable bool |
| Load map[string]int |
| Records []provision.Record |
| + Complete bool |
| + ReplicaApps map[AppRef]bool |
| + ReplicaManifests map[string]*release.Manifest |
| + ReplicaCounts map[AppRef]int |
| + ReplicaSizes map[string]string |
| } |
| // fleetBoxView is one active box of the fleet (registry status "active"), |
| @@ -63,6 +68,7 @@ type fleetView struct { |
| type fleetBoxView struct { |
| Label string |
| Fresh, Draining, RootfsReady, AtRootfsFloor, AtLabelFloor, AtReplicaFloor bool |
| + TotalMiB int64 |
| Labelled bool |
| LastSeen, DrainingSince time.Time |
| Release string |
| @@ -97,6 +103,9 @@ func joinBeats(boxes []fleetBoxView, hbs []status.Box, now time.Time) (unheard b |
| boxes[i].LastSeen = b.GeneratedAt |
| if b.Metrics != nil { |
| boxes[i].Release = b.Metrics.Release |
| + if b.Metrics.MemTotalBytes != nil && boxes[i].Fresh { |
| + boxes[i].TotalMiB = *b.Metrics.MemTotalBytes >> 20 |
| + } |
| boxes[i].AtReplicaFloor = atReplicaFloor(b.Metrics.Release) |
| } |
| } |
| @@ -154,11 +163,16 @@ func fleetLabelsRecord(rec provision.Record) bool { |
| // platform does not manage (Addr, Addrs), and either a rootfs runtime or a |
| // hibernation that is not switched off. An HA record is never movable: HA |
| // hosts are outside 1b's move machinery (controller ruling 3, Task 6), so a |
| -// fleet holding one is never labelled and a drain refuses it. |
| -func movable(rec provision.Record) bool { |
| - if rec.Addr != "" || len(rec.Addrs) > 0 || rec.HA { |
| +// fleet holding one is never labelled and a drain refuses it. An always-on |
| +// binary additionally needs the caller's verified selected stateless manifest. |
| +func movable(rec provision.Record, verified ...*release.Manifest) bool { |
| + if rec.Addr != "" || len(rec.Addrs) > 0 || rec.HA || rec.Unit != "" { |
| return false |
| } |
| + if rec.Runtime == "" && rec.Hibernate != nil && !*rec.Hibernate && len(verified) == 1 { |
| + _, err := provision.WithReplicaAssignmentManifest(context.Background(), rec, verified[0]) |
| + return err == nil |
| + } |
| return rec.Runtime == provision.RuntimeRootfsV1 || rec.Hibernate == nil || *rec.Hibernate |
| } |
| @@ -278,7 +292,11 @@ func (s *Server) loadFleetViewAt(ctx context.Context, fleet string, now time.Tim |
| if s.cfg.Releases == nil { |
| return v, nil |
| } |
| - if len(v.Boxes) < 2 { |
| + v.ReplicaApps, err = s.replicaFleetApps(ctx, fleet) |
| + if err != nil { |
| + return v, err |
| + } |
| + if len(v.Boxes) < 2 && len(v.ReplicaApps) == 0 { |
| if !v.labelled() { |
| return v, nil |
| } |
| @@ -328,7 +346,12 @@ func (s *Server) loadFleetViewAt(ctx context.Context, fleet string, now time.Tim |
| if !fleetLabelsRecord(rec) { |
| continue |
| } |
| - if rec.FleetBox != "" { |
| + if rec.ReplicaAssignment != nil { |
| + v.ReplicaApps[AppRef{Sqid: rec.Account, App: rec.App}] = true |
| + for _, box := range rec.ReplicaAssignment.Boxes { |
| + v.Load[box]++ |
| + } |
| + } else if rec.FleetBox != "" { |
| v.Load[rec.FleetBox]++ |
| } |
| if !movable(rec) { |
| @@ -336,7 +359,8 @@ func (s *Server) loadFleetViewAt(ctx context.Context, fleet string, now time.Tim |
| } |
| } |
| v.HasSidecars = sidecars > 0 |
| - v.Active = whole |
| + v.Complete = whole |
| + v.Active = whole && len(v.Boxes) >= 2 |
| return v, nil |
| } |
diff --git a/internal/console/fleetrelabel.go b/internal/console/fleetrelabel.go| index d258396b1..197751652 100644 |
| --- a/internal/console/fleetrelabel.go |
| +++ b/internal/console/fleetrelabel.go |
| @@ -120,6 +120,12 @@ func (s *Server) fleetRelabelPass(ctx context.Context, now time.Time) error { |
| unlock() |
| continue |
| } |
| + if err := s.reconcileReplicaFleet(ctx, f.Name, v, now); err != nil { |
| + jobFailed(ctx, err) |
| + log.Printf("console: replica placement %s: %v", f.Name, err) |
| + unlock() |
| + continue |
| + } |
| if _, err := s.relabelFleet(ctx, f.Name, v, now); err != nil { |
| log.Printf("console: fleet relabel %s: %v", f.Name, err) |
| jobFailed(ctx, err) |
| @@ -161,7 +167,7 @@ func (s *Server) relabelFleet(ctx context.Context, fleet string, v fleetView, no |
| plan = append(plan, first...) |
| } |
| for _, rec := range v.Records { |
| - if !fleetLabelsRecord(rec) || rec.FleetBox == "" { |
| + if v.replicaRecord(rec) || !fleetLabelsRecord(rec) || rec.FleetBox == "" { |
| continue |
| } |
| reason := v.boxGone(rec.FleetBox, now) |
| @@ -190,7 +196,7 @@ func (s *Server) relabelFleet(ctx context.Context, fleet string, v fleetView, no |
| func (s *Server) planFirstLabelling(ctx context.Context, fleet string, v fleetView) ([]relabel, error) { |
| var plan []relabel |
| for _, rec := range v.Records { |
| - if !fleetLabelsRecord(rec) || rec.FleetBox != "" || !movable(rec) { |
| + if v.replicaRecord(rec) || !fleetLabelsRecord(rec) || rec.FleetBox != "" || !movable(rec) { |
| continue |
| } |
| b, ok, err := s.readFleetBinding(ctx, fleet, rec.Host) |
| @@ -447,6 +453,9 @@ func (s *Server) drainBox(ctx context.Context, fleet, label string) (stuck []str |
| strand := map[string]bool{} |
| var plan []relabel |
| for _, rec := range recs { |
| + if v.replicaRecord(rec) { |
| + continue |
| + } |
| if !fleetLabelsRecord(rec) || (rec.FleetBox != "" && rec.FleetBox != label) { |
| continue |
| } |
| @@ -475,6 +484,14 @@ func (s *Server) drainBox(ctx context.Context, fleet, label string) (stuck []str |
| return nil, err |
| } |
| log.Printf("console: fleet drain %s/%s: draining since %s, %d records to move", fleet, label, time.Unix(0, since).UTC().Format(time.RFC3339Nano), len(plan)) |
| + for i := range v.Boxes { |
| + if v.Boxes[i].Label == label { |
| + v.Boxes[i].Draining = true |
| + } |
| + } |
| + if err := s.reconcileReplicaFleet(ctx, fleet, v, now); err != nil { |
| + return nil, err |
| + } |
| moved := s.writeRelabels(ctx, fleet, plan, now) |
| if moved < len(plan) { |
| log.Printf("console: fleet drain %s/%s: moved %d of %d records; the relabel worker moves the rest", fleet, label, moved, len(plan)) |
diff --git a/internal/console/fleets.go b/internal/console/fleets.go| index 39b54b7f0..a583c40d3 100644 |
| --- a/internal/console/fleets.go |
| +++ b/internal/console/fleets.go |
| @@ -601,13 +601,18 @@ func (s *Server) handleAPIFleetDetachBox(w http.ResponseWriter, r *http.Request) |
| jsonError(w, http.StatusConflict, msgDetachNotDrained(fleet.Name, label)) |
| return |
| } |
| + warnings := s.replicaDetachWarnings(r.Context(), fleet.Name, label) |
| if err := reg.SetFleetBoxStatus(fleet.Name, label, "detached"); err != nil { |
| log.Printf("console: fleet detach %s/%s/%s: %v", acct.Sqid, fleet.Name, label, err) |
| jsonError(w, http.StatusInternalServerError, "could not detach the box — try again") |
| return |
| } |
| s.audit(acct, fleet.Name, addr, "fleet-detach-box", "detached "+fleet.Name+"/"+label+" (cli)") |
| - writeJSON(w, http.StatusOK, map[string]any{}) |
| + reply := map[string]any{} |
| + if len(warnings) > 0 { |
| + reply["warnings"] = warnings |
| + } |
| + writeJSON(w, http.StatusOK, reply) |
| } |
| // handleAPIFleetDrainBox answers `carlos fleets drain`: the first of the two |
| @@ -1601,12 +1606,17 @@ func (s *Server) handleFleetDetachBoxPage(w http.ResponseWriter, r *http.Request |
| back("err", msgDetachNotDrainedPage(fleet.Name, label)) |
| return |
| } |
| + warnings := s.replicaDetachWarnings(r.Context(), fleet.Name, label) |
| if err := reg.SetFleetBoxStatus(fleet.Name, label, "detached"); err != nil { |
| log.Printf("console: fleet detach %s/%s/%s: %v", acct.Sqid, fleet.Name, label, err) |
| back("err", "Could not detach the box — try again.") |
| return |
| } |
| s.audit(acct, fleet.Name, addr, "fleet-detach-box", "detached "+fleet.Name+"/"+label+" (console)") |
| + if len(warnings) > 0 { |
| + back("ok", strings.Join(warnings, "\n")) |
| + return |
| + } |
| back("ok", "Detached "+fleet.Name+"/"+label+".") |
| } |
diff --git a/internal/console/replicaplacement.go b/internal/console/replicaplacement.go| new file mode 100644 |
| index 000000000..93ae0cba8 |
| --- /dev/null |
| +++ b/internal/console/replicaplacement.go |
| @@ -0,0 +1,341 @@ |
| +package console |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "fmt" |
| + "os" |
| + "slices" |
| + "sort" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/appconfig" |
| + "github.com/carlosframework/platform/internal/apppolicy" |
| + "github.com/carlosframework/platform/internal/cgroup" |
| + "github.com/carlosframework/platform/internal/provision" |
| + "github.com/carlosframework/platform/internal/registry" |
| + "github.com/carlosframework/platform/internal/release" |
| + "github.com/carlosframework/platform/internal/replicas" |
| + "github.com/carlosframework/platform/internal/version" |
| +) |
| + |
| +// The marker is discovery, never desired-count authority. Persist it before |
| +// publishing config so a crash before the first assignment remains retryable. |
| +func (s *Store) markReplicaApp(ctx context.Context, account int64, app string, enabled bool) error { |
| + return s.withAutoAppSQL(ctx, account, app, "sql.MarkReplicaApp", func(st *Store) error { |
| + _, err := st.db.ExecContext(ctx, `UPDATE apps SET copies_configured = ? WHERE account_id = ? AND app = ? AND deleted_at = 0`, enabled, account, app) |
| + return err |
| + }) |
| +} |
| + |
| +func (s *Server) replicaFleetApps(ctx context.Context, fleet string) (map[AppRef]bool, error) { |
| + rows, err := s.store.db.QueryContext(ctx, `SELECT a.sqid, p.app FROM apps p JOIN accounts a ON a.id = p.account_id WHERE p.placement = ? AND p.deleted_at = 0 AND p.copies_configured = 1`, registry.PlacementTarget(fleet)) |
| + if err != nil { |
| + return nil, err |
| + } |
| + defer rows.Close() |
| + out := map[AppRef]bool{} |
| + for rows.Next() { |
| + var a AppRef |
| + if err := rows.Scan(&a.Sqid, &a.App); err != nil { |
| + return nil, err |
| + } |
| + out[a] = true |
| + } |
| + return out, rows.Err() |
| +} |
| + |
| +func replicaRecordKey(rec provision.Record) string { |
| + return provision.RecordKey(rec.Account, rec.App, rec.Host) |
| +} |
| + |
| +func (v fleetView) replicaRecord(rec provision.Record) bool { |
| + return rec.ReplicaAssignment != nil || v.ReplicaApps[AppRef{Sqid: rec.Account, App: rec.App}] |
| +} |
| + |
| +func (s *Server) replicaBuild() string { |
| + if s.consoleBuild != "" { |
| + return s.consoleBuild |
| + } |
| + return version.Build |
| +} |
| + |
| +// Unknown versions pause membership edits. A known but stale member can be |
| +// removed without requiring all other boxes to be fresh (count admission does). |
| +func (s *Server) replicaViewReady(v fleetView, n int) bool { |
| + if !v.Complete || v.HasSidecars || !v.DeploymentCurrent { |
| + return false |
| + } |
| + floor := atStatelessRuntimeFloor |
| + if n > 1 { |
| + floor = atReplicaFloor |
| + } |
| + if !floor(s.replicaBuild()) { |
| + return false |
| + } |
| + for _, b := range v.Boxes { |
| + if !floor(b.Release) { |
| + return false |
| + } |
| + } |
| + return true |
| +} |
| + |
| +func (s *Server) replicaNext(rec provision.Record, v fleetView, n int) (replicas.Assignment, error) { |
| + if !s.replicaViewReady(v, n) { |
| + return replicas.Assignment{}, replicas.ErrFenced |
| + } |
| + m := v.ReplicaManifests[replicaRecordKey(rec)] |
| + if !movable(rec, m) { |
| + return replicas.Assignment{}, replicas.ErrInvalid |
| + } |
| + if _, err := provision.WithReplicaAssignmentManifest(context.Background(), rec, m); err != nil { |
| + return replicas.Assignment{}, err |
| + } |
| + current := replicas.Assignment{Desired: n} |
| + if rec.ReplicaAssignment != nil { |
| + current = *rec.ReplicaAssignment |
| + current.Desired = n |
| + } else if rec.FleetBox != "" { |
| + current.Boxes = []string{rec.FleetBox} |
| + } |
| + sizeName := v.ReplicaSizes[replicaRecordKey(rec)] |
| + if sizeName == "" { |
| + sizeName = "standard" |
| + } |
| + size, ok := cgroup.SizeByName(sizeName) |
| + if !ok { |
| + return replicas.Assignment{}, replicas.ErrInvalid |
| + } |
| + candidates := make([]replicas.Candidate, 0, len(v.Boxes)) |
| + for _, b := range v.Boxes { |
| + eligible := v.replicaEligible(b, rec.Runtime == provision.RuntimeRootfsV1) |
| + if n == 1 { |
| + eligible = atStatelessRuntimeFloor(b.Release) && b.destinationFor(rec.Runtime == provision.RuntimeRootfsV1) |
| + } |
| + eligible = eligible && sizeRefusal([]sizeBox{{Box: b.Label, TotalMiB: b.TotalMiB}}, true, size) == nil |
| + candidates = append(candidates, replicas.Candidate{Label: b.Label, Load: v.Load[b.Label], Eligible: eligible}) |
| + } |
| + return replicas.Place(current, candidates) |
| +} |
| + |
| +// Caller holds fleet and app publication exclusion. Evidence is prepared once |
| +// for the complete fleet before any write, and bound again by the typed CAS. |
| +func (s *Server) placeReplicaRecord(ctx context.Context, rec provision.Record, v fleetView, n int) error { |
| + next, err := s.replicaNext(rec, v, n) |
| + if err != nil { |
| + return err |
| + } |
| + if old := rec.ReplicaAssignment; old != nil && old.Desired == next.Desired && slices.Equal(old.Boxes, next.Boxes) && slices.Equal(old.Retiring, next.Retiring) { |
| + return nil |
| + } |
| + ctx, err = provision.WithReplicaAssignmentManifest(ctx, rec, v.ReplicaManifests[replicaRecordKey(rec)]) |
| + if err != nil { |
| + return err |
| + } |
| + inc, err := provision.Incarnation(rec.Account, rec.App, rec.Host, rec.CreatedAt) |
| + if err != nil { |
| + return err |
| + } |
| + fleet, _ := registry.FleetPlacement(rec.Region) |
| + reg, err := s.openPassRegistry() |
| + if err != nil { |
| + return err |
| + } |
| + for _, box := range next.Boxes { |
| + if err := reg.MarkFleetBoxLabelled(fleet, box, time.Now().UnixNano()); err != nil { |
| + return err |
| + } |
| + } |
| + _, err = provision.SetRecordReplicaAssignment(ctx, s.cfg.Releases, replicas.Identity{Account: rec.Account, App: rec.App, Host: rec.Host, Incarnation: inc}, replicas.Expect{Incarnation: inc, Region: rec.Region, RecordSeq: rec.RecordSeq, Revision: next.Revision}, next) |
| + return err |
| +} |
| + |
| +// The fleet lock is already held. Try app locks to avoid deadlocking a create |
| +// holding app exclusion while waiting for this fleet. All reads precede writes. |
| +func (s *Server) reconcileReplicaFleet(ctx context.Context, fleet string, v fleetView, now time.Time) error { |
| + if !v.Complete || v.HasSidecars || len(v.ReplicaApps) == 0 { |
| + return nil |
| + } |
| + apps := make([]AppRef, 0, len(v.ReplicaApps)) |
| + for a := range v.ReplicaApps { |
| + apps = append(apps, a) |
| + } |
| + sort.Slice(apps, func(i, j int) bool { |
| + if apps[i].Sqid != apps[j].Sqid { |
| + return apps[i].Sqid < apps[j].Sqid |
| + } |
| + return apps[i].App < apps[j].App |
| + }) |
| + for _, a := range apps { |
| + unlock, ok := s.appLocks.tryLock(a.Sqid + "/" + a.App) |
| + if !ok { |
| + return nil |
| + } |
| + defer unlock() |
| + } |
| + ctx = withWriteMemo(ctx) |
| + v.ReplicaManifests = map[string]*release.Manifest{} |
| + v.ReplicaCounts = map[AppRef]int{} |
| + v.ReplicaSizes = map[string]string{} |
| + reg, err := s.openPassRegistry() |
| + if err != nil { |
| + return err |
| + } |
| + policies := map[AppRef]*apppolicy.Policy{} |
| + for _, a := range apps { |
| + acct, err := s.store.AccountBySqid(a.Sqid) |
| + if err != nil { |
| + return err |
| + } |
| + if acct == nil { |
| + return replicas.ErrFenced |
| + } |
| + nameLock := s.store.AppPolicyLock(acct.ID, a.App) |
| + if !nameLock.TryLock() { |
| + return nil |
| + } |
| + defer nameLock.Unlock() |
| + placed, err := s.store.AppPlacement(acct.ID, a.App) |
| + if err != nil { |
| + return err |
| + } |
| + own, err := ownsFleet(reg, acct, registry.PlacementTarget(fleet)) |
| + if err != nil { |
| + return err |
| + } |
| + if !own || placed != registry.PlacementTarget(fleet) { |
| + return replicas.ErrFenced |
| + } |
| + cfg, err := s.copiesDefault(ctx, a.Sqid, a.App) |
| + if err != nil { |
| + return err |
| + } |
| + // A lost config field must not turn a durable set into a legacy label. |
| + n := appconfig.CopiesOf(&cfg.manifest) |
| + if n < 1 { |
| + return replicas.ErrInvalid |
| + } |
| + assigned := false |
| + for _, rec := range v.Records { |
| + if rec.Account == a.Sqid && rec.App == a.App && rec.ReplicaAssignment != nil { |
| + assigned = true |
| + break |
| + } |
| + } |
| + if n == 1 && !assigned { |
| + delete(v.ReplicaApps, a) |
| + if !cfg.explicit { |
| + if err := s.store.markReplicaApp(ctx, acct.ID, a.App, false); err != nil { |
| + return err |
| + } |
| + } |
| + continue |
| + } |
| + v.ReplicaCounts[a] = n |
| + if !s.replicaViewReady(v, n) { |
| + return nil |
| + } |
| + p, _, err := apppolicy.Get(ctx, s.cfg.Releases, s.cfg.ReleasePub, a.Sqid, a.App, now) |
| + if err != nil && !errors.Is(err, os.ErrNotExist) { |
| + return err |
| + } |
| + policies[a] = p |
| + } |
| + records := slices.Clone(v.Records) |
| + sort.Slice(records, func(i, j int) bool { return replicaRecordKey(records[i]) < replicaRecordKey(records[j]) }) |
| + for _, rec := range records { |
| + if !v.replicaRecord(rec) { |
| + continue |
| + } |
| + a := AppRef{Sqid: rec.Account, App: rec.App} |
| + m, err := memoize(ctx, "replica-selected:"+rec.Account+"/"+rec.App+"/"+rec.Channel+"/"+rec.Pin, func() (*release.Manifest, error) { |
| + ver := rec.Pin |
| + if ver == "" { |
| + head, err := release.Channel(ctx, s.cfg.Releases, s.cfg.ReleasePub, rec.Account, rec.App, rec.Channel) |
| + if err != nil { |
| + return nil, err |
| + } |
| + if head == nil { |
| + return nil, replicas.ErrFenced |
| + } |
| + ver = head.Version |
| + } |
| + return memoize(ctx, "replica-manifest:"+release.ManifestKey(rec.Account, rec.App, ver), func() (*release.Manifest, error) { |
| + return release.AuthorizedManifest(ctx, s.cfg.Releases, s.cfg.ReleasePub, rec.Account, rec.App, ver) |
| + }) |
| + }) |
| + if err != nil { |
| + return err |
| + } |
| + v.ReplicaManifests[replicaRecordKey(rec)] = m |
| + if p := policies[a]; p != nil { |
| + v.ReplicaSizes[replicaRecordKey(rec)] = p.SizeFor(rec.Host, rec.CreatedAt) |
| + } |
| + if _, err := s.replicaNext(rec, v, v.ReplicaCounts[a]); err != nil { |
| + return err |
| + } |
| + } |
| + var errs []error |
| + changed := false |
| + for _, rec := range records { |
| + if !v.replicaRecord(rec) { |
| + continue |
| + } |
| + n := v.ReplicaCounts[AppRef{Sqid: rec.Account, App: rec.App}] |
| + next, err := s.replicaNext(rec, v, n) |
| + if err != nil { |
| + return err |
| + } |
| + if err = s.placeReplicaRecord(ctx, rec, v, n); err != nil { |
| + errs = append(errs, err) |
| + continue |
| + } |
| + old := rec.ReplicaAssignment |
| + if old != nil { |
| + for _, box := range old.Boxes { |
| + v.Load[box]-- |
| + } |
| + } else if rec.FleetBox != "" { |
| + v.Load[rec.FleetBox]-- |
| + } |
| + for _, box := range next.Boxes { |
| + v.Load[box]++ |
| + } |
| + changed = changed || old == nil || old.Desired != next.Desired || !slices.Equal(old.Boxes, next.Boxes) || !slices.Equal(old.Retiring, next.Retiring) |
| + } |
| + if changed { |
| + s.bumpSerial(ctx) |
| + } |
| + return errors.Join(errs...) |
| +} |
| + |
| +// SR-2-C10, approved copy. Availability counts distinct eligible survivors, |
| +// never the requested count or a duplicated member. |
| +func (s *Server) replicaDetachWarnings(ctx context.Context, fleet, label string) []string { |
| + apps, err := s.replicaFleetApps(ctx, fleet) |
| + if err != nil || len(apps) == 0 { |
| + return nil |
| + } |
| + v, err := s.loadFleetView(ctx, fleet) |
| + if err != nil || !v.Complete { |
| + return nil |
| + } |
| + warnings := []string{} |
| + for _, rec := range v.Records { |
| + a := rec.ReplicaAssignment |
| + if a == nil || !a.Contains(label) { |
| + continue |
| + } |
| + available := 0 |
| + for _, box := range v.Boxes { |
| + if box.Label != label && a.Contains(box.Label) && v.replicaEligible(box, rec.Runtime == provision.RuntimeRootfsV1) { |
| + available++ |
| + } |
| + } |
| + if available < a.Desired { |
| + warnings = append(warnings, fmt.Sprintf("detaching %s leaves %d of %d copies available. the requested count stays %d", label, available, a.Desired, a.Desired)) |
| + } |
| + } |
| + return slices.Compact(warnings) |
| +} |
diff --git a/internal/console/replicaplacement_test.go b/internal/console/replicaplacement_test.go| new file mode 100644 |
| index 000000000..ce2942779 |
| --- /dev/null |
| +++ b/internal/console/replicaplacement_test.go |
| @@ -0,0 +1,443 @@ |
| +package console |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "errors" |
| + "net/http" |
| + "reflect" |
| + "slices" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/appconfig" |
| + "github.com/carlosframework/platform/internal/provision" |
| + "github.com/carlosframework/platform/internal/registry" |
| + "github.com/carlosframework/platform/internal/release" |
| + "github.com/carlosframework/platform/internal/replicas" |
| +) |
| + |
| +func replicaPlacementWorld(t *testing.T) (*consoleFixture, string, *registry.Registry) { |
| + t.Helper() |
| + fx, token := copiesWorld(t) |
| + if code, out := copiesPut(t, fx, token, `{"copies":2}`); code != 200 { |
| + t.Fatalf("copies: %d %s", code, out) |
| + } |
| + reg := openTestReg(t, fx) |
| + t.Cleanup(func() { reg.Close() }) |
| + return fx, token, reg |
| +} |
| + |
| +func wantReplicaBoxes(t *testing.T, fx *consoleFixture, host string, boxes, retiring []string) *provision.Record { |
| + t.Helper() |
| + rec := shopRec(t, fx, host) |
| + a := rec.ReplicaAssignment |
| + if a == nil || a.Desired != 2 || !slices.Equal(a.Boxes, boxes) || !slices.Equal(a.Retiring, retiring) { |
| + t.Fatalf("%s: assignment %+v; want %v retiring %v", host, a, boxes, retiring) |
| + } |
| + return rec |
| +} |
| + |
| +func TestReplicaPlacementStableAndDistinct(t *testing.T) { |
| + fx, _, reg := replicaPlacementWorld(t) |
| + registerFleetBox(t, reg, "pi", "pi-3") |
| + copiesBeat(t, fx, "pi-3", release.StatelessReplicasFloor, time.Now()) |
| + relabelPass(t, fx) |
| + a := wantReplicaBoxes(t, fx, "a.example.com", []string{"pi-1", "pi-3"}, nil) |
| + b := wantReplicaBoxes(t, fx, "b.example.com", []string{"pi-1", "pi-2"}, nil) |
| + v, err := fx.srv.loadFleetView(context.Background(), "pi") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if !reflect.DeepEqual(v.Load, map[string]int{"pi-1": 2, "pi-2": 1, "pi-3": 1}) { |
| + t.Fatalf("load counts labels instead of copies: %v", v.Load) |
| + } |
| + cs := newCountStore(fx.rel) |
| + fx.srv.cfg.Releases = cs |
| + slices.Reverse(v.Boxes) |
| + slices.Reverse(v.Records) |
| + unlock := fx.srv.lockFleet("pi") |
| + err = fx.srv.reconcileReplicaFleet(context.Background(), "pi", v, time.Now()) |
| + unlock() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if cs.recordPuts() != 0 { |
| + t.Fatal("stable assignment rewritten") |
| + } |
| + if got := shopRec(t, fx, "a.example.com"); !reflect.DeepEqual(got.ReplicaAssignment, a.ReplicaAssignment) { |
| + t.Fatal("a rebalanced") |
| + } |
| + if got := shopRec(t, fx, "b.example.com"); !reflect.DeepEqual(got.ReplicaAssignment, b.ReplicaAssignment) { |
| + t.Fatal("b rebalanced") |
| + } |
| +} |
| + |
| +func TestReplicaPlacementLostAndReturning(t *testing.T) { |
| + for _, spare := range []bool{false, true} { |
| + t.Run(map[bool]string{false: "shortfall", true: "spare"}[spare], func(t *testing.T) { |
| + fx, _, reg := replicaPlacementWorld(t) |
| + relabelPass(t, fx) |
| + if spare { |
| + registerFleetBox(t, reg, "pi", "pi-3") |
| + copiesBeat(t, fx, "pi-3", release.StatelessReplicasFloor, time.Now()) |
| + } |
| + copiesBeat(t, fx, "pi-2", release.StatelessReplicasFloor, time.Now().Add(-time.Hour)) |
| + relabelPass(t, fx) |
| + boxes := []string{"pi-1"} |
| + if spare { |
| + boxes = append(boxes, "pi-3") |
| + } |
| + for _, h := range []string{"a.example.com", "b.example.com"} { |
| + wantReplicaBoxes(t, fx, h, boxes, []string{"pi-2"}) |
| + } |
| + copiesBeat(t, fx, "pi-2", release.StatelessReplicasFloor, time.Now()) |
| + relabelPass(t, fx) |
| + // A heartbeat is not termination proof; the coordinator's ACK is slice 3b. |
| + for _, h := range []string{"a.example.com", "b.example.com"} { |
| + rec := wantReplicaBoxes(t, fx, h, boxes, []string{"pi-2"}) |
| + m, err := release.AuthorizedManifest(context.Background(), fx.rel, fx.pub, fx.sqid, "shop", map[string]string{"edge": "v1", "stable": "v2"}[rec.Channel]) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + ctx, err := provision.WithReplicaAssignmentManifest(context.Background(), *rec, m) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + inc, _ := provision.Incarnation(rec.Account, rec.App, rec.Host, rec.CreatedAt) |
| + _, err = provision.RecordReplicaRetired(ctx, fx.rel, replicas.Identity{Account: rec.Account, App: rec.App, Host: rec.Host, Incarnation: inc}, rec.ReplicaAssignment.Revision, "pi-2") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + relabelPass(t, fx) |
| + if !spare { |
| + boxes = []string{"pi-1", "pi-2"} |
| + } |
| + for _, h := range []string{"a.example.com", "b.example.com"} { |
| + wantReplicaBoxes(t, fx, h, boxes, nil) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestReplicaDetachPreservesDesiredShortfall(t *testing.T) { |
| + fx, token, _ := replicaPlacementWorld(t) |
| + relabelPass(t, fx) |
| + code, _, out := rawReq(t, http.MethodPost, fleetsURL(fx, fx.sqid)+"/pi/boxes/pi-2/detach", token, `{"terminated":true}`) |
| + if code != 200 || !strings.Contains(out, "detaching pi-2 leaves 1 of 2 copies available. the requested count stays 2") { |
| + t.Fatalf("detach: %d %s", code, out) |
| + } |
| + relabelPass(t, fx) |
| + rec := wantReplicaBoxes(t, fx, "a.example.com", []string{"pi-1"}, []string{"pi-2"}) |
| + desired, available, duplicateBoxes := rec.ReplicaAssignment.Desired, len(rec.ReplicaAssignment.Boxes), 0 |
| + seen := map[string]bool{} |
| + for _, box := range rec.ReplicaAssignment.Boxes { |
| + if seen[box] { |
| + duplicateBoxes++ |
| + } |
| + seen[box] = true |
| + } |
| + // TestReplicaDetachPreservesDesiredShortfall |
| + if desired != 2 || available != 1 || duplicateBoxes != 0 { |
| + t.Fatal("detach clamped or duplicated copies") |
| + } |
| + cfg, err := fx.srv.copiesDefault(context.Background(), fx.sqid, "shop") |
| + if err != nil || appconfig.CopiesOf(&cfg.manifest) != 2 { |
| + t.Fatal("config clamped", err) |
| + } |
| + if code, _ := copiesPut(t, fx, token, `{"copies":2}`); code < 400 { |
| + t.Fatal("new count accepted with one eligible box") |
| + } |
| +} |
| + |
| +type replicaFailRead struct { |
| + *countStore |
| + get, list string |
| +} |
| + |
| +func (s *replicaFailRead) Get(ctx context.Context, k string) ([]byte, string, error) { |
| + if k == s.get { |
| + return nil, "", errors.New("injected read failure") |
| + } |
| + return s.countStore.Get(ctx, k) |
| +} |
| +func (s *replicaFailRead) ListETags(ctx context.Context, k string) ([]release.KeyETag, error) { |
| + if k == s.list { |
| + return nil, errors.New("injected page failure") |
| + } |
| + return s.countStore.ListETags(ctx, k) |
| +} |
| + |
| +func TestReplicaIncompleteViewWritesNothing(t *testing.T) { |
| + for _, kind := range []string{"page", "record", "floor", "sidecar"} { |
| + t.Run(kind, func(t *testing.T) { |
| + fx, _, _ := replicaPlacementWorld(t) |
| + fx.srv.fleetInventories.Delete("pi") |
| + cs := newCountStore(fx.rel) |
| + fail := &replicaFailRead{countStore: cs} |
| + fx.srv.cfg.Releases = fail |
| + switch kind { |
| + case "page": |
| + fail.list = provision.RecordsPrefix(fx.sqid, "shop") |
| + case "record": |
| + fail.get = provision.RecordKey(fx.sqid, "shop", "a.example.com") |
| + case "floor": |
| + copiesBeat(t, fx, "pi-2", "unknown", time.Now()) |
| + case "sidecar": |
| + raw, _ := json.Marshal(provision.SidecarRecord{Schema: 1, Account: fx.sqid, App: "shop", Name: "worker", Region: "fleet/pi", Channel: "edge"}) |
| + if _, err := fx.rel.Put(context.Background(), provision.SidecarsPrefix(fx.sqid, "shop")+"worker.json", raw, ""); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + relabelPass(t, fx) |
| + if cs.recordPuts() != 0 { |
| + t.Fatalf("%s: wrote %d records", kind, cs.recordPuts()) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestReplicaPlacementRuntimeFloorAndEligibility(t *testing.T) { |
| + fx, _, _ := replicaPlacementWorld(t) |
| + rec := *shopRec(t, fx, "a.example.com") |
| + m, err := release.AuthorizedManifest(context.Background(), fx.rel, fx.pub, fx.sqid, "shop", "v1") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + v := fleetView{Complete: true, DeploymentCurrent: true, Load: map[string]int{}, ReplicaManifests: map[string]*release.Manifest{replicaRecordKey(rec): m}, Boxes: []fleetBoxView{{Label: "pi-1", Fresh: true, AtLabelFloor: true, AtReplicaFloor: true, Release: release.StatelessReplicasFloor}, {Label: "pi-2", Fresh: true, AtLabelFloor: true, AtReplicaFloor: true, Release: release.StatelessReplicasFloor}}} |
| + for _, test := range []string{"stale", "draining", "label", "replicas", "capacity"} { |
| + t.Run(test, func(t *testing.T) { |
| + testView := v |
| + testView.Boxes = slices.Clone(v.Boxes) |
| + switch test { |
| + case "stale": |
| + testView.Boxes[1].Fresh = false |
| + case "draining": |
| + testView.Boxes[1].Draining = true |
| + case "label": |
| + testView.Boxes[1].AtLabelFloor = false |
| + case "replicas": |
| + testView.Boxes[1].AtReplicaFloor = false |
| + case "capacity": |
| + testView.Boxes[1].TotalMiB = 128 |
| + } |
| + next, err := fx.srv.replicaNext(rec, testView, 2) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if !slices.Equal(next.Boxes, []string{"pi-1"}) { |
| + t.Fatalf("ineligible box selected: %+v", next) |
| + } |
| + }) |
| + } |
| + root := rec |
| + root.Runtime = provision.RuntimeRootfsV1 |
| + rm := *m |
| + rm.Kind = release.KindRootfs |
| + rv := v |
| + rv.ReplicaManifests = map[string]*release.Manifest{replicaRecordKey(root): &rm} |
| + rv.Boxes = slices.Clone(v.Boxes) |
| + for i := range rv.Boxes { |
| + rv.Boxes[i].AtRootfsFloor = true |
| + rv.Boxes[i].RootfsReady = true |
| + } |
| + rv.Boxes[1].RootfsReady = false |
| + if next, err := fx.srv.replicaNext(root, rv, 2); err != nil || !slices.Equal(next.Boxes, []string{"pi-1"}) { |
| + t.Fatalf("rootfs readiness ignored: %+v %v", next, err) |
| + } |
| + rv.Boxes[1].RootfsReady = true |
| + rv.Boxes[1].AtRootfsFloor = false |
| + if next, err := fx.srv.replicaNext(root, rv, 2); err != nil || !slices.Equal(next.Boxes, []string{"pi-1"}) { |
| + t.Fatalf("rootfs floor ignored: %+v %v", next, err) |
| + } |
| + v.Boxes = v.Boxes[:1] |
| + v.Boxes[0].Release = release.StatelessRuntimeFloor |
| + v.Boxes[0].AtReplicaFloor = false |
| + fx.srv.consoleBuild = release.StatelessRuntimeFloor |
| + next, err := fx.srv.replicaNext(rec, v, 1) |
| + if err != nil || !slices.Equal(next.Boxes, []string{"pi-1"}) { |
| + t.Fatalf("runtime-floor one-copy app stopped: %+v %v", next, err) |
| + } |
| + if _, err := fx.srv.replicaNext(rec, v, 2); err == nil { |
| + t.Fatal("two copies accepted below replica floor") |
| + } |
| + if !movable(rec, m) || movable(rec) || movable(rec, &release.Manifest{Schema: 1, App: rec.App, Version: "v1", Kind: "binary"}) { |
| + t.Fatal("unverified/stateful binary admitted or verified binary refused") |
| + } |
| + for _, mut := range []func(*provision.Record){func(r *provision.Record) { r.HA = true }, func(r *provision.Record) { r.Addr = "127.0.0.1:9000" }, func(r *provision.Record) { r.Unit = "external.service" }} { |
| + r := rec |
| + mut(&r) |
| + if movable(r, m) { |
| + t.Fatal("unmanaged binary admitted") |
| + } |
| + } |
| +} |
| + |
| +func TestReplicaPlacementLegacyReadBudget(t *testing.T) { |
| + for _, single := range []bool{false, true} { |
| + t.Run(map[bool]string{false: "two-box", true: "single-box"}[single], func(t *testing.T) { |
| + boxes := []string{"pi-1", "pi-2"} |
| + if single { |
| + boxes = boxes[:1] |
| + } |
| + fx, _, _ := fleetBoxWorld(t, "replica-inert", boxes...) |
| + putFleetRecord(t, fx, "shop", "a.example.com", func(r *provision.Record) { r.FleetBox = "pi-1" }) |
| + cs := newCountStore(fx.rel) |
| + fx.srv.cfg.Releases = cs |
| + for pass := 0; pass < 2; pass++ { |
| + cs.reset() |
| + relabelPass(t, fx) |
| + wantGets := map[string]int{} |
| + wantLists := map[string]int{} |
| + if !single { |
| + wantLists = map[string]int{"fleets/pi/status/boxes/": 1, "status/boxes/": 1, provision.RecordsPrefix(fx.sqid, "shop"): 1, provision.SidecarsPrefix(fx.sqid, "shop"): 1} |
| + wantGets = map[string]int{"fleets/pi/status/boxes/pi-1.json": 1, "fleets/pi/status/boxes/pi-2.json": 1} |
| + if pass == 0 { |
| + wantGets[provision.RecordKey(fx.sqid, "shop", "a.example.com")] = 1 |
| + } |
| + } |
| + if !reflect.DeepEqual(cs.gets, wantGets) || !reflect.DeepEqual(cs.lists, wantLists) || len(cs.puts) != 0 { |
| + t.Fatalf("pass %d: gets %v lists %v puts %v; expected gets %v lists %v", pass, cs.gets, cs.lists, cs.puts, wantGets, wantLists) |
| + } |
| + } |
| + }) |
| + } |
| +} |
| + |
| +type replicaWriteFailure struct { |
| + *countStore |
| + fail string |
| +} |
| + |
| +func (s *replicaWriteFailure) Put(ctx context.Context, key string, body []byte, etag string) (string, error) { |
| + if key == s.fail { |
| + return "", errors.New("injected write failure") |
| + } |
| + return s.countStore.Put(ctx, key, body, etag) |
| +} |
| + |
| +func TestReplicaPlacementRetriesAndSerializes(t *testing.T) { |
| + fx, _, _ := replicaPlacementWorld(t) |
| + cs := newCountStore(fx.rel) |
| + failed := &replicaWriteFailure{countStore: cs, fail: provision.RecordKey(fx.sqid, "shop", "b.example.com")} |
| + fx.srv.cfg.Releases = failed |
| + relabelPass(t, fx) |
| + wantReplicaBoxes(t, fx, "a.example.com", []string{"pi-1", "pi-2"}, nil) |
| + if shopRec(t, fx, "b.example.com").ReplicaAssignment != nil { |
| + t.Fatal("injected failure did not fail") |
| + } |
| + failed.fail = "" |
| + cs.reset() |
| + relabelPass(t, fx) |
| + wantReplicaBoxes(t, fx, "b.example.com", []string{"pi-1", "pi-2"}, nil) |
| + if cs.recordPuts() != 1 { |
| + t.Fatalf("retry rewrote converged records: %v", cs.puts) |
| + } |
| + unlock := fx.srv.lockApp(fx.sqid, "shop") |
| + done := make(chan error, 1) |
| + go func() { done <- fx.srv.fleetRelabelPass(context.Background(), time.Now()) }() |
| + select { |
| + case err := <-done: |
| + unlock() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + case <-time.After(5 * time.Second): |
| + unlock() |
| + t.Fatal("fleet pass blocked behind app publication") |
| + } |
| +} |
| + |
| +func TestReplicaPlacementReadAccounting(t *testing.T) { |
| + fx, _, _ := replicaPlacementWorld(t) |
| + fx.srv.fleetInventories.Delete("pi") |
| + cs := newCountStore(fx.rel) |
| + fx.srv.cfg.Releases = cs |
| + for pass := 0; pass < 4; pass++ { |
| + if pass == 3 { |
| + if _, err := appconfig.SetCopies(context.Background(), fx.rel, fx.sqid, "shop", 1); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + cs.reset() |
| + relabelPass(t, fx) |
| + wantGets := map[string]int{ |
| + appconfig.Key(fx.sqid, "shop"): 1, |
| + "control/app-policy/" + fx.sqid + "/shop.json": 1, |
| + release.ChannelKey(fx.sqid, "shop", "edge"): 1, |
| + release.ChannelKey(fx.sqid, "shop", "stable"): 1, |
| + release.ManifestKey(fx.sqid, "shop", "v1"): 1, |
| + release.ManifestKey(fx.sqid, "shop", "v2"): 1, |
| + release.PromotionRecordKey(fx.sqid, "shop", "v1"): 1, |
| + release.PromotionRecordKey(fx.sqid, "shop", "v2"): 1, |
| + "fleets/pi/status/boxes/pi-1.json": 1, |
| + "fleets/pi/status/boxes/pi-2.json": 1, |
| + } |
| + wantLists := map[string]int{"status/boxes/": 1, "fleets/pi/status/boxes/": 1, provision.RecordsPrefix(fx.sqid, "shop"): 1, provision.SidecarsPrefix(fx.sqid, "shop"): 1} |
| + wantPuts := map[string]int{} |
| + for _, host := range []string{"a.example.com", "b.example.com"} { |
| + key := provision.RecordKey(fx.sqid, "shop", host) |
| + if pass == 0 { |
| + wantGets[key] = 2 |
| + } else if pass == 1 || pass == 3 { |
| + wantGets[key] = 1 |
| + } |
| + if pass == 0 || pass == 3 { |
| + wantPuts[key] = 1 |
| + } |
| + } |
| + if pass == 0 || pass == 3 { |
| + wantGets["control/serial"] = 1 |
| + wantPuts["control/serial"] = 1 |
| + } |
| + if !reflect.DeepEqual(cs.gets, wantGets) || !reflect.DeepEqual(cs.lists, wantLists) || !reflect.DeepEqual(cs.puts, wantPuts) { |
| + t.Fatalf("pass %d gets=%v lists=%v puts=%v; want gets=%v lists=%v puts=%v", pass, cs.gets, cs.lists, cs.puts, wantGets, wantLists, wantPuts) |
| + } |
| + } |
| +} |
| + |
| +func TestReplicaPlacementDrain(t *testing.T) { |
| + for _, spare := range []bool{false, true} { |
| + t.Run(map[bool]string{false: "shortfall", true: "spare"}[spare], func(t *testing.T) { |
| + fx, _, reg := replicaPlacementWorld(t) |
| + relabelPass(t, fx) |
| + if spare { |
| + registerFleetBox(t, reg, "pi", "pi-3") |
| + copiesBeat(t, fx, "pi-3", release.StatelessReplicasFloor, time.Now()) |
| + } |
| + stuck, err := fx.srv.drainBox(context.Background(), "pi", "pi-2") |
| + if err != nil || len(stuck) != 0 { |
| + t.Fatalf("drain: %v %v", stuck, err) |
| + } |
| + boxes := []string{"pi-1"} |
| + if spare { |
| + boxes = append(boxes, "pi-3") |
| + } |
| + for _, h := range []string{"a.example.com", "b.example.com"} { |
| + wantReplicaBoxes(t, fx, h, boxes, []string{"pi-2"}) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestReplicaPlacementReversedInventory(t *testing.T) { |
| + fx, _, reg := replicaPlacementWorld(t) |
| + registerFleetBox(t, reg, "pi", "pi-3") |
| + copiesBeat(t, fx, "pi-3", release.StatelessReplicasFloor, time.Now()) |
| + v, err := fx.srv.loadFleetView(context.Background(), "pi") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + slices.Reverse(v.Records) |
| + slices.Reverse(v.Boxes) |
| + unlock := fx.srv.lockFleet("pi") |
| + err = fx.srv.reconcileReplicaFleet(context.Background(), "pi", v, time.Now()) |
| + unlock() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + wantReplicaBoxes(t, fx, "a.example.com", []string{"pi-1", "pi-3"}, nil) |
| + wantReplicaBoxes(t, fx, "b.example.com", []string{"pi-1", "pi-2"}, nil) |
| +} |
diff --git a/internal/console/store.go b/internal/console/store.go| index fe48e4d84..2a5f3b07c 100644 |
| --- a/internal/console/store.go |
| +++ b/internal/console/store.go |
| @@ -591,6 +591,7 @@ func (s *Store) migrate() error { |
| // old region (regiondrift.go). Member moves' region write uses the |
| // same column (member-moves design §6.6). |
| `ALTER TABLE apps ADD COLUMN region_set_at INTEGER NOT NULL DEFAULT 0;`, |
| + `ALTER TABLE apps ADD COLUMN copies_configured INTEGER NOT NULL DEFAULT 0;`, |
| // How a session was proved (email sign-in spec §5.4). Every session |
| // that predates the column was made through Keymail, so the default |
| // is the backfill. |
| @@ -770,6 +771,7 @@ func (s *Store) migrateAppsKey() error { |
| region TEXT NOT NULL DEFAULT '', |
| region_source TEXT NOT NULL DEFAULT '', |
| region_set_at INTEGER NOT NULL DEFAULT 0, |
| + copies_configured INTEGER NOT NULL DEFAULT 0, |
| expires_at INTEGER NOT NULL DEFAULT 0, |
| restoring INTEGER NOT NULL DEFAULT 0, |
| purge_after INTEGER NOT NULL DEFAULT 0, |
| @@ -788,8 +790,8 @@ func (s *Store) migrateAppsKey() error { |
| // lifetime is carried across, and minted for a row that has none (the |
| // ALTER above adds it empty); randomblob(8) is 16 hex digits, the |
| // same form insertAppRow mints. |
| - `INSERT INTO apps_new (app, account_id, created_by, created_at, deleted_at, placement, control_plane, build_probe, region, region_source, region_set_at, expires_at, restoring, purge_after, purge_for, lifetime) |
| - SELECT app, account_id, created_by, created_at, deleted_at, placement, control_plane, build_probe, region, region_source, region_set_at, expires_at, restoring, purge_after, purge_for, |
| + `INSERT INTO apps_new (app, account_id, created_by, created_at, deleted_at, placement, control_plane, build_probe, region, region_source, region_set_at, copies_configured, expires_at, restoring, purge_after, purge_for, lifetime) |
| + SELECT app, account_id, created_by, created_at, deleted_at, placement, control_plane, build_probe, region, region_source, region_set_at, copies_configured, expires_at, restoring, purge_after, purge_for, |
| CASE WHEN lifetime = '' THEN lower(hex(randomblob(8))) ELSE lifetime END FROM apps;`, |
| `DROP TABLE apps;`, |
| `ALTER TABLE apps_new RENAME TO apps;`, |