carlos / platform Public

feat: store replica assignments with lifetime CAS

Add deterministic distinct-box placement and strict assignment validation.
Persist assignments and retirement acknowledgements through typed record
writers that fence stale lifetimes and revisions and preserve stop obligations.

Require caller-supplied verified manifest evidence without adding release
reads to legacy writers. Refuse single-label moves until a set converges to
one copy. Cover CAS retries, shape refusals, publication fixtures and both
record censuses.
Co-Authored-By: Codex (gpt-6-astra) <noreply@openai.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev 1fa26887c9ae183f7942fb37d5114c48dcad6177 parent caf48a0
11 files changed, +814 −10
  • internal/console/copiespublication_test.go +4 −4
  • internal/provision/fleetbox.go +3 −0
  • internal/provision/plan9_b8_census_test.go +3 −1
  • internal/provision/provision.go +3 −0
  • internal/provision/replicaassignment.go +168 −0
  • internal/provision/replicaassignment_test.go +387 −0
  • internal/provision/replicacoordinator.go +2 −2
  • internal/provision/stateless_placement_census_test.go +16 −1
  • internal/provision/testdata/plan14-root-reads-stateless-replicas-2.tsv +2 −2
  • internal/replicas/placement.go +145 −0
  • internal/replicas/placement_test.go +81 −0

CI failed — run details

Intent

Human

<task-notification> <task-id>b7axnsbsq</task-id> <tool-use-id>toolu_019wXoWTtFERrm8P7KjaAiRA</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/7c5a7d70-0e28-42b9-896c-5d73b2d2a05d/tasks/b7axnsbsq.output</output-file> <status>completed</status> <summary>Background command "Wait for fix round 2" completed (exit code 0)</summary> </task-notification>

Human

<task-notification> <task-id>a7e084cb04df56e46</task-id> <tool-use-id>toolu_016UQ4Kop9N2UgBnA4nkuSbZ</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/7c5a7d70-0e28-42b9-896c-5d73b2d2a05d/tasks/a7e084cb04df56e46.output</output-file> <status>completed</status> <summary>Agent "Re-review Task 1 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 - **Claim create did two default-config GETs for every legacy app** — ADDRESSED. `apiinstances.go` (about 2409–2437, 2452–2462): without `PrivateStorage`, the first `beginCopiesMutation` hold and memo now stay through `finishClaimCreate`. - The `createUnlock()` and fresh `copiesHeldKey` are now only in the `m.PrivateStorage` branch. `finishCopiesClaimCreate`, with its new memo, hold and re-read, is only reached on the private path. - `TestCopiesClaimCreateReadsDefaultOnce` (`copies_upload_test.go`) asserts exactly one default-config GET for a legacy non-private claim create. It passed when I ran it. - `perfClaimInstanceCreate` (`perfwrites_test.go`) now measures the claim path with a 107-request cap, a median budget, and a one-GET assertion per create. - **`TestCopiesHelpHasOneDefault` could not fail** — ADDRESSED. `apps_copies_test.go:~60` finds the line containing the usage text and requires exactly one `"(default 1)"` and exactly one `"(default"`. The flag's default is 0, so Go adds nothing of its own, and a duplicated default string would now fail the test. - **`copiesShipManifestGate` started the 15 s timeout before the lock** — ADDRESSED. `copiespublication.go` now calls `beginCopiesMutation` on `withWriteMemo(ctx)` and only then creates the timeout from the held context. `TestCopiesShipManifestBudgetStartsAfterLock` holds the lock for 300 ms and checks the deadline is at least `configStoreTimeout` after the release. It passed when I ran it. ### New Breakage in the Fix Diff None found. - **Validation under the same hold:** `copiesCreateCheck` runs under the first hold, before the claim begins. That hold is released only by the deferred `createUnlock` when the handler returns, so it covers `beginClaimCreate` and `finishClaimCreate`. I did not check the copies-edit path myself. I assume it takes `beginCopiesMutation`'s app lock and name lock, which is the only way an edit can't slip in between check and publish. The record body is only ever changed by `buildClaim`, which touches `CreatedAt` and `Acquisition`, not the copies-relevant fields. - **Context carry-over:** `beginClaimCreate` derives its context from `createContext`. The memo and the held key are therefore inherited, and the 202-pending path returns normally, so the defer releases the lock. - **Unlock paths:** - Private path: unlocks early and sets `createUnlock` to nil, so there is no double unlock. `finishCopiesClaimCreate` takes its own hold and defers its unlock. - Non-private path: the deferred `createUnlock` runs on every return. - Ship gate: both refusal branches call `unlock()`, and the `cancel()` after the second refusal only exists once the timeout is created. ### Out-of-Scope Observations - In the ship gate, the SQL incarnation read and `copiesStillApp` inside `beginCopiesMutation` now run outside the 15 s timeout. This matches what you asked for, and the SQL context has its own limits. - The non-private claim path now holds the app lock through `RecordEffects` and `Complete`. This follows P9. Previously the lock was held only up to the start CAS and then re-taken for the finish. ### Verdict **Fix round:** All findings addressed, no new Critical/Important breakage</result> <usage><subagent_tokens>51986</subagent_tokens><tool_uses>6</tool_uses><duration_ms>78689</duration_ms></usage> </task-notification>

Human

<task-notification> <task-id>a5398278b47a819fb</task-id> <tool-use-id>toolu_014QDySck8Dmw1TkZA4wie1z</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/7c5a7d70-0e28-42b9-896c-5d73b2d2a05d/tasks/a5398278b47a819fb.output</output-file> <status>completed</status> <summary>Agent "Census review Task 1 (#280)" 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>| unit | class | verdict | reason (file:line) | |---|---|---|---| | `.` (root package) | envelope | APPROVE | The only new root-binary code is the CLI. `setCopies` sends an authenticated PUT to the console and checks the echoed count (apimode.go:5702, apps_copies.go:18). The `--copies` flag wiring is in apps_swap.go:167 and :223. Root opens, runs, queries and follows nothing new. | | `internal/appconfig` | envelope | APPROVE | `Manifest.Copies` is additive and omitempty (appconfig.go:28). Nothing in root scope acts on it beyond `CopiesOf` and `SetCopies`: host config sync ignores it, and every consumer is in `internal/console`. `SetSwapPolicy` gains only an optional check that runs on the already-read bundle before the unchanged CAS (swap.go:87). No check is weakened. | | `internal/provision` | envelope | APPROVE | `Record.ReplicaAssignment` is a new field (provision.go:43) that only the console reads (appcopies.go:142). `replicaFieldsFixed` now refuses any record write that changes it, with no exemption for any field (replicacoordinator.go:65, applied in `WriteRecord` at record_sequence.go:143). That is stricter for box agents, not looser. The lifetime index snapshot deep-copies the slices (lifetimeindex.go:137). No new root read. | | `internal/release` | envelope | APPROVE | `ShipSpooled` and `claimRawShipSpooled` take optional `ManifestGate`s that run after the artifact upload and before `putImmutableManifest`. The manifest bytes are marshalled before the gate (rootfs_ship.go:419-430). The only gate, in the console (copiespublication.go:310), does not change `m`. Callers without a gate keep the old path, and every validation is unchanged. | | `internal/replicas` | envelope | APPROVE | This package only adds data types (`Assignment`, `Expect`, assignment.go:4-17). There is no I/O, path or exec. | | `internal/appconfig/copies.go` `SetCopies` (new) | nonrecord, `sel:Put` | APPROVE | It is locked: `WithAppMutation` (copies.go:24). It validates account, app and n≥1 before building the key, and the key is always the default bundle `Key(acct, app)`. It is CAS'd: `getForWriteAt` returns the etag (copies.go:32), and `Put(..., etag)` is replace-only, or create-only when the bundle is absent (copies.go:46). It decodes the whole struct and rewrites it, so it keeps every field this binary knows, including `OwnerScope` through `manifestSchema`. It refuses a newer schema. An unchanged value writes nothing. | | `internal/appconfig/swap.go` `claimRawSetSwapPolicy` (re-digest) | nonrecord, `sel:Put` | APPROVE | The only change is the variadic check loop, run before the unchanged CAS write (swap.go:87). Its only caller holds the app lock through `beginCopiesMutation` (copiespublication.go:239-244). | | `internal/console/hostsused.go` `Server.createSidecarMarked` (re-digest) | record-writer | APPROVE | It still holds the app lock and adds the name lock. It refuses at copies&gt;1 before the hostname mark and the typed `CreateSidecarRecord` (hostsused.go:603-614). | | `internal/console/hostsused.go` `Server.createRecordMarked` (re-digest) | record-writer | APPROVE | It takes the app lock, then the hostname lock, then the name lock. `copiesCreateCheck` runs before any mark (hostsused.go:565-566). The only field it sets is `Hibernate=false` when copies&gt;1 (copiespublication.go:228-229). `CreateRecord` stays create-only (hostsused.go:591), and the returned record is the one persisted. | | `internal/console/lifetimes_create.go` `Server.createRecordWithLifetimeLocked` (re-digest) | key-site | APPROVE | The same name lock and admission run before any allocation (lifetimes_create.go:64-65). The existing lifetime, maintenance and CAS checks are untouched. No assignment is written here. | | `internal/console/channelmove.go` `Server.handleAPIInstanceChannel` (re-digest) | record-writer | APPROVE | `withRecordLock` is replaced by `beginCopiesMutation`, which takes the same `lockApp(acct.Sqid, app)` and is now held before `readRecord` (channelmove.go:126). It ends in an unchanged etag `UpdateRecord` (channelmove.go:189). `WriteRecord` keeps `ReplicaAssignment` fixed. | | `internal/console/channelmove.go` `Server.executePendingRouteChannel` (re-digest) | record-writer | APPROVE | The same lock is taken before the read of `acct.Sqid`/`app`/`p.Host` (channelmove.go:219-228). The proposal etag check stays, and the write is the etag `UpdateRecord` (channelmove.go:240). | | `internal/console/updatescore.go` `Server.applyUpdates` (re-digest) | record-writer | APPROVE | The app lock moves from around the write to the whole function (updatescore.go:97). It takes the same `lockApp` key, and none of its callees take it again. The write is still the etag `UpdateRecord` (updatescore.go:193). | | `internal/console/updatescore.go` `Server.requestInstall` (re-digest) | record-writer | APPROVE | The lock now spans the whole CAS retry loop (updatescore.go:216), and the read and write sit inside it. The monotonic-ID etag `UpdateRecord` is unchanged (updatescore.go:241). | | `internal/console/authcli.go` `Server.registerCLIRoutes` (re-digest) | key-site | APPROVE | It adds only `PUT .../copies` with the zero `svcrole.Set{}`, so the route is person-only and no app credential can call it (authcli.go:1022). | **Census: APPROVED at caf48a07** - **Seal:** the card's seal is `df8bf8056d80b9d78edc957fe7f2adbc75885e15f581e58167768346c4e05771` → `df8bf8056d80b9d78edc957fe7f2adbc75885e15f581e58167768346c4e05771`. It doesn't move, as expected for a card that only re-pins envelopes (0 body, 0 sites, 5 envelopes). At the tip, `make census-card` printed "Nothing to approve: the census is clean" with the same seal. - **Tests run at the tip:** in `internal/provision`, `TestPlan9B8RecordWriteCensus`, `TestPlan14RootReadCensus`, `TestReplicaAssignment*` and `TestCensusScopeIsTheRootBinary` pass. The `internal/appconfig` tests matching `Copies` and `SwapPolicy` pass too. The worktree is unchanged. - **Not blocking, one cross-version point:** `copies` goes into schema 1 without a schema bump. An older carlos that rewrites the default `config.json` in bucket mode would silently drop the field. That turns an explicit count back into "not explicit", which ends the console's copies checks for that app. Only an operator holding bucket write credentials can do that, not a tenant, app or box agent, so it raises no root-read concern. The author may still want to note it. - **Not blocking, a hazard for future gate authors:** `ManifestGate` gets `&amp;m` after `raw` has been marshalled (rootfs_ship.go:419-430). A future gate that changed `m` would no longer match the bytes that get written. Today's only gate doesn't change it. The verdicts still need recording on #280 with the tip `caf48a07`. I haven't done that, because this review was read-only. Files: `/home/paulca/amadan.net/carlos/platform/.claude/worktrees/stateless-replicas-2/docs/superpowers/notes/census-proposal-stateless-replicas-2.md`, `/home/paulca/amadan.net/carlos/platform/.claude/worktrees/stateless-replicas-2/internal/provision/stateless_placement_census_test.go`, `/home/paulca/amadan.net/carlos/platform/.claude/worktrees/stateless-replicas-2/internal/provision/testdata/plan14-root-reads-stateless-replicas-2.tsv`</result> <usage><subagent_tokens>87576</subagent_tokens><tool_uses>22</tool_uses><duration_ms>234768</duration_ms></usage> </task-notification>

Human

<task-notification> <task-id>b8bebxr3z</task-id> <tool-use-id>toolu_01C9Bz5RkVm9yuxPvqAtue3r</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/7c5a7d70-0e28-42b9-896c-5d73b2d2a05d/tasks/b8bebxr3z.output</output-file> <status>completed</status> <summary>Background command "Wait for Task 2a" completed (exit code 0)</summary> </task-notification>

Human

<task-notification> <task-id>b03bw7wki</task-id> <tool-use-id>toolu_018LQpBD6hSzyiT1rCHGi3ub</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/7c5a7d70-0e28-42b9-896c-5d73b2d2a05d/tasks/b03bw7wki.output</output-file> <status>completed</status> <summary>Background command "Wait for CI verdict on 61581b9f" completed (exit code 0)</summary> </task-notification>

Attributed to this commit: 9.53 g CO₂e (1,120,809 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/copiespublication_test.go b/internal/console/copiespublication_test.go
index 309ae1723..6639a73b9 100644
--- a/internal/console/copiespublication_test.go
+++ b/internal/console/copiespublication_test.go
@@ -97,10 +97,10 @@ func TestCopiesStoredAssignmentAndDecrease(t *testing.T) {
retired bool
refuse bool
}{
- {"two boxes", &replicas.Assignment{Boxes: []string{"pi-1", "pi-2"}}, false, true},
- {"retiring", &replicas.Assignment{Boxes: []string{"pi-1"}, Retiring: []string{"pi-2"}}, false, true},
- {"retired record", &replicas.Assignment{Boxes: []string{"pi-1"}, Retiring: []string{"pi-2"}}, true, true},
- {"one box", &replicas.Assignment{Boxes: []string{"pi-1"}}, false, false},
+ {"two boxes", &replicas.Assignment{Revision: 1, Desired: 2, Boxes: []string{"pi-1", "pi-2"}}, false, true},
+ {"retiring", &replicas.Assignment{Revision: 1, Desired: 1, Boxes: []string{"pi-1"}, Retiring: []string{"pi-2"}}, false, true},
+ {"retired record", &replicas.Assignment{Revision: 1, Desired: 1, Boxes: []string{"pi-1"}, Retiring: []string{"pi-2"}}, true, true},
+ {"one box", &replicas.Assignment{Revision: 1, Desired: 1, Boxes: []string{"pi-1"}}, false, false},
{"none", nil, false, false},
} {
t.Run(tc.name, func(t *testing.T) {
diff --git a/internal/provision/fleetbox.go b/internal/provision/fleetbox.go
index b7a0aaae3..dbd9f6744 100644
--- a/internal/provision/fleetbox.go
+++ b/internal/provision/fleetbox.go
@@ -58,6 +58,9 @@ func SetRecordFleetBox(ctx context.Context, s release.Store, acct, app, host str
// doors, which also refuse rootfs records (rootfsRefusalCallers),
// and a relabel inside a fleet moves rootfs records by design.
if rec.FleetBox != label {
+ if err := replicaAssignmentMoveRefusal(rec); err != nil {
+ return err
+ }
if b := rec.Seed.MoveBlock(); b != "" {
return fmt.Errorf("%w: %w", ErrFleetBoxImportInFlight, &SeedMoveError{Block: b})
}
diff --git a/internal/provision/plan9_b8_census_test.go b/internal/provision/plan9_b8_census_test.go
index 2d8c610d3..0cf14f57a 100644
--- a/internal/provision/plan9_b8_census_test.go
+++ b/internal/provision/plan9_b8_census_test.go
@@ -53,7 +53,7 @@ var censusMethods = map[string]bool{
// typed-record-writer touchpoint. Keep these names aligned with the APIs above.
var (
censusKeySuffixes = []string{"recordkey", "recordsprefix", "sidecarsprefix", "sidecarkey", "sidecarmanifestkey", "writerecord", "sequencedrecord"}
- censusKeyExact = map[string]bool{"createrecord": true, "updaterecord": true, "setrecordregion": true, "setrecordmove": true, "setrecordrun": true, "setrecordinteractive": true, "setrecordseed": true, "setrecordfleetbox": true, "setrecordcoordinator": true, "setrecordreplicarelease": true, "setrecordassetgen": true, "mintrecordassetgen": true, "createsidecarrecord": true, "claimrawupdaterecord": true}
+ censusKeyExact = map[string]bool{"createrecord": true, "updaterecord": true, "setrecordregion": true, "setrecordmove": true, "setrecordrun": true, "setrecordinteractive": true, "setrecordseed": true, "setrecordfleetbox": true, "setrecordcoordinator": true, "setrecordreplicarelease": true, "setrecordreplicaassignment": true, "recordreplicaretired": true, "setrecordassetgen": true, "mintrecordassetgen": true, "createsidecarrecord": true, "claimrawupdaterecord": true}
censusLitWords = []string{"instances", "sidecars"}
)
@@ -422,6 +422,8 @@ func Reviewed(ctx context.Context, s Store, k string) error {
{"box callsite", base + "\nfunc Box(ctx context.Context, s Store, k string, b []byte) { provision.WriteRecord(ctx, s, k, nil, b, \"\") }\n", "unlisted site x.go:Box [key:WriteRecord]"},
{"typed writer callsite", base + "\nfunc Typed(ctx context.Context, s Store) { provision.SetRecordMove(ctx, s, \"a\", \"b\", \"c\", nil) }\n", "unlisted site x.go:Typed [key:SetRecordMove]"},
{"fleet box writer callsite", base + "\nfunc Boxed(ctx context.Context, s Store) { provision.SetRecordFleetBox(ctx, s, \"a\", \"b\", \"c\", provision.FleetBoxExpect{}, \"pi-1\", time.Time{}) }\n", "unlisted site x.go:Boxed [key:SetRecordFleetBox]"},
+ {"assignment writer callsite", base + "\nfunc Assigned() { provision.SetRecordReplicaAssignment() }\n", "unlisted site x.go:Assigned [key:SetRecordReplicaAssignment]"},
+ {"retirement writer callsite", base + "\nfunc Retired() { provision.RecordReplicaRetired() }\n", "unlisted site x.go:Retired [key:RecordReplicaRetired]"},
{"record path literal", base + "\nfunc Lit(h string) string { return \"apps/a/b/instances/\" + h + \".json\" }\n", "unlisted site x.go:Lit [lit:instances]"},
{"sidecar path literal", base + "\nconst sidecarDir = \"sidecars\"\n", "unlisted site x.go:const sidecarDir [lit:sidecars]"},
{"reflective name", base + "\nfunc Reflect(v any) { _ = reflect.ValueOf(v).MethodByName(\"Put\") }\n", "unlisted site x.go:Reflect [str:Put]"},
diff --git a/internal/provision/provision.go b/internal/provision/provision.go
index cef756d05..71c11bb79 100644
--- a/internal/provision/provision.go
+++ b/internal/provision/provision.go
@@ -1044,6 +1044,9 @@ func CreateRecord(ctx context.Context, s release.Store, rec Record) error {
func SetRecordRegion(ctx context.Context, s release.Store, acct, app, host, region string) error {
_, err := updateRecord(ctx, s, acct, app, host, func(rec *Record) error {
if rec.Region != region {
+ if err := replicaAssignmentMoveRefusal(rec); err != nil {
+ return err
+ }
if err := seedMoveRefusal(rec); err != nil {
return err
}
diff --git a/internal/provision/replicaassignment.go b/internal/provision/replicaassignment.go
new file mode 100644
index 000000000..3a23029a6
--- /dev/null
+++ b/internal/provision/replicaassignment.go
@@ -0,0 +1,168 @@
+package provision
+
+import (
+ "context"
+ "math"
+ "slices"
+
+ "github.com/carlosframework/platform/internal/registry"
+ "github.com/carlosframework/platform/internal/release"
+ "github.com/carlosframework/platform/internal/replicas"
+)
+
+type replicaAssignmentManifestKey struct{}
+type replicaAssignmentManifest struct {
+ id replicas.Identity
+ channel, pin, runtime string
+}
+
+// WithReplicaAssignmentManifest carries the caller's already-authorized,
+// selected canonical manifest. The caller holds publication exclusion while
+// using this context; channel selection and fleet ownership are its checks.
+// It is bound to the observed lifetime and selector, not a reusable mode flag.
+// This helper reads no store and never verifies an untrusted manifest itself.
+func WithReplicaAssignmentManifest(ctx context.Context, rec Record, m *release.Manifest) (context.Context, error) {
+ if err := replicaAssignmentShape(&rec); err != nil {
+ return ctx, err
+ }
+ if m == nil || m.Schema != 1 || m.App != rec.App || m.Version == "" || !m.Stateless || m.Hibernate || (rec.Pin != "" && rec.Pin != m.Version) {
+ return ctx, replicas.ErrInvalid
+ }
+ if (rec.Runtime == "" && m.Kind != "binary") || (rec.Runtime == RuntimeRootfsV1 && m.Kind != release.KindRootfs) {
+ return ctx, replicas.ErrInvalid
+ }
+ inc, err := Incarnation(rec.Account, rec.App, rec.Host, rec.CreatedAt)
+ if err != nil {
+ return ctx, err
+ }
+ evidence := replicaAssignmentManifest{replicas.Identity{Account: rec.Account, App: rec.App, Host: rec.Host, Incarnation: inc}, rec.Channel, rec.Pin, rec.Runtime}
+ return context.WithValue(ctx, replicaAssignmentManifestKey{}, evidence), nil
+}
+
+func replicaAssignmentShape(rec *Record) error {
+ if _, ok := registry.FleetPlacement(rec.Region); !ok {
+ return replicas.ErrInvalid
+ }
+ if rec.Schema != 1 || rec.Retired || !rec.DerivesPaths() || rec.Pool != "" || rec.HA || rec.Role != "" || len(rec.Replicas) != 0 || rec.Unit != "" || rec.Move != nil || rec.Seed != nil || rec.HibernateOrDefault() || (rec.Runtime != "" && rec.Runtime != RuntimeRootfsV1) {
+ return replicas.ErrInvalid
+ }
+ return ValidateShape(*rec)
+}
+
+func replicaAssignmentEligible(ctx context.Context, rec *Record, id replicas.Identity) error {
+ if err := replicaIdentity(rec, id); err != nil {
+ return err
+ }
+ if err := replicaAssignmentShape(rec); err != nil {
+ return err
+ }
+ evidence, ok := ctx.Value(replicaAssignmentManifestKey{}).(replicaAssignmentManifest)
+ if !ok || evidence.id != id || evidence.channel != rec.Channel || evidence.pin != rec.Pin || evidence.runtime != rec.Runtime {
+ return replicas.ErrFenced
+ }
+ if rec.ReplicaAssignment != nil {
+ return replicas.ValidateAssignment(*rec.ReplicaAssignment)
+ }
+ return nil
+}
+
+func SetRecordReplicaAssignment(ctx context.Context, s release.Store, id replicas.Identity, want replicas.Expect, next replicas.Assignment) (*Record, error) {
+ next.Boxes, next.Retiring = slices.Clone(next.Boxes), slices.Clone(next.Retiring)
+ if err := replicas.ValidateAssignment(next); err != nil {
+ return nil, err
+ }
+ var result *Record
+ err := release.WithAppMutation(ctx, s, id.Account, id.App, "provision.SetRecordReplicaAssignment", func(ctx context.Context) error {
+ ctx = context.WithValue(WithRecordSequence(ctx), replicaWriteKey{}, "replica_assignment")
+ var err error
+ result, err = updateRecord(ctx, s, id.Account, id.App, id.Host, func(rec *Record) error {
+ if err := replicaAssignmentEligible(ctx, rec, id); err != nil {
+ return err
+ }
+ old := rec.ReplicaAssignment
+ revision := uint64(0)
+ if old != nil {
+ revision = old.Revision
+ }
+ if want.Incarnation != id.Incarnation || want.Region != rec.Region || want.RecordSeq != rec.RecordSeq || want.Revision != revision {
+ return replicas.ErrFenced
+ }
+ if next.Revision != revision {
+ return replicas.ErrFenced
+ }
+ if old != nil && old.Desired == next.Desired && slices.Equal(old.Boxes, next.Boxes) && slices.Equal(old.Retiring, next.Retiring) {
+ return errRecordUnchanged
+ }
+ if revision == math.MaxUint64 {
+ return replicas.ErrFenced
+ }
+ if old != nil {
+ for _, box := range old.Boxes {
+ if !next.Contains(box) && !slices.Contains(next.Retiring, box) {
+ return replicas.ErrInvalid
+ }
+ }
+ for _, box := range old.Retiring {
+ if !slices.Contains(next.Retiring, box) {
+ return replicas.ErrInvalid
+ }
+ }
+ } else if rec.FleetBox != "" && !next.Contains(rec.FleetBox) && !slices.Contains(next.Retiring, rec.FleetBox) {
+ return replicas.ErrInvalid
+ }
+ // Do not change next: a store conflict retries with the original request.
+ assigned := next
+ assigned.Revision = revision + 1
+ rec.ReplicaAssignment = &assigned
+ return nil
+ })
+ return err
+ })
+ return result, err
+}
+
+// RecordReplicaRetired persists an authenticated root termination ACK. The
+// caller verifies the proof for this lifetime, revision and box before entry;
+// a down/lost report is never a caller of this primitive.
+func RecordReplicaRetired(ctx context.Context, s release.Store, id replicas.Identity, revision uint64, box string) (*Record, error) {
+ var result *Record
+ err := release.WithAppMutation(ctx, s, id.Account, id.App, "provision.RecordReplicaRetired", func(ctx context.Context) error {
+ ctx = context.WithValue(WithRecordSequence(ctx), replicaWriteKey{}, "replica_assignment")
+ var err error
+ result, err = updateRecord(ctx, s, id.Account, id.App, id.Host, func(rec *Record) error {
+ if err := replicaAssignmentEligible(ctx, rec, id); err != nil {
+ return err
+ }
+ old := rec.ReplicaAssignment
+ if old == nil || old.Revision != revision {
+ return replicas.ErrFenced
+ }
+ i := slices.Index(old.Retiring, box)
+ if i < 0 {
+ return errRecordUnchanged
+ }
+ if revision == math.MaxUint64 {
+ return replicas.ErrFenced
+ }
+ next := *old
+ next.Retiring = slices.Delete(slices.Clone(old.Retiring), i, i+1)
+ next.Revision++
+ rec.ReplicaAssignment = &next
+ return nil
+ })
+ return err
+ })
+ return result, err
+}
+
+func replicaAssignmentMoveRefusal(rec *Record) error {
+ if a := rec.ReplicaAssignment; a != nil {
+ if err := replicas.ValidateAssignment(*a); err != nil {
+ return err
+ }
+ if a.Desired > 1 || len(a.Boxes) > 1 || len(a.Retiring) != 0 {
+ return replicas.ErrFenced
+ }
+ }
+ return nil
+}
diff --git a/internal/provision/replicaassignment_test.go b/internal/provision/replicaassignment_test.go
index d9d376600..dbdad3cde 100644
--- a/internal/provision/replicaassignment_test.go
+++ b/internal/provision/replicaassignment_test.go
@@ -1,8 +1,10 @@
package provision
import (
+ "bytes"
"context"
"encoding/json"
+ "fmt"
"reflect"
"testing"
"time"
@@ -46,3 +48,388 @@ func TestReplicaAssignmentOrdinaryWritersPreserve(t *testing.T) {
t.Fatalf("assignment lost: %+v %v", got, err)
}
}
+
+func assignmentFixture(t *testing.T) (context.Context, release.Store, Record, replicas.Identity, replicas.Expect) {
+ t.Helper()
+ s := release.NewDirStore(t.TempDir())
+ rec := Record{Schema: 1, Account: "bab", App: "shop", Host: "shop.example.com", Slug: "shop", Channel: "edge", Region: "fleet/pi", Hibernate: new(bool), CreatedAt: time.Date(2026, 11, 1, 0, 0, 0, 0, time.UTC)}
+ ctx := WithRecordSequence(context.Background())
+ if err := CreateRecord(ctx, s, rec); err != nil {
+ t.Fatal(err)
+ }
+ r, err := GetRecord(ctx, s, rec.Account, rec.App, rec.Host)
+ if err != nil {
+ t.Fatal(err)
+ }
+ rec = *r
+ inc, err := Incarnation(rec.Account, rec.App, rec.Host, rec.CreatedAt)
+ if err != nil {
+ t.Fatal(err)
+ }
+ id := replicas.Identity{Account: rec.Account, App: rec.App, Host: rec.Host, Incarnation: inc}
+ ctx, err = WithReplicaAssignmentManifest(ctx, rec, &release.Manifest{Schema: 1, App: rec.App, Version: "v1", Kind: "binary", Stateless: true})
+ if err != nil {
+ t.Fatal(err)
+ }
+ return ctx, s, rec, id, replicas.Expect{Incarnation: inc, Region: rec.Region, RecordSeq: rec.RecordSeq}
+}
+
+func assignmentBytes(t *testing.T, s release.Store, id replicas.Identity) []byte {
+ t.Helper()
+ b, _, err := s.Get(context.Background(), RecordKey(id.Account, id.App, id.Host))
+ if err != nil {
+ t.Fatal(err)
+ }
+ return b
+}
+
+func assignmentReplace(t *testing.T, s release.Store, id replicas.Identity, f func(*Record)) []byte {
+ t.Helper()
+ key := RecordKey(id.Account, id.App, id.Host)
+ b, tag, err := s.Get(context.Background(), key)
+ if err != nil {
+ t.Fatal(err)
+ }
+ rec, err := DecodeRecord(b)
+ if err != nil {
+ t.Fatal(err)
+ }
+ f(&rec)
+ b, err = json.Marshal(rec)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err = s.Put(context.Background(), key, b, tag); err != nil {
+ t.Fatal(err)
+ }
+ return b
+}
+
+func TestReplicaAssignmentCASAndShape(t *testing.T) {
+ ctx, s, _, id, want := assignmentFixture(t)
+ next := replicas.Assignment{Desired: 2, Boxes: []string{"a", "b"}}
+ got, err := SetRecordReplicaAssignment(ctx, s, id, want, next)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if got.ReplicaAssignment.Revision != 1 || got.RecordSeq != want.RecordSeq+1 {
+ t.Fatalf("counters not advanced: %+v", got)
+ }
+ want.Revision, want.RecordSeq = got.ReplicaAssignment.Revision, got.RecordSeq
+ next = *got.ReplicaAssignment
+ before := assignmentBytes(t, s, id)
+ if _, err := SetRecordReplicaAssignment(ctx, s, id, want, next); err != nil || !bytes.Equal(before, assignmentBytes(t, s, id)) {
+ t.Fatalf("no-op wrote: %v", err)
+ }
+ for name, bad := range map[string]replicas.Assignment{
+ "duplicates": {Revision: 1, Desired: 3, Boxes: []string{"a", "a"}},
+ "unsorted": {Revision: 1, Desired: 2, Boxes: []string{"b", "a"}},
+ "too-many": {Revision: 1, Desired: 1, Boxes: []string{"a", "b"}},
+ "bad-name": {Revision: 1, Desired: 2, Boxes: []string{"../a"}},
+ "zero": {Revision: 1}, "negative": {Revision: 1, Desired: -1},
+ "rollback": {Desired: 2, Boxes: []string{"a", "b"}},
+ "future": {Revision: 8, Desired: 2, Boxes: []string{"a", "b"}},
+ "lost-proof": {Revision: 1, Desired: 1, Boxes: []string{"a"}},
+ } {
+ t.Run(name, func(t *testing.T) {
+ if _, err := SetRecordReplicaAssignment(ctx, s, id, want, bad); err == nil || !bytes.Equal(before, assignmentBytes(t, s, id)) {
+ t.Fatal("invalid assignment wrote")
+ }
+ })
+ }
+ next = replicas.Assignment{Revision: 1, Desired: 1, Boxes: []string{"a"}, Retiring: []string{"b"}}
+ got, err = SetRecordReplicaAssignment(ctx, s, id, want, next)
+ if err != nil || got.ReplicaAssignment.Revision != 2 {
+ t.Fatalf("scale down: %+v %v", got, err)
+ }
+ before = assignmentBytes(t, s, id)
+ if _, err := RecordReplicaRetired(ctx, s, id, 1, "b"); err == nil || !bytes.Equal(before, assignmentBytes(t, s, id)) {
+ t.Fatal("stale proof wrote")
+ }
+ want.Revision, want.RecordSeq = 2, got.RecordSeq
+ if _, err := SetRecordReplicaAssignment(ctx, s, id, want, replicas.Assignment{Revision: 2, Desired: 1, Boxes: []string{"a"}}); err == nil {
+ t.Fatal("assignment erased stop obligation")
+ }
+ got, err = RecordReplicaRetired(ctx, s, id, 2, "b")
+ if err != nil || len(got.ReplicaAssignment.Retiring) != 0 || got.ReplicaAssignment.Revision != 3 {
+ t.Fatalf("retirement: %+v %v", got, err)
+ }
+ before = assignmentBytes(t, s, id)
+ if _, err := RecordReplicaRetired(ctx, s, id, 3, "b"); err != nil || !bytes.Equal(before, assignmentBytes(t, s, id)) {
+ t.Fatal("repeated retirement wrote")
+ }
+}
+
+func TestReplicaAssignmentRejectsOldLifetime(t *testing.T) {
+ for _, raced := range []bool{false, true} {
+ for _, change := range []string{"region", "record-seq", "channel", "recreate", "revision", "retired"} {
+ t.Run(fmt.Sprintf("%s/retry=%v", change, raced), func(t *testing.T) {
+ ctx, base, _, id, want := assignmentFixture(t)
+ var beforeRecord []byte
+ mutate := func() {
+ if change == "recreate" {
+ key := RecordKey(id.Account, id.App, id.Host)
+ r, err := GetRecord(ctx, base, id.Account, id.App, id.Host)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := base.Delete(ctx, key); err != nil {
+ t.Fatal(err)
+ }
+ r.CreatedAt = r.CreatedAt.Add(time.Second)
+ r.RecordSeq = 0
+ if err := CreateRecord(ctx, base, *r); err != nil {
+ t.Fatal(err)
+ }
+ beforeRecord = assignmentBytes(t, base, id)
+ return
+ }
+ beforeRecord = assignmentReplace(t, base, id, func(r *Record) {
+ switch change {
+ case "region":
+ r.Region = "fleet/other"
+ case "record-seq":
+ r.RecordSeq++
+ case "channel":
+ r.Channel = "stable"
+ r.RecordSeq++
+ case "revision":
+ r.ReplicaAssignment = &replicas.Assignment{Revision: 5, Desired: 1}
+ case "retired":
+ r.Retired = true
+ }
+ })
+ }
+ var s release.Store = base
+ if raced {
+ s = &replicaConflictStore{Store: base, hook: func(context.Context, string, []byte, string) { mutate() }}
+ } else {
+ mutate()
+ }
+ _, err := SetRecordReplicaAssignment(ctx, s, id, want, replicas.Assignment{Desired: 2, Boxes: []string{"a", "b"}})
+ afterRecord := assignmentBytes(t, base, id)
+ if err == nil || !bytes.Equal(beforeRecord, afterRecord) {
+ t.Fatal("stale assignment changed the recreated host")
+ }
+ })
+ }
+ }
+}
+
+func TestReplicaAssignmentEligibilityAndLegacyGuards(t *testing.T) {
+ for _, name := range []string{"unverified", "schema", "kind", "region", "pool", "ha", "role", "upstream", "unit", "hibernate", "move", "retired"} {
+ t.Run(name, func(t *testing.T) {
+ ctx, s, _, id, want := assignmentFixture(t)
+ before := assignmentReplace(t, s, id, func(r *Record) {
+ switch name {
+ case "schema":
+ r.Schema = 2
+ case "kind":
+ r.Kind = "sidecar"
+ case "region":
+ r.Region = "eu-west-1"
+ want.Region = r.Region
+ case "pool":
+ r.Pool = "pool"
+ case "ha":
+ r.HA = true
+ case "role":
+ r.Role = "primary"
+ case "upstream":
+ r.Addr = "127.0.0.1:1234"
+ case "unit":
+ r.Unit = "console.service"
+ case "hibernate":
+ *r.Hibernate = true
+ case "move":
+ r.Move = &MoveState{State: "unknown"}
+ case "retired":
+ r.Retired = true
+ }
+ })
+ if name == "unverified" {
+ ctx = context.Background()
+ }
+ if _, err := SetRecordReplicaAssignment(ctx, s, id, want, replicas.Assignment{Desired: 2, Boxes: []string{"a", "b"}}); err == nil || !bytes.Equal(before, assignmentBytes(t, s, id)) {
+ t.Fatal("ineligible record wrote")
+ }
+ })
+ }
+ for _, a := range []*replicas.Assignment{nil, {Revision: 1, Desired: 1, Boxes: []string{"a"}}, {Revision: 1, Desired: 2, Boxes: []string{"a", "b"}}, {Revision: 1, Desired: 1, Boxes: []string{"a"}, Retiring: []string{"b"}}} {
+ for _, region := range []bool{false, true} {
+ ctx, s, rec, id, _ := assignmentFixture(t)
+ before := assignmentReplace(t, s, id, func(r *Record) { r.ReplicaAssignment = a; r.FleetBox = "a" })
+ var err error
+ if region {
+ err = SetRecordRegion(ctx, s, id.Account, id.App, id.Host, "fleet/other")
+ } else {
+ err = SetRecordFleetBox(ctx, s, id.Account, id.App, id.Host, FleetBoxExpect{Region: rec.Region, Label: "a", CreatedAt: rec.CreatedAt}, "c", time.Now())
+ }
+ active := a != nil && (len(a.Boxes) > 1 || len(a.Retiring) > 0)
+ if active && (err == nil || !bytes.Equal(before, assignmentBytes(t, s, id))) {
+ t.Fatal("single-label writer changed active set")
+ }
+ if !active && err != nil {
+ t.Fatal(err)
+ }
+ }
+ }
+}
+
+func TestReplicaAssignmentRetryAndPreservation(t *testing.T) {
+ ctx, base, _, id, want := assignmentFixture(t)
+ assignmentReplace(t, base, id, func(r *Record) {
+ r.Coordinator = &replicas.Coordinator{Term: "term", Box: "a", BootID: "boot"}
+ r.ReplicaDeploy = &replicas.Deploy{ID: "deploy", Phase: "released", Revision: 4}
+ })
+ s := &replicaConflictStore{Store: base, hook: func(context.Context, string, []byte, string) {}}
+ got, err := SetRecordReplicaAssignment(ctx, s, id, want, replicas.Assignment{Desired: 2, Boxes: []string{"a", "b"}})
+ if err != nil || got.ReplicaAssignment.Revision != 1 || got.Coordinator.Term != "term" || got.ReplicaDeploy.ID != "deploy" {
+ t.Fatalf("retry/preservation: %+v %v", got, err)
+ }
+ for _, change := range []string{"lifetime", "revision"} {
+ t.Run(change, func(t *testing.T) {
+ ctx, base, _, id, _ := assignmentFixture(t)
+ assignmentReplace(t, base, id, func(r *Record) {
+ r.ReplicaAssignment = &replicas.Assignment{Revision: 4, Desired: 1, Boxes: []string{"a"}, Retiring: []string{"b", "c"}}
+ })
+ var before []byte
+ s := &replicaConflictStore{Store: base, hook: func(context.Context, string, []byte, string) {
+ before = assignmentReplace(t, base, id, func(r *Record) {
+ if change == "lifetime" {
+ r.CreatedAt = r.CreatedAt.Add(time.Second)
+ } else {
+ r.ReplicaAssignment.Revision++
+ }
+ })
+ }}
+ if _, err := RecordReplicaRetired(ctx, s, id, 4, "b"); err == nil || !bytes.Equal(before, assignmentBytes(t, base, id)) {
+ t.Fatal("stale retirement wrote on retry")
+ }
+ })
+ }
+}
+
+func TestReplicaAssignmentManifestEvidence(t *testing.T) {
+ ctx, s, rec, id, want := assignmentFixture(t)
+ for _, name := range []string{"nil", "stateful", "hibernate", "schema", "kind", "app", "version", "pin"} {
+ t.Run(name, func(t *testing.T) {
+ r := rec
+ m := &release.Manifest{Schema: 1, App: rec.App, Version: "v1", Kind: "binary", Stateless: true}
+ switch name {
+ case "nil":
+ m = nil
+ case "stateful":
+ m.Stateless = false
+ case "hibernate":
+ m.Hibernate = true
+ case "schema":
+ m.Schema = 2
+ case "kind":
+ m.Kind = "static"
+ case "app":
+ m.App = "other"
+ case "version":
+ m.Version = ""
+ case "pin":
+ r.Pin = "v2"
+ }
+ if _, err := WithReplicaAssignmentManifest(context.Background(), r, m); err == nil {
+ t.Fatal("unusable evidence accepted")
+ }
+ })
+ }
+ before := assignmentReplace(t, s, id, func(r *Record) { r.FleetBox = "old" })
+ if _, err := SetRecordReplicaAssignment(ctx, s, id, want, replicas.Assignment{Desired: 2, Boxes: []string{"a", "b"}}); err == nil || !bytes.Equal(before, assignmentBytes(t, s, id)) {
+ t.Fatal("bootstrap lost the old copy")
+ }
+ got, err := SetRecordReplicaAssignment(ctx, s, id, want, replicas.Assignment{Desired: 2, Boxes: []string{"a", "b"}, Retiring: []string{"old"}})
+ if err != nil {
+ t.Fatal(err)
+ }
+ // An identical label or region does not move an active set.
+ if err := SetRecordFleetBox(ctx, s, id.Account, id.App, id.Host, FleetBoxExpect{Region: rec.Region, Label: "old", CreatedAt: rec.CreatedAt}, "old", time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ if err := SetRecordRegion(ctx, s, id.Account, id.App, id.Host, rec.Region); err != nil {
+ t.Fatal(err)
+ }
+ // New writers introduce RecordSeq even for records born without it.
+ ctx, s, _, id, want = assignmentFixture(t)
+ assignmentReplace(t, s, id, func(r *Record) { r.RecordSeq = 0 })
+ want.RecordSeq = 0
+ got, err = SetRecordReplicaAssignment(ctx, s, id, want, replicas.Assignment{Desired: 1, Boxes: []string{"a"}})
+ if err != nil || got.RecordSeq != 1 {
+ t.Fatalf("legacy counter: %+v %v", got, err)
+ }
+}
+
+func TestReplicaAssignmentOverflowAndUnknownState(t *testing.T) {
+ ctx, s, _, id, want := assignmentFixture(t)
+ before := assignmentReplace(t, s, id, func(r *Record) {
+ r.ReplicaAssignment = &replicas.Assignment{Revision: ^uint64(0), Desired: 1, Retiring: []string{"a"}}
+ })
+ want.Revision = ^uint64(0)
+ if _, err := SetRecordReplicaAssignment(ctx, s, id, want, replicas.Assignment{Revision: want.Revision, Desired: 2, Retiring: []string{"a"}}); err == nil || !bytes.Equal(before, assignmentBytes(t, s, id)) {
+ t.Fatal("assignment revision wrapped")
+ }
+ if _, err := RecordReplicaRetired(ctx, s, id, want.Revision, "a"); err == nil || !bytes.Equal(before, assignmentBytes(t, s, id)) {
+ t.Fatal("retirement revision wrapped")
+ }
+ for _, field := range []string{`"schema":2`, `"state":"unknown"`} {
+ ctx, s, _, id, want := assignmentFixture(t)
+ key := RecordKey(id.Account, id.App, id.Host)
+ raw, etag, err := s.Get(ctx, key)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var fields map[string]json.RawMessage
+ if err := json.Unmarshal(raw, &fields); err != nil {
+ t.Fatal(err)
+ }
+ fields["replica_assignment"] = json.RawMessage(`{"desired":1,` + field + `}`)
+ before, err := json.Marshal(fields)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := s.Put(ctx, key, before, etag); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := SetRecordReplicaAssignment(ctx, s, id, want, replicas.Assignment{Desired: 1}); err == nil || !bytes.Equal(before, assignmentBytes(t, s, id)) {
+ t.Fatal("unknown assignment state was erased")
+ }
+ }
+}
+
+type assignmentCountingStore struct {
+ release.Store
+ gets, puts int
+}
+
+func (s *assignmentCountingStore) Get(ctx context.Context, key string) ([]byte, string, error) {
+ s.gets++
+ return s.Store.Get(ctx, key)
+}
+func (s *assignmentCountingStore) Put(ctx context.Context, key string, body []byte, etag string) (string, error) {
+ s.puts++
+ return s.Store.Put(ctx, key, body, etag)
+}
+
+func TestReplicaAssignmentLegacyWriterReadBudget(t *testing.T) {
+ for _, region := range []bool{false, true} {
+ ctx, base, rec, id, _ := assignmentFixture(t)
+ // A legacy stateful record has no manifest evidence or assignment.
+ assignmentReplace(t, base, id, func(r *Record) { r.Hibernate = nil })
+ ctx = context.Background()
+ s := &assignmentCountingStore{Store: base}
+ var err error
+ if region {
+ err = SetRecordRegion(ctx, s, id.Account, id.App, id.Host, "fleet/other")
+ } else {
+ err = SetRecordFleetBox(ctx, s, id.Account, id.App, id.Host, FleetBoxExpect{Region: rec.Region, CreatedAt: rec.CreatedAt}, "a", time.Now())
+ }
+ if err != nil || s.gets != 1 || s.puts != 1 {
+ t.Fatalf("legacy writer budget: gets=%d puts=%d err=%v", s.gets, s.puts, err)
+ }
+ }
+}
diff --git a/internal/provision/replicacoordinator.go b/internal/provision/replicacoordinator.go
index cad940f94..818bc8239 100644
--- a/internal/provision/replicacoordinator.go
+++ b/internal/provision/replicacoordinator.go
@@ -62,10 +62,10 @@ func replicaFieldsFixed(ctx context.Context, before, body []byte) error {
if json.Unmarshal(before, &old) != nil || json.Unmarshal(body, &next) != nil {
return ErrRecordSequence
}
- if !reflect.DeepEqual(old.ReplicaAssignment, next.ReplicaAssignment) {
+ field, _ := ctx.Value(replicaWriteKey{}).(string)
+ if field != "replica_assignment" && !reflect.DeepEqual(old.ReplicaAssignment, next.ReplicaAssignment) {
return replicas.ErrFenced
}
- field, _ := ctx.Value(replicaWriteKey{}).(string)
if field != "coordinator" && !reflect.DeepEqual(old.Coordinator, next.Coordinator) {
return replicas.ErrFenced
}
diff --git a/internal/provision/stateless_placement_census_test.go b/internal/provision/stateless_placement_census_test.go
index eef0bdaf6..adb82c437 100644
--- a/internal/provision/stateless_placement_census_test.go
+++ b/internal/provision/stateless_placement_census_test.go
@@ -1,10 +1,25 @@
package provision
-// Plan 2 Task 1 slice 1b author review, including the two slice 1a CI gaps.
+// Plan 2 Tasks 1 and 2a author review; independent approval is controller-owned.
// These notes explain each re-digest. Independent approval is controller-owned.
func statelessPlacementWriteCensusInventory() []censusEntry {
entries := append([]censusEntry(nil), statelessReplicasWriteCensusInventory()...)
for _, next := range []censusEntry{
+ // Slice 2a: typed assignment CAS checks lifetime, region, RecordSeq and
+ // assignment revision on every attempt. Manifest evidence is supplied
+ // under caller publication exclusion; no new store read. Retirement
+ // obligations survive until the separate proof writer clears them.
+ {"internal/provision/replicaassignment.go", "SetRecordReplicaAssignment", "record-writer", "key:SetRecordReplicaAssignment,key:updateRecord", "11d04126fc53d7727f8364731ee512f26f4dec99f21ea5d084ea896682361802"},
+ // Slice 2a: authenticated termination ACK persistence checks lifetime
+ // and assignment revision again on CAS retry; removes only the named
+ // retiring member and advances revision/sequence. Caller verifies proof.
+ {"internal/provision/replicaassignment.go", "RecordReplicaRetired", "record-writer", "key:RecordReplicaRetired,key:updateRecord", "a6eb73e1a1c71beb5e41fb63076c0a4dcac0dcbb0468272358708ce97660b4f6"},
+ // Slice 2a: same region writer and read; before a move, refuse a set
+ // whose desired count exceeds one or whose members still need retiring.
+ {"internal/provision/provision.go", "SetRecordRegion", "record-writer", "key:SetRecordRegion,key:updateRecord", "778f4887cbd8f23211768f7858ac0b5a862c13f802076b99e30b04973b9f6606"},
+ // Slice 2a: same label CAS; the shared set guard runs only on relabel.
+ // Records without an assignment keep the previous read/write path.
+ {"internal/provision/fleetbox.go", "SetRecordFleetBox", "record-writer", "key:SetRecordFleetBox,key:updateRecord", "3a1de2c9d59325ff9e6d3734382e6c459db2a2dd457cbc49732ac327adb85b9f"},
// P7: sidecar create keeps the existing app lock and typed writer, pins the admitted name, and refuses counts above one before hostname marks or record creation. This also covers a fleet that shrank after count admission.
{"internal/console/hostsused.go", "Server.createSidecarMarked", "record-writer", "key:CreateSidecarRecord,key:SidecarRecordKey", "228da907d8e1f8cebc691c2eb728f2b8d80251f10f51e9da9673a278392f1faa"},
// P7: the default-bundle CAS preserves all fields and retains an explicit count after a decrease. It writes only config.json and its existing generation signal, never an instance record.
diff --git a/internal/provision/testdata/plan14-root-reads-stateless-replicas-2.tsv b/internal/provision/testdata/plan14-root-reads-stateless-replicas-2.tsv
index 9d9f5eb76..85bb43a0d 100644
--- a/internal/provision/testdata/plan14-root-reads-stateless-replicas-2.tsv
+++ b/internal/provision/testdata/plan14-root-reads-stateless-replicas-2.tsv
@@ -2,6 +2,6 @@
# 0 body, 0 sites, 5 envelope: each changed unit re-frozen at its existing disposition with its claim appended.
@coverage . 9857cb346182ee701b2dff653cee0c4b7ed36b038975d3eeaea75cc85da938b7
@coverage internal/appconfig 32d5f27628b319917ed88ac39e0b22e25292f8f16ba5ef4e69a57ea35471bf77
-@coverage internal/provision ae4676e47acb446f5377c9d5750de83f24c1eadad225e6ff6622cf8c723fe71e
+@coverage internal/provision b6684c18c0775437dc7d395706bd837ec31b32d087e66ccf805d0e169f8138f9
@coverage internal/release 6c7784eb02f9c2b68045266dabf5a79fb656bcb11a06427787d74ca8f3f96dd6
-@coverage internal/replicas 43d5d005572feb08938b489d62459752d510bc6349280bbd75437b66bca16a46
+@coverage internal/replicas d449179f2fe033691dd65005fd3bc80dc6f96f40d7e6b0dde1e6137b14c9b17e
diff --git a/internal/replicas/placement.go b/internal/replicas/placement.go
new file mode 100644
index 000000000..3ba210073
--- /dev/null
+++ b/internal/replicas/placement.go
@@ -0,0 +1,145 @@
+package replicas
+
+import (
+ "bytes"
+ "encoding/json"
+ "io"
+ "slices"
+ "sort"
+
+ "github.com/carlosframework/platform/internal/controlname"
+)
+
+func (a *Assignment) Contains(box string) bool {
+ return a != nil && slices.Contains(a.Boxes, box)
+}
+
+func ValidateAssignment(a Assignment) error {
+ if a.Desired <= 0 || len(a.Boxes) > a.Desired {
+ return ErrInvalid
+ }
+ seen := make(map[string]bool, len(a.Boxes)+len(a.Retiring))
+ for _, labels := range [][]string{a.Boxes, a.Retiring} {
+ for i, label := range labels {
+ if !controlname.ValidLabel(label) || seen[label] || (i > 0 && labels[i-1] >= label) {
+ return ErrInvalid
+ }
+ seen[label] = true
+ }
+ }
+ return nil
+}
+
+// Unknown assignment fields must survive as a refusal, not disappear in a CAS.
+// There is no schema or state discriminator in this version of Assignment.
+func (a *Assignment) UnmarshalJSON(raw []byte) error {
+ d := json.NewDecoder(bytes.NewReader(raw))
+ if token, err := d.Token(); err != nil || token != json.Delim('{') {
+ return ErrInvalid
+ }
+ var next Assignment
+ seen := map[string]bool{}
+ for d.More() {
+ token, err := d.Token()
+ if err != nil {
+ return ErrInvalid
+ }
+ name, ok := token.(string)
+ if !ok || seen[name] {
+ return ErrInvalid
+ }
+ seen[name] = true
+ var value json.RawMessage
+ if d.Decode(&value) != nil || bytes.Equal(value, []byte("null")) {
+ return ErrInvalid
+ }
+ var target any
+ switch name {
+ case "revision":
+ target = &next.Revision
+ case "desired":
+ target = &next.Desired
+ case "boxes":
+ target = &next.Boxes
+ case "retiring":
+ target = &next.Retiring
+ default:
+ return ErrInvalid
+ }
+ if json.Unmarshal(value, target) != nil {
+ return ErrInvalid
+ }
+ }
+ if token, err := d.Token(); err != nil || token != json.Delim('}') {
+ return ErrInvalid
+ }
+ if _, err := d.Token(); err != io.EOF {
+ return ErrInvalid
+ }
+ if err := ValidateAssignment(next); err != nil {
+ return err
+ }
+ *a = next
+ return nil
+}
+
+type Candidate struct {
+ Label string
+ Load int
+ Eligible bool
+}
+
+func Place(current Assignment, candidates []Candidate) (Assignment, error) {
+ current.Boxes = slices.Clone(current.Boxes)
+ current.Retiring = slices.Clone(current.Retiring)
+ sort.Strings(current.Boxes)
+ sort.Strings(current.Retiring)
+ // Lowering Desired is how the caller asks for a scale-down. Validate the
+ // old membership before selecting the deterministic surviving prefix.
+ shape := current
+ if shape.Desired > 0 && len(shape.Boxes) > shape.Desired {
+ shape.Desired = len(shape.Boxes)
+ }
+ if err := ValidateAssignment(shape); err != nil {
+ return Assignment{}, err
+ }
+ byLabel := make(map[string]Candidate, len(candidates))
+ for _, c := range candidates {
+ if !controlname.ValidLabel(c.Label) || c.Load < 0 {
+ return Assignment{}, ErrInvalid
+ }
+ if old, ok := byLabel[c.Label]; ok && old != c {
+ return Assignment{}, ErrInvalid
+ }
+ byLabel[c.Label] = c
+ }
+ next := Assignment{Revision: current.Revision, Desired: current.Desired, Retiring: current.Retiring}
+ for _, box := range current.Boxes {
+ if byLabel[box].Eligible && len(next.Boxes) < next.Desired {
+ next.Boxes = append(next.Boxes, box)
+ } else {
+ next.Retiring = append(next.Retiring, box)
+ }
+ }
+ available := make([]Candidate, 0, len(byLabel))
+ for _, c := range byLabel {
+ if c.Eligible && !next.Contains(c.Label) && !slices.Contains(next.Retiring, c.Label) {
+ available = append(available, c)
+ }
+ }
+ sort.Slice(available, func(i, j int) bool {
+ if available[i].Load != available[j].Load {
+ return available[i].Load < available[j].Load
+ }
+ return available[i].Label < available[j].Label
+ })
+ for _, c := range available {
+ if len(next.Boxes) == next.Desired {
+ break
+ }
+ next.Boxes = append(next.Boxes, c.Label)
+ }
+ sort.Strings(next.Boxes)
+ sort.Strings(next.Retiring)
+ return next, ValidateAssignment(next)
+}
diff --git a/internal/replicas/placement_test.go b/internal/replicas/placement_test.go
new file mode 100644
index 000000000..125fe1ef2
--- /dev/null
+++ b/internal/replicas/placement_test.go
@@ -0,0 +1,81 @@
+package replicas
+
+import (
+ "encoding/json"
+ "math/rand"
+ "reflect"
+ "testing"
+)
+
+func TestReplicaAssignmentShape(t *testing.T) {
+ good := Assignment{Revision: 3, Desired: 2, Boxes: []string{"a", "b"}, Retiring: []string{"c", "d"}}
+ if err := ValidateAssignment(good); err != nil {
+ t.Fatal(err)
+ }
+ if !good.Contains("a") || good.Contains("c") || (*Assignment)(nil).Contains("a") {
+ t.Fatal("membership includes a retirement or omits a member")
+ }
+ for name, a := range map[string]Assignment{
+ "duplicates": {Desired: 3, Boxes: []string{"a", "a"}},
+ "unsorted": {Desired: 2, Boxes: []string{"b", "a"}},
+ "too-many": {Desired: 1, Boxes: []string{"a", "b"}},
+ "bad-label": {Desired: 1, Boxes: []string{"../a"}},
+ "zero": {}, "negative": {Desired: -1},
+ "retiring-duplicates": {Desired: 1, Retiring: []string{"a", "a"}},
+ "retiring-unsorted": {Desired: 1, Retiring: []string{"b", "a"}},
+ "retiring-bad-label": {Desired: 1, Retiring: []string{"A"}},
+ "overlap": {Desired: 1, Boxes: []string{"a"}, Retiring: []string{"a"}},
+ } {
+ t.Run(name, func(t *testing.T) {
+ if ValidateAssignment(a) == nil {
+ t.Fatal("invalid assignment accepted")
+ }
+ })
+ }
+ for _, raw := range []string{`{"desired":1,"schema":2}`, `{"desired":1,"state":"unknown"}`, `{"desired":1,"desired":2}`, `{"desired":1,"Boxes":["a"]}`, `null`} {
+ var a Assignment
+ if json.Unmarshal([]byte(raw), &a) == nil {
+ t.Fatalf("unknown/ambiguous wire shape accepted: %s", raw)
+ }
+ }
+}
+
+func TestReplicaPlaceStableDistinctAndReordered(t *testing.T) {
+ current := Assignment{Revision: 7, Desired: 3, Boxes: []string{"a", "b"}, Retiring: []string{"z"}}
+ candidates := []Candidate{{"a", 90, true}, {"b", 80, true}, {"c", 2, true}, {"d", 2, true}, {"z", 0, true}, {"e", 0, false}, {"c", 2, true}}
+ want := Assignment{Revision: 7, Desired: 3, Boxes: []string{"a", "b", "c"}, Retiring: []string{"z"}}
+ saved, _ := json.Marshal(current)
+ for i := 0; i < 30; i++ {
+ rand.New(rand.NewSource(int64(i))).Shuffle(len(candidates), func(i, j int) { candidates[i], candidates[j] = candidates[j], candidates[i] })
+ got, err := Place(current, candidates)
+ if err != nil || !reflect.DeepEqual(got, want) {
+ t.Fatalf("placement %+v, %v; want %+v", got, err, want)
+ }
+ again, err := Place(got, candidates)
+ if err != nil || !reflect.DeepEqual(again, got) {
+ t.Fatal("placement rebalanced")
+ }
+ }
+ after, _ := json.Marshal(current)
+ if string(saved) != string(after) {
+ t.Fatal("placement mutated input")
+ }
+}
+
+func TestReplicaPlaceRetirementAndShortfall(t *testing.T) {
+ current := Assignment{Revision: 4, Desired: 2, Boxes: []string{"a", "b"}}
+ got, err := Place(current, []Candidate{{"a", 9, true}, {"b", 0, false}, {"a", 9, true}})
+ if err != nil || !reflect.DeepEqual(got, Assignment{Revision: 4, Desired: 2, Boxes: []string{"a"}, Retiring: []string{"b"}}) {
+ t.Fatalf("shortfall: %+v %v", got, err)
+ }
+ current.Desired = 1
+ got, err = Place(current, []Candidate{{"a", 9, true}, {"b", 0, true}})
+ if err != nil || !reflect.DeepEqual(got, Assignment{Revision: 4, Desired: 1, Boxes: []string{"a"}, Retiring: []string{"b"}}) {
+ t.Fatalf("scale down: %+v %v", got, err)
+ }
+ for _, cs := range [][]Candidate{{{"a", 1, true}, {"a", 2, true}}, {{"a", 1, true}, {"a", 1, false}}, {{"../a", 1, true}}} {
+ if _, err := Place(Assignment{Desired: 2}, cs); err == nil {
+ t.Fatal("ambiguous candidates accepted")
+ }
+ }
+}