carlos / platform Public

fix: isolate replica placement and bound evidence reads

Keep replica evidence failures and busy app locks from suppressing legacy
relabel and drain. Classify legacy records by assignment presence and
clear discovery when a one-copy app has no assignments left.

Persist dirty count edits in SQL and use successful inventory observations
to skip steady evidence reads. Re-read evidence before typed writes, decide
one none/set/clear/halt action, and charge only committed membership.

Release reconcile exclusion before ACK and coordinator network calls.
Make set-binding validation determine acceptance, retain legacy Unit
behaviour, guard active swaps without assignments, and show both detach
confirmation and warning. Refresh the cumulative census and record-write
inventory; validation and baseline exceptions are in the Task 3 report.
Co-Authored-By: Codex (gpt-6-astra) <noreply@openai.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev 9f19bdb4012e86f1c297838ff8100d73851ceba2 parent 4624c79
16 files changed, +814 −254
  • docs/superpowers/notes/census-proposal-stateless-replicas-2.md +1 −1
  • internal/console/appcopies.go +2 −4
  • internal/console/fleetbox.go +15 −3
  • internal/console/fleetrelabel.go +5 −6
  • internal/console/fleets.go +2 −5
  • internal/console/replicaplacement.go +355 −189
  • internal/console/replicaplacement_fix_test.go +303 −0
  • internal/console/replicaplacement_test.go +6 −3
  • internal/console/server.go +3 −2
  • internal/console/store.go +4 −2
  • internal/host/fleetbind.go +18 −9
  • internal/host/replica_request_budget_test.go +75 −16
  • internal/host/replicaplacement.go +7 −5
  • internal/provision/stateless_placement_census_test.go +12 −3
  • internal/provision/testdata/plan14-root-reads-chain.tsv +1 −1
  • internal/provision/testdata/plan14-root-reads-stateless-replicas-2.tsv +5 −5

CI passed — run details

Intent

Human

<task-notification> <task-id>byx1hdaxy</task-id> <tool-use-id>toolu_0141CKf7RtAF7g8Mb9vRvayY</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/7c5a7d70-0e28-42b9-896c-5d73b2d2a05d/tasks/byx1hdaxy.output</output-file> <status>completed</status> <summary>Background command "Wait for 3b and CI on 1f16c301" completed (exit code 0)</summary> </task-notification>

Human

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

Human

<task-notification> <task-id>a3d58c35229db54b3</task-id> <tool-use-id>toolu_01NzwbtT3oBjcHZomjf1ijVd</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/7c5a7d70-0e28-42b9-896c-5d73b2d2a05d/tasks/a3d58c35229db54b3.output</output-file> <status>completed</status> <summary>Agent "Review Task 3 (spec + quality)" 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>### Spec Compliance The requested interfaces are all present: the two placement functions with the exact signatures, the authenticated `retired` coordinator operation, the additive `FleetBinding` fields, the P14 read-free admission, P15 decrease handling, P16 conversion through a typed writer, swap freeze with loss halt, and coordinator transfer only after the old lease expires. All the named tests exist. I read the whole diff in eight passes, one group of files at a time (lines are up to 11k characters). I made five lookups outside the diff, each for one named risk: `handleReplicaRelease`, the `drainBox` fleet lock, `Record.Unit`, `reconcileMu` plus `CoordinationClient.Acquire`, and `Service.Quiesced`. I ran no tests. Late in the review the sandbox stopped starting (bwrap could not find a worktree's `commondir` while other sessions were changing worktrees), so I read the last few hunks with Read. The fit is not clean in three places: - **Inert-for-existing-apps is broken on fleets that also host an opted-in app.** Legacy apps on those fleets can lose relabel and drain behaviour (Important 1 and 2). - **Steady passes re-read evidence.** The brief says "reconcile only changed config/assignment records", but every pass re-reads config, policy, channel heads and manifests for every opted-in app (Important 4). - **The hub reader's "validates key/lifetime/revision/ownership" check does nothing** (Minor 1). **Missing:** none of the named items. **Extra:** `movable` now refuses `rec.Unit` on the legacy path too (Minor 3). ### Strengths - **Retired-op authentication is sound.** The box comes from the path name plus `fleetIdentityOK`, never the payload. Retiring membership and the exact revision are checked again under `withRecordLock`, and the typed writer checks them a third time inside its CAS. Tests cover wrong box, revoked token, wrong revision, not-retiring and stale lifetime. - **The box-side proof is conservative.** It needs no registry row, no activator entry, and empty nested and flat cgroups, all under `reconcileMu` so reconcile cannot mint a row mid-proof. It never kills anything. A detached or lost box keeps its obligation. - **No early coordinator takeover.** `ReplicaCoordinatorBox` returns "" for a live lease held by a non-member, so a removed coordinator cannot renew. Other members get the held expiry back as their retry time. Release still requires the caller to be the coordinator (`replicacoordinator.go:160`, unchanged). - **The P16 conversion cannot race a copies increase.** The placement pass holds the same `appLocks` key that the copies API takes. Clear is a CAS on RecordSeq and the revision. Re-opt-in uses RecordSeq as its revision floor, so an old ACK cannot match a later set (`replicaassignment.go` `max(..., rec.RecordSeq)`). - **Lock order is safe.** Fleet lock, then try-lock on the app and name locks. A busy lock means skip and retry on the next pass, with no deadlock against create. - **Request budget is unchanged on the box.** `replicaReconcileBudget` shows reconcile traces for one, two and five copies identical to the one-copy (1b) trace, and the binding is one object per host. - **Test waits all have deadlines** (5 s, 15 s, 5 s). ### Issues #### Critical (Must Fix) None. #### Important (Should Fix) 1. **A replica evidence error turns off legacy relabel and drain for every other app on the fleet.** - In `fleetrelabel.go` (`fleetRelabelPass`), an error from `reconcileReplicaFleet` hits `continue` before `relabelFleet`. - In `drainBox`, the same error returns after `SetFleetBoxDraining` has already been written but before `writeRelabels(plan)`. The legacy records stay on the draining box, and the relabel worker that should "move the rest" is blocked by the same error. - The errors are persistent, not just transient ones. In `replicaplacement.go` `reconcileReplicaFleet`: the precheck `release.Channel` head is nil when a record's channel has no release (`return nil, replicas.ErrFenced`), `AuthorizedManifest` can fail, `copiesDefault` or `apppolicy.Get` reads can fail, `ownsFleet` can be false, and `replicaNext` returns `ErrInvalid` for an unmovable record of an opted-in app. - So one bad opted-in record stops failover for legacy apps that have no copies config. That breaks the merge gate's "legacy relabel/drain unchanged". - Fix: scope the refusal to the affected app or record, and always run the legacy relabel and drain moves. 2. **A stale discovery marker hides legacy records from the drain's stranded-app refusal.** - The copies API sets `copies_configured` only for counts above 1. The pass clears it only when the config is not explicit (`if !cfg.explicit { markReplicaApp(false) }`). - Every app that goes 2 → 1 through the API is explicit 1, so after P16 its marker stays on forever. - `drainBox` skips `v.replicaRecord(rec)` records before `reconcileReplicaFleet` removes the app from `ReplicaApps` (`fleetrelabel.go` drain loop). That app's now-legacy one-box record is neither planned nor counted as stranded. The drain no longer refuses and names it when it has nowhere to go, which opens the way to taking a one-copy app down at detach. - The same skip hides these records from `relabelFleet` whenever `reconcileReplicaFleet` returns early before reaching that app: a busy lock, `!v.Complete`, or an earlier app's `!replicaViewReady`, which persists while the fleet is below the floor. - The marker also costs one config GET per pass forever. - Fix: clear the marker once n == 1 and no record carries an assignment, explicit or not. Or have the drain and relabel use the assignment alone, not the marker. 3. **The box worker holds `reconcileMu` across network calls.** - In `internal/host/replicaplacement.go` `run`, `reconcileMu.Lock()` is held around `w.retired(rctx, ...)` (30 s timeout), `coordinator.Acquire` (a network call when no lease is cached) and `publisher.publish` (bucket GET/PUT), once per pending item in sequence. - `reconcileMu` serializes every provisioning pass on the box (`agent.go:1816`). If the console is slow or unreachable, legacy apps' reconcile on that box stalls for up to 30 s per pending item on each retry round. - The ACK itself is protected by the revision CAS, so only the local proof (row absent, quiet, empty cgroups) needs the lock. Release the lock before the POST, Acquire and publish. 4. **Every steady placement pass re-reads evidence (needs a ruling).** - Each opted-in app costs about 8 bucket GETs every fleet pass even when nothing changed: config, size policy, channel pointers, and manifests with their promotion authorizations. The report's own accounting shows a steady pass at 10 GETs against 2 heartbeat GETs for a warm legacy fleet. - The brief says "reconcile only changed config/assignment records", and the index budget lists only record, inventory and loadFleetView reads. - The report discloses this, but it is not inside the stated budget. Either gate the evidence reads on a record, config or serial change, or get an explicit controller ruling accepting per-app console polling. #### Minor (Nice to Have) 1. **The hub binding validation does nothing.** In `internal/host/fleetbind.go`, `ReconcileFleetBindings` reads `if !validReplicaFleetBinding(...) { continue }; continue`. The result is discarded, so it only costs `FleetOwners` and `ListFleetBoxes`. It is safe, because sets are ignored either way, but the claimed "validates" is false. `TestReplicaHubBindingReader` would pass with the validator deleted from that path. 2. **Latent nil dereference.** In `replicaNext`, the swap-active branch does `return *rec.ReplicaAssignment`. A legacy record (assignment nil) of an app raised to copies=2 that has an active swap would panic the console pass goroutine. Nothing writes `ActiveBox` today (`SetRecordReplicaRelease` refuses it), but Plan 4 will make this reachable. 3. **Legacy `movable` behaviour changed** (⚠️ unchanged-path change). `movable` now refuses `rec.Unit != ""` for legacy relabel and drain too (`fleetbox.go`). This is probably harmless, since adopted units are control-plane records, but it is a legacy behaviour change outside the stated gate. 4. **Detach warnings.** On the fleet page, a warning replaces the "Detached X." confirmation instead of adding to it. When the view is incomplete, `replicaDetachWarnings` silently returns no warning, so a truthful shortfall can go unreported. 5. **Duplicated logic.** The "changed / P16-eligible" predicate is copied between `placeReplicaRecord` and `reconcileReplicaFleet` as very long one-line conditions. `replicaNext` runs about three times per record per pass. In the halt case, `Load` is updated as if `next` had been written. One helper returning a typed action (none, set, clear, halt) would remove the copies. 6. ⚠️ **Plan-level gap.** A box that dies for good never ACKs, and `fleetIdentityOK` refuses detached boxes. So `Retiring` persists forever and blocks P16 and stateful publication. This matches the index invariant, but no operator path exists, so it should be noted for the plan. 7. **Marker discovery edge case.** On a one-box fleet whose console database was restored without the marker, `loadFleetViewAt` returns before the inventory read, so an existing assignment is never discovered or repaired. As a durable discovery bit, `copies_configured` is otherwise a reasonable, inert choice: it is a SQL-only read, migration and rebuild keep it, and config stays the count authority. ### Assessment **Task quality:** Needs fixes **Reasoning:** The core replica mechanics (ACK authentication and proof, coordinator transfer, swap freeze, P16 CAS and revision fencing) are well built and tested. But the console pass ties legacy relabel and drain to the health of opted-in apps' evidence, and the marker hides converted legacy records from drain refusal, which together break the "inert for existing apps" gate. The box worker also holds the box-wide reconcile lock across HTTP calls.</result> <usage><subagent_tokens>148873</subagent_tokens><tool_uses>29</tool_uses><duration_ms>565939</duration_ms></usage> </task-notification>

Attributed to this commit: 41.0 g CO₂e (5,127,206 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/docs/superpowers/notes/census-proposal-stateless-replicas-2.md b/docs/superpowers/notes/census-proposal-stateless-replicas-2.md
index 715a8f7e1..c7ae9621f 100644
--- a/docs/superpowers/notes/census-proposal-stateless-replicas-2.md
+++ b/docs/superpowers/notes/census-proposal-stateless-replicas-2.md
@@ -66,6 +66,6 @@ New dispositions, which census-propose wrote and the reviewer checks against the
- reads `internal/registry/registry.go:scanRoute`: +registry:Copies, +registry:FleetBoxes, +registry:ReplicaIncarnation, +registry:ReplicaRevision; keeps legacy, task accepted-legacy
- reads `internal/registry/remote_dispatch.go:Registry.dispatchRemote`: +registry:Assignment ×2, +registry:Changed ×2, +registry:Host ×2, +registry:Observed ×4, +registry:On, +registry:ReplicaLife ×2, +registry:TValue, +whole:Route ×5; keeps hint, task E2
-Seal: `df8bf8056d80b9d78edc957fe7f2adbc75885e15f581e58167768346c4e05771` → `1d704149c47d2cdb710aaf7dfc9a0aa4256cfbf69349afa23fa7f06997674879`.
+Seal: `df8bf8056d80b9d78edc957fe7f2adbc75885e15f581e58167768346c4e05771` → `125f7cbab86efcf81600ee0ae08c10d29acaa49e46f69422daa078d58dd85731`.
Overlay: `internal/provision/testdata/plan14-root-reads-stateless-replicas-2.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`.
diff --git a/internal/console/appcopies.go b/internal/console/appcopies.go
index e6a46ad30..6580351af 100644
--- a/internal/console/appcopies.go
+++ b/internal/console/appcopies.go
@@ -96,10 +96,8 @@ 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
- }
+ 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)
diff --git a/internal/console/fleetbox.go b/internal/console/fleetbox.go
index 749cceeb0..47fb60387 100644
--- a/internal/console/fleetbox.go
+++ b/internal/console/fleetbox.go
@@ -54,6 +54,8 @@ type fleetView struct {
Records []provision.Record
Complete bool
ReplicaApps map[AppRef]bool
+ ReplicaDirty map[AppRef]bool
+ RecordETags map[string]string
ReplicaManifests map[string]*release.Manifest
ReplicaCounts map[AppRef]int
ReplicaSizes map[string]string
@@ -166,7 +168,10 @@ func fleetLabelsRecord(rec provision.Record) bool {
// 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 != "" {
+ if rec.Addr != "" || len(rec.Addrs) > 0 || rec.HA {
+ return false
+ }
+ if rec.Unit != "" && (rec.ReplicaAssignment != nil || len(verified) != 0) {
return false
}
if rec.Runtime == "" && rec.Hibernate != nil && !*rec.Hibernate && len(verified) == 1 {
@@ -292,7 +297,7 @@ func (s *Server) loadFleetViewAt(ctx context.Context, fleet string, now time.Tim
if s.cfg.Releases == nil {
return v, nil
}
- v.ReplicaApps, err = s.replicaFleetApps(ctx, fleet)
+ v.ReplicaApps, v.ReplicaDirty, err = s.replicaFleetState(ctx, fleet)
if err != nil {
return v, err
}
@@ -342,6 +347,13 @@ func (s *Server) loadFleetViewAt(ctx context.Context, fleet string, now time.Tim
whole = false
}
v.Records = recs
+ inv := s.fleetInventory(fleet)
+ inv.mu.Lock()
+ v.RecordETags = make(map[string]string, len(inv.records))
+ for key, object := range inv.records {
+ v.RecordETags[key] = object.etag
+ }
+ inv.mu.Unlock()
for _, rec := range recs {
if !fleetLabelsRecord(rec) {
continue
@@ -354,7 +366,7 @@ func (s *Server) loadFleetViewAt(ctx context.Context, fleet string, now time.Tim
} else if rec.FleetBox != "" {
v.Load[rec.FleetBox]++
}
- if !movable(rec) {
+ if rec.ReplicaAssignment == nil && !movable(rec) {
v.Unmovable = true
}
}
diff --git a/internal/console/fleetrelabel.go b/internal/console/fleetrelabel.go
index 197751652..69e6a4784 100644
--- a/internal/console/fleetrelabel.go
+++ b/internal/console/fleetrelabel.go
@@ -123,8 +123,6 @@ func (s *Server) fleetRelabelPass(ctx context.Context, now time.Time) error {
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)
@@ -167,7 +165,7 @@ func (s *Server) relabelFleet(ctx context.Context, fleet string, v fleetView, no
plan = append(plan, first...)
}
for _, rec := range v.Records {
- if v.replicaRecord(rec) || !fleetLabelsRecord(rec) || rec.FleetBox == "" {
+ if rec.ReplicaAssignment != nil || !fleetLabelsRecord(rec) || rec.FleetBox == "" {
continue
}
reason := v.boxGone(rec.FleetBox, now)
@@ -196,7 +194,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 v.replicaRecord(rec) || !fleetLabelsRecord(rec) || rec.FleetBox != "" || !movable(rec) {
+ if rec.ReplicaAssignment != nil || !fleetLabelsRecord(rec) || rec.FleetBox != "" || !movable(rec) {
continue
}
b, ok, err := s.readFleetBinding(ctx, fleet, rec.Host)
@@ -453,7 +451,7 @@ 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) {
+ if rec.ReplicaAssignment != nil {
continue
}
if !fleetLabelsRecord(rec) || (rec.FleetBox != "" && rec.FleetBox != label) {
@@ -490,7 +488,8 @@ func (s *Server) drainBox(ctx context.Context, fleet, label string) (stuck []str
}
}
if err := s.reconcileReplicaFleet(ctx, fleet, v, now); err != nil {
- return nil, err
+ jobFailed(ctx, err)
+ log.Printf("console: replica placement %s: %v", fleet, err)
}
moved := s.writeRelabels(ctx, fleet, plan, now)
if moved < len(plan) {
diff --git a/internal/console/fleets.go b/internal/console/fleets.go
index a583c40d3..39e73b897 100644
--- a/internal/console/fleets.go
+++ b/internal/console/fleets.go
@@ -1613,11 +1613,8 @@ func (s *Server) handleFleetDetachBoxPage(w http.ResponseWriter, r *http.Request
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+".")
+ confirmation := "Detached " + fleet.Name + "/" + label + "."
+ back("ok", strings.Join(append([]string{confirmation}, warnings...), "\n"))
}
// handleFleetTagBoxPage answers the owner's "Tag" form: the same full-replace
diff --git a/internal/console/replicaplacement.go b/internal/console/replicaplacement.go
index 1c2ec987e..6647eb96c 100644
--- a/internal/console/replicaplacement.go
+++ b/internal/console/replicaplacement.go
@@ -2,6 +2,7 @@ package console
import (
"context"
+ "encoding/json"
"errors"
"fmt"
"os"
@@ -23,34 +24,43 @@ import (
// 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)
+ _, err := st.db.ExecContext(ctx, `UPDATE apps SET copies_configured = ?, copies_dirty = ? WHERE account_id = ? AND app = ? AND deleted_at = 0`, enabled, 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))
+func (s *Store) settleReplicaApp(ctx context.Context, account int64, app string, configured bool) error {
+ return s.withAutoAppSQL(ctx, account, app, "sql.MarkReplicaApp", func(st *Store) error {
+ _, err := st.db.ExecContext(ctx, `UPDATE apps SET copies_configured = ?, copies_dirty = 0 WHERE account_id = ? AND app = ? AND deleted_at = 0`, configured, account, app)
+ return err
+ })
+}
+
+func (s *Server) replicaFleetState(ctx context.Context, fleet string) (map[AppRef]bool, map[AppRef]bool, error) {
+ rows, err := s.store.db.QueryContext(ctx, `SELECT a.sqid,p.app,p.copies_dirty 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 OR p.copies_dirty=1)`, registry.PlacementTarget(fleet))
if err != nil {
- return nil, err
+ return nil, nil, err
}
defer rows.Close()
- out := map[AppRef]bool{}
+ apps, dirty := map[AppRef]bool{}, map[AppRef]bool{}
for rows.Next() {
- var a AppRef
- if err := rows.Scan(&a.Sqid, &a.App); err != nil {
- return nil, err
+ var app AppRef
+ var changed bool
+ if err := rows.Scan(&app.Sqid, &app.App, &changed); err != nil {
+ return nil, nil, err
}
- out[a] = true
+ apps[app], dirty[app] = true, changed
}
- return out, rows.Err()
+ return apps, dirty, rows.Err()
}
-func replicaRecordKey(rec provision.Record) string {
- return provision.RecordKey(rec.Account, rec.App, rec.Host)
+func (s *Server) replicaFleetApps(ctx context.Context, fleet string) (map[AppRef]bool, error) {
+ apps, _, err := s.replicaFleetState(ctx, fleet)
+ return apps, err
}
-func (v fleetView) replicaRecord(rec provision.Record) bool {
- return rec.ReplicaAssignment != nil || v.ReplicaApps[AppRef{Sqid: rec.Account, App: rec.App}]
+func replicaRecordKey(rec provision.Record) string {
+ return provision.RecordKey(rec.Account, rec.App, rec.Host)
}
func (s *Server) replicaBuild() string {
@@ -99,22 +109,9 @@ func (s *Server) replicaNext(rec provision.Record, v fleetView, n int) (replicas
} 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})
+ candidates, err := replicaCandidates(rec, v, n, v.ReplicaSizes[replicaRecordKey(rec)])
+ if err != nil {
+ return replicas.Assignment{}, err
}
next, err := replicas.Place(current, candidates)
if err != nil {
@@ -133,78 +130,210 @@ func (s *Server) replicaNext(rec provision.Record, v fleetView, n int) (replicas
}
}
}
- if provision.ReplicaSwapActive(&rec) {
- lost := false
- for _, box := range current.Boxes {
- fresh := false
- for _, member := range v.Boxes {
- if member.Label == box && member.Fresh {
- fresh = true
- }
+
+ return next, nil
+}
+
+func replicaCandidates(rec provision.Record, v fleetView, n int, sizeName string) ([]replicas.Candidate, error) {
+ if sizeName == "" {
+ sizeName = "standard"
+ }
+ size, ok := cgroup.SizeByName(sizeName)
+ if !ok {
+ return nil, 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 candidates, nil
+}
+
+type replicaActionKind uint8
+
+const (
+ replicaNone replicaActionKind = iota
+ replicaSet
+ replicaClear
+ replicaHalt
+)
+
+type replicaPlacementAction struct {
+ kind replicaActionKind
+ next replicas.Assignment
+}
+
+func replicaMemberLost(rec provision.Record, v fleetView) bool {
+ if rec.ReplicaAssignment == nil {
+ return false
+ }
+ for _, box := range rec.ReplicaAssignment.Boxes {
+ fresh := false
+ for _, member := range v.Boxes {
+ if member.Label == box && member.Fresh {
+ fresh = true
+ break
}
- lost = lost || !fresh
}
- if !lost {
- return *rec.ReplicaAssignment, nil
+ if !fresh {
+ return true
}
}
- return next, nil
+ return false
}
-// 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.
-// P15: additions use the latest app count read under that exclusion. A decrease
-// can commit before this pass; its existing excess members stop after this pass
-// moves them to Retiring. Boxes do not read app config or add a start fence.
-func (s *Server) placeReplicaRecord(ctx context.Context, rec provision.Record, v fleetView, n int) error {
+// One decision per record, after fresh publication evidence and before its CAS.
+func (s *Server) replicaAction(rec provision.Record, v fleetView, n int) (replicaPlacementAction, error) {
if n == 1 && rec.ReplicaAssignment == nil {
- return nil
+ return replicaPlacementAction{}, nil
+ }
+ if !s.replicaViewReady(v, n) {
+ return replicaPlacementAction{}, replicas.ErrFenced
+ }
+ if _, err := provision.WithReplicaAssignmentManifest(context.Background(), rec, v.ReplicaManifests[replicaRecordKey(rec)]); err != nil {
+ return replicaPlacementAction{}, err
+ }
+ if provision.ReplicaSwapActive(&rec) {
+ if rec.ReplicaAssignment == nil || !replicaMemberLost(rec, v) {
+ return replicaPlacementAction{}, nil
+ }
+ return replicaPlacementAction{kind: replicaHalt, next: *rec.ReplicaAssignment}, nil
}
next, err := s.replicaNext(rec, v, n)
if err != nil {
- return err
+ return replicaPlacementAction{}, err
}
- if old := rec.ReplicaAssignment; old != nil && !(n == 1 && old.Desired == 1 && len(old.Boxes) == 1 && len(old.Retiring) == 0 && !provision.ReplicaSwapActive(&rec)) && old.Desired == next.Desired && slices.Equal(old.Boxes, next.Boxes) && slices.Equal(old.Retiring, next.Retiring) {
- return nil
+ if old := rec.ReplicaAssignment; old != nil && old.Desired == next.Desired && slices.Equal(old.Boxes, next.Boxes) && slices.Equal(old.Retiring, next.Retiring) {
+ if n == 1 && len(old.Boxes) == 1 && len(old.Retiring) == 0 {
+ return replicaPlacementAction{replicaClear, next}, nil
+ }
+ return replicaPlacementAction{}, nil
+ }
+ return replicaPlacementAction{replicaSet, next}, nil
+}
+
+func (s *Server) applyReplicaAction(ctx context.Context, rec provision.Record, v fleetView, action replicaPlacementAction) (*provision.Record, error) {
+ if action.kind == replicaNone {
+ return &rec, nil
}
- ctx, err = provision.WithReplicaAssignmentManifest(ctx, rec, v.ReplicaManifests[replicaRecordKey(rec)])
+ ctx, err := provision.WithReplicaAssignmentManifest(ctx, rec, v.ReplicaManifests[replicaRecordKey(rec)])
if err != nil {
- return err
+ return nil, err
}
inc, err := provision.Incarnation(rec.Account, rec.App, rec.Host, rec.CreatedAt)
if err != nil {
- return err
+ return nil, err
}
id := replicas.Identity{Account: rec.Account, App: rec.App, Host: rec.Host, Incarnation: inc}
- want := replicas.Expect{Incarnation: inc, Region: rec.Region, RecordSeq: rec.RecordSeq, Revision: next.Revision}
- if provision.ReplicaSwapActive(&rec) {
- _, err = provision.HaltRecordReplicaDeploy(ctx, s.cfg.Releases, id, want, rec.ReplicaDeploy.Revision)
- return err
+ want := replicas.Expect{Incarnation: inc, Region: rec.Region, RecordSeq: rec.RecordSeq, Revision: action.next.Revision}
+ switch action.kind {
+ case replicaHalt:
+ return provision.HaltRecordReplicaDeploy(ctx, s.cfg.Releases, id, want, rec.ReplicaDeploy.Revision)
+ case replicaClear:
+ return provision.ClearRecordReplicaAssignment(ctx, s.cfg.Releases, id, want)
+ case replicaSet:
+ fleet, _ := registry.FleetPlacement(rec.Region)
+ reg, err := s.openPassRegistry()
+ if err != nil {
+ return nil, err
+ }
+ for _, box := range action.next.Boxes {
+ if err := reg.MarkFleetBoxLabelled(fleet, box, time.Now().UnixNano()); err != nil {
+ return nil, err
+ }
+ }
+ return provision.SetRecordReplicaAssignment(ctx, s.cfg.Releases, id, want, action.next)
+ default:
+ return nil, replicas.ErrInvalid
}
- if old := rec.ReplicaAssignment; n == 1 && old != nil && old.Desired == 1 && len(old.Boxes) == 1 && len(old.Retiring) == 0 && slices.Equal(old.Boxes, next.Boxes) {
- _, err = provision.ClearRecordReplicaAssignment(ctx, s.cfg.Releases, id, want)
+}
+
+// Caller holds fleet and app publication exclusion. P15 bounds additions by
+// the current count; a decrease retains retirement obligations until proof.
+func (s *Server) placeReplicaRecord(ctx context.Context, rec provision.Record, v fleetView, n int) error {
+ action, err := s.replicaAction(rec, v, n)
+ if err != nil {
return err
}
- fleet, _ := registry.FleetPlacement(rec.Region)
- reg, err := s.openPassRegistry()
+ _, err = s.applyReplicaAction(ctx, rec, v, action)
+ return err
+}
+
+type replicaPlacementObservation struct {
+ stamp, size string
+ desired int
+}
+type replicaPlacementCache struct {
+ records map[string]replicaPlacementObservation
+ apps map[AppRef]int
+}
+
+func replicaStamp(rec provision.Record, v fleetView) string {
+ raw, _ := json.Marshal(rec)
+ return v.RecordETags[replicaRecordKey(rec)] + string(raw)
+}
+
+// P17: only inventory changes, dirty count edits or a possible membership
+// change need publication evidence. This check performs no store read.
+func replicaMayChange(rec provision.Record, v fleetView, old replicaPlacementObservation) bool {
+ if old.stamp == "" || old.stamp != replicaStamp(rec, v) {
+ return true
+ }
+ a := rec.ReplicaAssignment
+ if a == nil {
+ return false
+ }
+ if provision.ReplicaSwapActive(&rec) {
+ return replicaMemberLost(rec, v)
+ }
+ if a.Desired != old.desired {
+ return true
+ }
+ if old.desired == 1 && len(a.Boxes) == 1 && len(a.Retiring) == 0 {
+ c := rec.Coordinator
+ return c == nil || c.Box == a.Boxes[0] || !time.Now().Before(c.ExpiresAt)
+ }
+ candidates, err := replicaCandidates(rec, v, old.desired, old.size)
if err != nil {
- return err
+ return true
+ }
+ eligible := map[string]bool{}
+ spare := false
+ for _, c := range candidates {
+ eligible[c.Label] = c.Eligible
+ spare = spare || (c.Eligible && !a.Contains(c.Label) && !slices.Contains(a.Retiring, c.Label))
}
- for _, box := range next.Boxes {
- if err := reg.MarkFleetBoxLabelled(fleet, box, time.Now().UnixNano()); err != nil {
- return err
+ for _, box := range a.Boxes {
+ if !eligible[box] {
+ return true
}
}
- _, 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
+ return len(a.Boxes) < old.desired && spare
+}
+
+func replicaLoad(v fleetView, rec provision.Record, delta int) {
+ if rec.ReplicaAssignment != nil {
+ for _, box := range rec.ReplicaAssignment.Boxes {
+ v.Load[box] += delta
+ }
+ } else if rec.FleetBox != "" {
+ v.Load[rec.FleetBox] += delta
+ }
}
-// 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.
+// The fleet lock protects the observation cache. Each app holds its own
+// nonblocking publication locks; a busy or broken app never blocks its peers.
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
}
+ value, _ := s.replicaPlacements.LoadOrStore(fleet, &replicaPlacementCache{records: map[string]replicaPlacementObservation{}, apps: map[AppRef]int{}})
+ cache := value.(*replicaPlacementCache)
apps := make([]AppRef, 0, len(v.ReplicaApps))
for a := range v.ReplicaApps {
apps = append(apps, a)
@@ -215,147 +344,184 @@ func (s *Server) reconcileReplicaFleet(ctx context.Context, fleet string, v flee
}
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{}
+ var errs []error
+ changed := false
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)
+ moved, err := s.reconcileReplicaApp(ctx, fleet, a, v, cache, now)
+ changed = changed || moved
if err != nil {
- return err
+ errs = append(errs, fmt.Errorf("%s/%s: %w", a.Sqid, a.App, 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
+ }
+ if changed {
+ s.bumpSerial(ctx)
+ }
+ // A removed record must be treated as new if it appears again.
+ present := map[string]bool{}
+ for _, rec := range v.Records {
+ present[replicaRecordKey(rec)] = true
+ }
+ for key := range cache.records {
+ if !present[key] {
+ delete(cache.records, key)
}
- 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) || (rec.ReplicaAssignment == nil && v.ReplicaCounts[AppRef{Sqid: rec.Account, App: rec.App}] <= 1) {
+ return errors.Join(errs...)
+}
+
+func (s *Server) reconcileReplicaApp(ctx context.Context, fleet string, app AppRef, v fleetView, cache *replicaPlacementCache, now time.Time) (bool, error) {
+ unlock, ok := s.appLocks.tryLock(app.Sqid + "/" + app.App)
+ if !ok {
+ return false, nil
+ }
+ defer unlock()
+ acct, err := s.store.AccountBySqid(app.Sqid)
+ if err != nil {
+ return false, err
+ }
+ if acct == nil {
+ return false, replicas.ErrFenced
+ }
+ nameLock := s.store.AppPolicyLock(acct.ID, app.App)
+ if !nameLock.TryLock() {
+ return false, nil
+ }
+ defer nameLock.Unlock()
+ reg, err := s.openPassRegistry()
+ if err != nil {
+ return false, err
+ }
+ placed, err := s.store.AppPlacement(acct.ID, app.App)
+ if err != nil {
+ return false, err
+ }
+ own, err := ownsFleet(reg, acct, registry.PlacementTarget(fleet))
+ if err != nil {
+ return false, err
+ }
+ if !own || placed != registry.PlacementTarget(fleet) {
+ return false, replicas.ErrFenced
+ }
+ indices := []int{}
+ needs := map[int]bool{}
+ dirty := v.ReplicaDirty[app]
+ mayWrite := dirty || cache.apps[app] == 0
+ for i, rec := range v.Records {
+ if rec.Account != app.Sqid || rec.App != app.App {
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
- }
+ indices = append(indices, i)
+ needs[i] = dirty || replicaMayChange(rec, v, cache.records[replicaRecordKey(rec)])
+ mayWrite = mayWrite || needs[i]
+ }
+ if !mayWrite {
+ return false, nil
+ }
+ sort.Slice(indices, func(i, j int) bool {
+ return replicaRecordKey(v.Records[indices[i]]) < replicaRecordKey(v.Records[indices[j]])
+ })
+ cfg, err := s.copiesDefault(ctx, app.Sqid, app.App)
+ if err != nil {
+ return false, err
+ }
+ n := appconfig.CopiesOf(&cfg.manifest)
+ if n < 1 {
+ return false, replicas.ErrInvalid
+ }
+ assigned := false
+ for _, i := range indices {
+ assigned = assigned || v.Records[i].ReplicaAssignment != nil
+ }
+ if n == 1 && !assigned {
+ delete(v.ReplicaApps, app)
+ cache.apps[app] = n
+ return false, s.store.settleReplicaApp(ctx, acct.ID, app.App, false)
+ }
+ if !s.replicaViewReady(v, n) {
+ return false, nil
+ }
+ policy, _, err := apppolicy.Get(ctx, s.cfg.Releases, s.cfg.ReleasePub, app.Sqid, app.App, now)
+ if err != nil && !errors.Is(err, os.ErrNotExist) {
+ return false, err
}
var errs []error
changed := false
- for _, rec := range records {
- if !v.replicaRecord(rec) || (rec.ReplicaAssignment == nil && v.ReplicaCounts[AppRef{Sqid: rec.Account, App: rec.App}] <= 1) {
+ for _, i := range indices {
+ rec := v.Records[i]
+ if !needs[i] || (n == 1 && rec.ReplicaAssignment == nil) {
continue
}
- n := v.ReplicaCounts[AppRef{Sqid: rec.Account, App: rec.App}]
- next, err := s.replicaNext(rec, v, n)
+ key := replicaRecordKey(rec)
+ m, err := s.replicaSelected(ctx, rec)
if err != nil {
- return err
- }
- if err = s.placeReplicaRecord(ctx, rec, v, n); err != nil {
- errs = append(errs, err)
+ delete(cache.records, key)
+ errs = append(errs, fmt.Errorf("%s: %w", rec.Host, err))
continue
}
- old := rec.ReplicaAssignment
- if old != nil {
- for _, box := range old.Boxes {
- v.Load[box]--
+ v.ReplicaManifests[key] = m
+ if policy != nil {
+ v.ReplicaSizes[key] = policy.SizeFor(rec.Host, rec.CreatedAt)
+ }
+ action, err := s.replicaAction(rec, v, n)
+ if err == nil {
+ var result *provision.Record
+ result, err = s.applyReplicaAction(ctx, rec, v, action)
+ if err == nil {
+ if action.kind == replicaSet || action.kind == replicaClear {
+ replicaLoad(v, rec, -1)
+ replicaLoad(v, *result, 1)
+ }
+ v.Records[i] = *result
+ changed = changed || action.kind != replicaNone
}
- } else if rec.FleetBox != "" {
- v.Load[rec.FleetBox]--
}
- for _, box := range next.Boxes {
- v.Load[box]++
+ if err != nil {
+ delete(cache.records, key)
+ errs = append(errs, fmt.Errorf("%s: %w", rec.Host, err))
+ continue
+ }
+ if action.kind == replicaNone {
+ cache.records[key] = replicaPlacementObservation{replicaStamp(rec, v), v.ReplicaSizes[key], n}
+ } else {
+ delete(cache.records, key)
}
- changed = changed || (n == 1 && old != nil && old.Desired == 1 && len(old.Boxes) == 1 && len(old.Retiring) == 0 && !provision.ReplicaSwapActive(&rec)) || old == nil || old.Desired != next.Desired || !slices.Equal(old.Boxes, next.Boxes) || !slices.Equal(old.Retiring, next.Retiring)
}
- if changed {
- s.bumpSerial(ctx)
+ if len(errs) == 0 {
+ assigned = false
+ for _, i := range indices {
+ assigned = assigned || v.Records[i].ReplicaAssignment != nil
+ }
+ if err := s.store.settleReplicaApp(ctx, acct.ID, app.App, n > 1 || assigned); err != nil {
+ return changed, err
+ }
+ cache.apps[app] = n
+ if n == 1 && !assigned {
+ delete(v.ReplicaApps, app)
+ }
}
- return errors.Join(errs...)
+ return changed, errors.Join(errs...)
+}
+
+func (s *Server) replicaSelected(ctx context.Context, rec provision.Record) (*release.Manifest, error) {
+ return 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)
+ })
+ })
}
// SR-2-C10, approved copy. Availability counts distinct eligible survivors,
diff --git a/internal/console/replicaplacement_fix_test.go b/internal/console/replicaplacement_fix_test.go
new file mode 100644
index 000000000..41790a704
--- /dev/null
+++ b/internal/console/replicaplacement_fix_test.go
@@ -0,0 +1,303 @@
+package console
+
+import (
+ "context"
+ "reflect"
+ "slices"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/appconfig"
+ "github.com/carlosframework/platform/internal/provision"
+ "github.com/carlosframework/platform/internal/release"
+ "github.com/carlosframework/platform/internal/replicas"
+)
+
+func TestReplicaEvidenceFailureDoesNotBlockLegacy(t *testing.T) {
+ for _, kind := range []string{"config", "policy", "channel", "manifest", "authorization", "unmovable"} {
+ for _, operation := range []string{"loss", "drain"} {
+ t.Run(kind+"/"+operation, func(t *testing.T) {
+ fx, _, _ := replicaPlacementWorld(t)
+ relabelPass(t, fx)
+ placeBlog(t, fx)
+ putFleetRecord(t, fx, "blog", "legacy.example.com", func(rec *provision.Record) { rec.FleetBox = "pi-2" })
+ fail := &replicaFailRead{countStore: newCountStore(fx.rel)}
+ switch kind {
+ case "config":
+ fail.get = appconfig.Key(fx.sqid, "shop")
+ case "policy":
+ fail.get = "control/app-policy/" + fx.sqid + "/shop.json"
+ case "channel":
+ placementEdit(t, fx, "a.example.com", func(rec *provision.Record) { rec.Channel = "missing" })
+ case "manifest":
+ fail.get = release.ManifestKey(fx.sqid, "shop", "v1")
+ case "authorization":
+ fail.get = release.PromotionRecordKey(fx.sqid, "shop", "v1")
+ case "unmovable":
+ placementEdit(t, fx, "a.example.com", func(rec *provision.Record) { rec.Unit = "external.service" })
+ }
+ fx.srv.cfg.Releases = fail
+ if operation == "loss" {
+ copiesBeat(t, fx, "pi-2", release.StatelessReplicasFloor, time.Now().Add(-time.Hour))
+ relabelPass(t, fx)
+ } else {
+ stuck, err := fx.srv.drainBox(context.Background(), "pi", "pi-2")
+ if err != nil || len(stuck) != 0 {
+ t.Fatalf("legacy drain: %v %v", stuck, err)
+ }
+ }
+ legacy, err := provision.GetRecord(context.Background(), fx.rel, fx.sqid, "blog", "legacy.example.com")
+ if err != nil || legacy.FleetBox != "pi-1" {
+ t.Fatalf("legacy blocked: %+v %v", legacy, err)
+ }
+ a := shopRec(t, fx, "a.example.com")
+ if !a.ReplicaAssignment.Contains("pi-2") {
+ t.Fatal("failed replica evidence allowed a write")
+ }
+ if kind == "channel" || kind == "manifest" || kind == "authorization" || kind == "unmovable" {
+ b := shopRec(t, fx, "b.example.com")
+ if b.ReplicaAssignment.Contains("pi-2") {
+ t.Fatal("one record's failure blocked its healthy sibling")
+ }
+ }
+ relabelPass(t, fx)
+ legacy, _ = provision.GetRecord(context.Background(), fx.rel, fx.sqid, "blog", "legacy.example.com")
+ if legacy.FleetBox != "pi-1" {
+ t.Fatal("persistent replica failure reverted legacy placement")
+ }
+ })
+ }
+ }
+}
+
+func TestReplicaLegacyRelabelSurvivesEarlyReturn(t *testing.T) {
+ for _, reason := range []string{"busy", "incomplete", "floor"} {
+ t.Run(reason, func(t *testing.T) {
+ fx, _, _ := replicaPlacementWorld(t)
+ placeBlog(t, fx)
+ putFleetRecord(t, fx, "blog", "legacy.example.com", func(rec *provision.Record) { rec.FleetBox = "pi-2" })
+ // A stale marker on a legacy record must never hide it from relabel.
+ if err := fx.st.markReplicaApp(context.Background(), OpsAccountID, "blog", true); err != nil {
+ t.Fatal(err)
+ }
+ copiesBeat(t, fx, "pi-2", release.StatelessReplicasFloor, time.Now().Add(-time.Hour))
+ v, err := fx.srv.loadFleetView(context.Background(), "pi")
+ if err != nil {
+ t.Fatal(err)
+ }
+ switch reason {
+ case "busy":
+ unlock := fx.srv.lockApp(fx.sqid, "blog")
+ defer unlock()
+ case "incomplete":
+ v.Complete = false
+ case "floor":
+ fx.srv.consoleBuild = release.StatelessRuntimeFloor
+ }
+ unlock := fx.srv.lockFleet("pi")
+ defer unlock()
+ if err := fx.srv.reconcileReplicaFleet(context.Background(), "pi", v, time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := fx.srv.relabelFleet(context.Background(), "pi", v, time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ rec, err := provision.GetRecord(context.Background(), fx.rel, fx.sqid, "blog", "legacy.example.com")
+ if err != nil || rec.FleetBox != "pi-1" {
+ t.Fatalf("%s hid legacy: %+v %v", reason, rec, err)
+ }
+ })
+ }
+}
+
+func TestReplicaLegacyDrainAndDiscoveryAfterDecrease(t *testing.T) {
+ fx, token, _ := replicaPlacementWorld(t)
+ relabelPass(t, fx)
+ if code, out := copiesPut(t, fx, token, `{"copies":1}`); code != 200 {
+ t.Fatalf("%d %s", code, out)
+ }
+ relabelPass(t, fx)
+ for _, host := range []string{"a.example.com", "b.example.com"} {
+ rec := shopRec(t, fx, host)
+ inc, _ := provision.Incarnation(rec.Account, rec.App, rec.Host, rec.CreatedAt)
+ if _, err := provision.RecordReplicaRetired(context.Background(), fx.rel, replicas.Identity{Account: rec.Account, App: rec.App, Host: rec.Host, Incarnation: inc}, rec.ReplicaAssignment.Revision, "pi-2"); err != nil {
+ t.Fatal(err)
+ }
+ }
+ relabelPass(t, fx)
+ var configured, dirty bool
+ if err := fx.st.db.QueryRow(`SELECT copies_configured,copies_dirty FROM apps WHERE account_id=? AND app='shop'`, OpsAccountID).Scan(&configured, &dirty); err != nil {
+ t.Fatal(err)
+ }
+ if configured || dirty {
+ t.Fatal("explicit one left a discovery/dirty marker")
+ }
+ for _, host := range []string{"a.example.com", "b.example.com"} {
+ if shopRec(t, fx, host).ReplicaAssignment != nil {
+ t.Fatal("set not converted")
+ }
+ }
+ cs := newCountStore(fx.rel)
+ fx.srv.cfg.Releases = cs
+ for i := 0; i < 2; i++ {
+ relabelPass(t, fx)
+ }
+ for key := range cs.gets {
+ if strings.Contains(key, "config.json") {
+ t.Fatal("legacy app kept polling config", cs.gets)
+ }
+ }
+ // Inject the stale SQL state too: classification must depend on the record.
+ if err := fx.st.markReplicaApp(context.Background(), OpsAccountID, "shop", true); err != nil {
+ t.Fatal(err)
+ }
+ stuck, err := fx.srv.drainBox(context.Background(), "pi", "pi-1")
+ if err != nil || !slices.Equal(stuck, []string{"shop"}) {
+ t.Fatalf("stranded app was hidden: %v %v", stuck, err)
+ }
+}
+
+func TestReplicaHaltDoesNotProjectUnwrittenLoad(t *testing.T) {
+ fx, _, reg := replicaPlacementWorld(t)
+ relabelPass(t, fx)
+ registerFleetBox(t, reg, "pi", "pi-3")
+ copiesBeat(t, fx, "pi-3", release.StatelessReplicasFloor, time.Now())
+ placementEdit(t, fx, "a.example.com", func(rec *provision.Record) {
+ inc, _ := provision.Incarnation(rec.Account, rec.App, rec.Host, rec.CreatedAt)
+ rec.ReplicaDeploy = &replicas.Deploy{ID: "swap", Phase: "swapping", ActiveBox: "pi-2", Incarnation: inc, Revision: 1}
+ })
+ copiesBeat(t, fx, "pi-2", release.StatelessReplicasFloor, time.Now().Add(-time.Hour))
+ v, err := fx.srv.loadFleetView(context.Background(), "pi")
+ if err != nil {
+ t.Fatal(err)
+ }
+ unlock := fx.srv.lockFleet("pi")
+ defer unlock()
+ if err := fx.srv.reconcileReplicaFleet(context.Background(), "pi", v, time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ actual := map[string]int{"pi-1": 0, "pi-2": 0, "pi-3": 0}
+ for _, host := range []string{"a.example.com", "b.example.com"} {
+ for _, box := range shopRec(t, fx, host).ReplicaAssignment.Boxes {
+ actual[box]++
+ }
+ }
+ if !reflect.DeepEqual(actual, v.Load) {
+ t.Fatalf("halt charged an unwritten assignment: %v actual %v", v.Load, actual)
+ }
+ if shopRec(t, fx, "a.example.com").ReplicaDeploy.Phase != "unknown" {
+ t.Fatal("loss did not halt")
+ }
+}
+
+func TestReplicaLegacyActiveSwapDoesNotCreateSet(t *testing.T) {
+ fx, _, _ := replicaPlacementWorld(t)
+ placementEdit(t, fx, "a.example.com", func(rec *provision.Record) {
+ inc, _ := provision.Incarnation(rec.Account, rec.App, rec.Host, rec.CreatedAt)
+ rec.ReplicaDeploy = &replicas.Deploy{ID: "swap", Phase: "swapping", ActiveBox: "pi-1", Incarnation: inc, Revision: 1}
+ })
+ relabelPass(t, fx)
+ if rec := shopRec(t, fx, "a.example.com"); rec.ReplicaAssignment != nil || rec.ReplicaDeploy.Phase != "swapping" {
+ t.Fatalf("legacy swap changed: %+v", rec)
+ }
+}
+
+func TestReplicaLegacyUnitMovability(t *testing.T) {
+ for _, rec := range []provision.Record{{Unit: "example.service"}, {Unit: "example.service", Runtime: provision.RuntimeRootfsV1}} {
+ if !movable(rec) {
+ t.Fatal("legacy unit behaviour changed")
+ }
+ rec.ReplicaAssignment = &replicas.Assignment{Desired: 2, Boxes: []string{"a", "b"}}
+ if movable(rec) {
+ t.Fatal("replica unit accepted")
+ }
+ }
+}
+
+func TestReplicaDetachPageKeepsConfirmation(t *testing.T) {
+ fx, _, _ := replicaPlacementWorld(t)
+ relabelPass(t, fx)
+ page := detachPage(t, fx, "pi-2", true)
+ for _, text := range []string{"Detached pi/pi-2.", "detaching pi-2 leaves 1 of 2 copies available. the requested count stays 2"} {
+ if !strings.Contains(page, text) {
+ t.Fatalf("missing %q: %s", text, page)
+ }
+ }
+}
+
+func TestReplicaEvidenceFailureIsScopedToApp(t *testing.T) {
+ fx, _, _ := replicaPlacementWorld(t)
+ placeBlog(t, fx)
+ putFleetRecord(t, fx, "blog", "other.example.com", func(rec *provision.Record) { rec.Hibernate = new(bool); rec.FleetBox = "pi-1" })
+ shipStatelessFloorRelease(t, fx, "blog", "v1")
+ if err := release.Promote(context.Background(), fx.rel, fx.priv, fx.sqid, "blog", "edge", "v1"); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := appconfig.SetCopies(context.Background(), fx.rel, fx.sqid, "blog", 2); err != nil {
+ t.Fatal(err)
+ }
+ if err := fx.st.markReplicaApp(context.Background(), OpsAccountID, "blog", true); err != nil {
+ t.Fatal(err)
+ }
+ fx.srv.cfg.Releases = &replicaFailRead{countStore: newCountStore(fx.rel), get: appconfig.Key(fx.sqid, "shop")}
+ relabelPass(t, fx)
+ rec, err := provision.GetRecord(context.Background(), fx.rel, fx.sqid, "blog", "other.example.com")
+ if err != nil || rec.ReplicaAssignment == nil || len(rec.ReplicaAssignment.Boxes) != 2 {
+ t.Fatalf("healthy app blocked: %+v %v", rec, err)
+ }
+ if shopRec(t, fx, "a.example.com").ReplicaAssignment != nil {
+ t.Fatal("failed app wrote")
+ }
+}
+
+func TestReplicaEvidenceRefreshesChangedInventory(t *testing.T) {
+ fx, _, _ := replicaPlacementWorld(t)
+ relabelPass(t, fx)
+ relabelPass(t, fx)
+ old := shopRec(t, fx, "a.example.com")
+ placementEdit(t, fx, old.Host, func(rec *provision.Record) { rec.Channel = "stable" })
+ if shopRec(t, fx, old.Host).RecordSeq != old.RecordSeq {
+ t.Fatal("fixture should change ETag without sequence")
+ }
+ cs := newCountStore(fx.rel)
+ fx.srv.cfg.Releases = cs
+ relabelPass(t, fx)
+ for _, key := range []string{appconfig.Key(fx.sqid, "shop"), "control/app-policy/" + fx.sqid + "/shop.json", release.ChannelKey(fx.sqid, "shop", "stable"), release.ManifestKey(fx.sqid, "shop", "v2"), release.PromotionRecordKey(fx.sqid, "shop", "v2")} {
+ if cs.gets[key] != 1 {
+ t.Fatalf("changed record did not re-read evidence %s: %v", key, cs.gets)
+ }
+ }
+ if cs.gets[release.ChannelKey(fx.sqid, "shop", "edge")] != 0 || cs.recordPuts() != 0 {
+ t.Fatalf("unchanged sibling re-read or record rewritten: %v %v", cs.gets, cs.puts)
+ }
+ cs.reset()
+ relabelPass(t, fx)
+ if cs.gets[appconfig.Key(fx.sqid, "shop")] != 0 {
+ t.Fatalf("steady pass re-read evidence: %v", cs.gets)
+ }
+}
+
+func TestReplicaDirtyCountSurvivesRestart(t *testing.T) {
+ fx, token, _ := replicaPlacementWorld(t)
+ relabelPass(t, fx)
+ relabelPass(t, fx)
+ if code, out := copiesPut(t, fx, token, `{"copies":1}`); code != 200 {
+ t.Fatalf("%d %s", code, out)
+ }
+ var dirty bool
+ if err := fx.st.db.QueryRow(`SELECT copies_dirty FROM apps WHERE account_id=? AND app='shop'`, OpsAccountID).Scan(&dirty); err != nil || !dirty {
+ t.Fatalf("count edit was not durably marked: %v %v", dirty, err)
+ }
+ fx.srv.replicaPlacements.Delete("pi")
+ relabelPass(t, fx)
+ for _, host := range []string{"a.example.com", "b.example.com"} {
+ rec := shopRec(t, fx, host)
+ if rec.ReplicaAssignment.Desired != 1 || len(rec.ReplicaAssignment.Retiring) != 1 {
+ t.Fatalf("dirty count did not converge: %+v", rec.ReplicaAssignment)
+ }
+ }
+ if err := fx.st.db.QueryRow(`SELECT copies_dirty FROM apps WHERE account_id=? AND app='shop'`, OpsAccountID).Scan(&dirty); err != nil || dirty {
+ t.Fatalf("successful pass did not clear dirty: %v %v", dirty, err)
+ }
+}
diff --git a/internal/console/replicaplacement_test.go b/internal/console/replicaplacement_test.go
index 47fa9a0d8..c67c99a20 100644
--- a/internal/console/replicaplacement_test.go
+++ b/internal/console/replicaplacement_test.go
@@ -351,14 +351,14 @@ func TestReplicaPlacementRetriesAndSerializes(t *testing.T) {
}
func TestReplicaPlacementReadAccounting(t *testing.T) {
- fx, _, _ := replicaPlacementWorld(t)
+ fx, token, _ := 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)
+ if code, out := copiesPut(t, fx, token, `{"copies":1}`); code != 200 {
+ t.Fatalf("%d %s", code, out)
}
}
cs.reset()
@@ -375,6 +375,9 @@ func TestReplicaPlacementReadAccounting(t *testing.T) {
"fleets/pi/status/boxes/pi-1.json": 1,
"fleets/pi/status/boxes/pi-2.json": 1,
}
+ if pass == 2 {
+ wantGets = map[string]int{"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"} {
diff --git a/internal/console/server.go b/internal/console/server.go
index aeb4704cf..44123797b 100644
--- a/internal/console/server.go
+++ b/internal/console/server.go
@@ -994,8 +994,9 @@ type Server struct {
// fleetLocks holds one mutex per fleet name (lockFleet, fleetbox.go),
// and fleetInventories each fleet's record inventory cache
// (*fleetInventory), both made on first use.
- fleetLocks sync.Map
- fleetInventories sync.Map
+ fleetLocks sync.Map
+ fleetInventories sync.Map
+ replicaPlacements sync.Map
// detachBeforeLock, when set, runs in both detach doors just before
// they take the fleet's lock (tests only: an interleaving seam).
detachBeforeLock func(fleet, label string)
diff --git a/internal/console/store.go b/internal/console/store.go
index 2a5f3b07c..574ec69d2 100644
--- a/internal/console/store.go
+++ b/internal/console/store.go
@@ -592,6 +592,7 @@ func (s *Store) migrate() error {
// 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;`,
+ `ALTER TABLE apps ADD COLUMN copies_dirty 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.
@@ -772,6 +773,7 @@ func (s *Store) migrateAppsKey() error {
region_source TEXT NOT NULL DEFAULT '',
region_set_at INTEGER NOT NULL DEFAULT 0,
copies_configured INTEGER NOT NULL DEFAULT 0,
+ copies_dirty 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,
@@ -790,8 +792,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, 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,
+ `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, copies_dirty, 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, copies_dirty, 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;`,
diff --git a/internal/host/fleetbind.go b/internal/host/fleetbind.go
index 254eb104e..d8fcdfcc9 100644
--- a/internal/host/fleetbind.go
+++ b/internal/host/fleetbind.go
@@ -271,6 +271,7 @@ func ReconcileFleetBindings(ctx context.Context, s release.Store, reg *registry.
if err != nil {
return err
}
+ var rejected []error
for _, dir := range fleetDirs {
keys, err := s.List(ctx, dir+"bindings/")
if err != nil {
@@ -289,6 +290,9 @@ func ReconcileFleetBindings(ctx context.Context, s release.Store, reg *registry.
continue
}
if key != fleetBindingKey(b.Fleet, b.Host) {
+ if b.Incarnation != "" || b.Boxes != nil || b.AssignmentRevision != 0 {
+ rejected = append(rejected, replicas.ErrFenced)
+ }
log.Printf("host: fleet bindings: skipping %s: body names fleet %q host %q, not its key", key, b.Fleet, b.Host)
continue
}
@@ -300,6 +304,18 @@ func ReconcileFleetBindings(ctx context.Context, s release.Store, reg *registry.
if rt == nil {
continue // no matching route on this platform box
}
+ if rt.FleetBoxes != "" || b.Incarnation != "" || b.Boxes != nil || b.AssignmentRevision != 0 {
+ // A legacy stamp carries no set evidence. A set stamp is
+ // accepted only if it corroborates the current projection.
+ // Report rejection after processing the other bindings.
+ if b.Incarnation == "" && b.Boxes == nil && b.AssignmentRevision == 0 {
+ continue
+ }
+ if !validReplicaFleetBinding(reg, *rt, b) {
+ rejected = append(rejected, replicas.ErrFenced)
+ }
+ continue
+ }
// Never stamp a sidecar. SetFleetBoxIf on a fleet-placed route is
// precisely what turns the edge's fleet dispatch arm into a live
// proxy, so this reader is the last gate on the chain and it
@@ -321,14 +337,7 @@ func ReconcileFleetBindings(ctx context.Context, s release.Store, reg *registry.
// comment above).
continue
}
- if rt.FleetBoxes != "" || b.Incarnation != "" || b.Boxes != nil || b.AssignmentRevision != 0 {
- // Assignment projection is already authoritative; a binding cannot
- // replace it or make a stale set current.
- if !validReplicaFleetBinding(reg, *rt, b) {
- continue
- }
- continue
- }
+
if rt.FleetBox == b.Box {
continue
}
@@ -345,7 +354,7 @@ func ReconcileFleetBindings(ctx context.Context, s release.Store, reg *registry.
}
}
}
- return nil
+ return errors.Join(rejected...)
}
// fleetBindingHook builds the activator's OnWake hook for a fleet box: on
diff --git a/internal/host/replica_request_budget_test.go b/internal/host/replica_request_budget_test.go
index 6ef09ee56..7bf85726f 100644
--- a/internal/host/replica_request_budget_test.go
+++ b/internal/host/replica_request_budget_test.go
@@ -5,6 +5,8 @@ import (
"encoding/json"
"errors"
"github.com/carlosframework/platform/internal/domains"
+ "net/http"
+ "net/http/httptest"
"reflect"
"slices"
"strings"
@@ -199,23 +201,18 @@ func TestReplicaHubBindingReader(t *testing.T) {
}
rt = *saved
valid := FleetBinding{Host: rt.Host, Fleet: "pi", Boxes: []string{"a", "b"}, Incarnation: "life", AssignmentRevision: 4}
- if !validReplicaFleetBinding(reg, rt, valid) {
- t.Fatal("current set refused")
- }
- for _, mut := range []func(*FleetBinding){func(b *FleetBinding) { b.Incarnation = "old" }, func(b *FleetBinding) { b.AssignmentRevision-- }, func(b *FleetBinding) { b.Fleet = "other" }, func(b *FleetBinding) { b.Boxes = []string{"a"} }, func(b *FleetBinding) { b.Box = "a" }} {
- b := valid
- mut(&b)
- if validReplicaFleetBinding(reg, rt, b) {
- t.Fatalf("invalid binding accepted %+v", b)
- }
- }
- for _, b := range []FleetBinding{{Host: rt.Host, Fleet: "pi", Box: "a"}, valid} {
+ check := func(key string, b FleetBinding, wantErr bool) {
+ t.Helper()
raw, _ := json.Marshal(b)
- _, tag, _ := store.Get(ctx, fleetBindingKey("pi", rt.Host))
- if _, err := store.Put(ctx, fleetBindingKey("pi", rt.Host), raw, tag); err != nil {
+ _, tag, _ := store.Get(ctx, key)
+ if _, err := store.Put(ctx, key, raw, tag); err != nil {
t.Fatal(err)
}
- if err := ReconcileFleetBindings(ctx, store, reg); err != nil {
+ err := ReconcileFleetBindings(ctx, store, reg)
+ if errors.Is(err, replicas.ErrFenced) != wantErr {
+ t.Fatalf("binding %+v accepted=%v error=%v", b, !wantErr, err)
+ }
+ if err := store.Delete(ctx, key); err != nil {
t.Fatal(err)
}
got, _ := reg.Get(rt.Host)
@@ -223,12 +220,26 @@ func TestReplicaHubBindingReader(t *testing.T) {
t.Fatal("binding changed declarative assignment")
}
}
+ check(fleetBindingKey("pi", rt.Host), valid, false)
+ for _, mut := range []func(*FleetBinding){func(b *FleetBinding) { b.Incarnation = "old" }, func(b *FleetBinding) { b.AssignmentRevision-- }, func(b *FleetBinding) { b.Fleet = "other" }, func(b *FleetBinding) { b.Boxes = []string{"a"} }, func(b *FleetBinding) { b.Box = "a" }} {
+ b := valid
+ mut(&b)
+ check(fleetBindingKey("pi", rt.Host), b, true)
+ }
+ check(fleetBindingKey("pi", rt.Host), FleetBinding{Host: rt.Host, Fleet: "pi", Box: "a"}, false)
+ check(fleetBindingKey("other", rt.Host), valid, true)
+
if err := reg.SetFleetBoxStatus("pi", "b", "detached"); err != nil {
t.Fatal(err)
}
- if validReplicaFleetBinding(reg, rt, valid) {
- t.Fatal("detached member accepted")
+ check(fleetBindingKey("pi", rt.Host), valid, true)
+ if err := reg.SetFleetBoxStatus("pi", "b", "active"); err != nil {
+ t.Fatal(err)
}
+ if err := reg.UpsertFleet(registry.Fleet{Name: "pi", Account: "bac"}); err != nil {
+ t.Fatal(err)
+ }
+ check(fleetBindingKey("pi", rt.Host), valid, true)
}
func replicaReconcileBudget(t *testing.T) {
@@ -283,3 +294,51 @@ func replicaReconcileBudget(t *testing.T) {
}
}
}
+
+func TestReplicaBlockedACKDoesNotBlockReconcile(t *testing.T) {
+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+ defer cancel()
+ entered, releasePost := make(chan struct{}), make(chan struct{})
+ ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ close(entered)
+ select {
+ case <-releasePost:
+ case <-ctx.Done():
+ case <-r.Context().Done():
+ }
+ _, _ = w.Write([]byte(`{}`))
+ }))
+ defer ts.Close()
+ defer close(releasePost)
+ reg := testRegistry(t)
+ api := &replicaCoordinatorAPI{base: ts.URL, fleet: "pi", box: "a", token: "test-token", client: ts.Client()}
+ worker := &replicaPlacementWorker{reg: reg, box: "a", quiet: func(string) bool { return true }, empty: func(registry.Route) error { return nil }, retired: api.retired}
+ worker.observe(provision.Record{Account: "bab", App: "shop", Host: "shop.example.com", Region: "fleet/pi", CreatedAt: time.Unix(1, 0), ReplicaAssignment: &replicas.Assignment{Revision: 1, Desired: 1, Boxes: []string{"b"}, Retiring: []string{"a"}}})
+ done := make(chan struct{}, 1)
+ go func() { worker.run(ctx, time.Now()); done <- struct{}{} }()
+ defer func() {
+ cancel()
+ select {
+ case <-done:
+ case <-time.After(5 * time.Second):
+ t.Error("ACK worker did not stop")
+ }
+ }()
+ select {
+ case <-entered:
+ case <-ctx.Done():
+ t.Fatal("ACK did not start")
+ }
+ reconciled := make(chan error, 1)
+ store := release.NewDirStore(t.TempDir())
+ cfg := provision.ReconcileConfig{Region: "fleet/pi", FleetBox: "a", DataDir: t.TempDir()}
+ go func() { reconciled <- reconcileSerializedAuth(ctx, store, reg, cfg, nil, newAssetAuthority(nil)) }()
+ select {
+ case err := <-reconciled:
+ if err != nil {
+ t.Fatal(err)
+ }
+ case <-ctx.Done():
+ t.Fatal("blocked ACK held reconcileMu")
+ }
+}
diff --git a/internal/host/replicaplacement.go b/internal/host/replicaplacement.go
index 1fdf45988..60ef1fd07 100644
--- a/internal/host/replicaplacement.go
+++ b/internal/host/replicaplacement.go
@@ -109,19 +109,21 @@ func (w *replicaPlacementWorker) run(ctx context.Context, now time.Time) {
// Serialize local removal/proof against reconcile minting a new lifetime.
reconcileMu.Lock()
rt, err := w.reg.Get(rec.Host)
+ proven := false
if err == nil && slices.Contains(a.Retiring, w.box) && rt == nil && w.quiet != nil && w.quiet(rec.Host) && w.empty != nil {
proof := provision.RouteFor(rec, w.dataDir, "", false, nil)
- if err = w.empty(proof); err == nil && w.retired != nil {
- err = w.retired(rctx, id, a.Revision)
- done = err == nil || errors.Is(err, replicas.ErrFenced)
- }
+ proven = w.empty(proof) == nil
+ }
+ reconcileMu.Unlock()
+ if proven && w.retired != nil {
+ err = w.retired(rctx, id, a.Revision)
+ done = err == nil || errors.Is(err, replicas.ErrFenced)
} else if err == nil && a.Contains(w.box) && rt != nil && rt.ReplicaIncarnation == inc && rt.ReplicaRevision == a.Revision && provision.ReplicaCoordinatorBox(&rec, now) == w.box && w.coordinator != nil {
if _, err = w.coordinator.Acquire(rctx, id); err == nil && w.publisher != nil {
// Acquire's new term reaches the publisher through the next record pass.
err = w.publisher.publish(rctx, rec, *rt)
}
}
- reconcileMu.Unlock()
cancel()
w.mu.Lock()
current := w.pending[rec.Host]
diff --git a/internal/provision/stateless_placement_census_test.go b/internal/provision/stateless_placement_census_test.go
index 32a54a847..1a103e1ef 100644
--- a/internal/provision/stateless_placement_census_test.go
+++ b/internal/provision/stateless_placement_census_test.go
@@ -5,6 +5,14 @@ package provision
func statelessPlacementWriteCensusInventory() []censusEntry {
entries := append([]censusEntry(nil), statelessReplicasWriteCensusInventory()...)
for _, next := range []censusEntry{
+ // Fix round 1 I1/I2/P17: nonblocking app/name locks and current fleet ownership isolate failures. Fresh count, policy and selection precede each typed action. Successful actions alone update load; dirty SQL clears only after success, discovery clears at count one without assignments. Independent approval pending.
+ {"internal/console/replicaplacement.go", "Server.reconcileReplicaApp", "key-site", "key:replicaRecordKey", "931aba66ff12c3c11df54c6993d85f506aaff1cc6fb9e4290a644d7b7e546262"},
+ // Fix round 1 P17: pure canonical record JSON plus the ETag already read by fleetInventory. No store read; a changed stamp requires fresh publication evidence. Independent approval pending.
+ {"internal/console/replicaplacement.go", "replicaStamp", "key-site", "key:replicaRecordKey", "2844f820cbf80a88474581a363120072f36e3cb626e739db95beb4b60d2b3b33"},
+ // Fix round 1 m2/m5: one none/set/clear/halt decision per record. Nil-assignment active swaps freeze safely. Halt retains current assignment; only set/clear can change load. No new store read. Independent approval pending.
+ {"internal/console/replicaplacement.go", "Server.replicaAction", "key-site", "key:replicaRecordKey", "79f003d35c73ceaa17d0cb0a61c3bbddaa2938721f3332d6bfc3ef875548383f"},
+ // Fix round 1 m5: sole typed-write dispatch for set, clear and halt. Caller holds fleet/app exclusion; current selected-manifest evidence and the existing lifetime/region/sequence/revision CAS remain required. None performs no write. Independent approval pending.
+ {"internal/console/replicaplacement.go", "Server.applyReplicaAction", "record-writer", "key:ClearRecordReplicaAssignment,key:HaltRecordReplicaDeploy,key:SetRecordReplicaAssignment,key:replicaRecordKey", "5e698ca9bd1edad6c0f927afdb20dd195a52c8414148f5520152a2ff600a515d"},
// Slice 3b, author inspection; independent approval pending: New typed P16 writer checks Expect CAS, current manifest evidence, desired one, exactly one member, no Retiring, no active swap and no other live authority; writes legacy FleetBox and clears assignment.
{"internal/provision/replicaassignment.go", "ClearRecordReplicaAssignment", "record-writer", "key:ClearRecordReplicaAssignment,key:updateRecord", "ef79b839935baeaf38eb2f0592658cdc27b4f0ab9cd7b737bc0e9b42b9fbf45e"},
// Slice 3b, author inspection; independent approval pending: New typed halt writer checks instance/assignment/deploy CAS and active swap, records unknown with incremented revision, retains ActiveBox, never grants a new permit.
@@ -30,16 +38,17 @@ func statelessPlacementWriteCensusInventory() []censusEntry {
// existing typed CAS. It receives selected canonical manifest evidence
// under app/fleet exclusion, and unchanged assignments are not written.
// Slice 3b, author inspection; independent approval pending: Calls typed assignment, halt or legacy-clear CAS under publication exclusion. Active swap loss halts first; one-member proof-complete records clear via P16.
- {"internal/console/replicaplacement.go", "Server.placeReplicaRecord", "record-writer", "key:ClearRecordReplicaAssignment,key:HaltRecordReplicaDeploy,key:SetRecordReplicaAssignment,key:replicaRecordKey", "26b413c66c2be0d4d6171cd114e4ea8eaa200bc3e26c317bbb3d5fc51639f7f8"},
// Complete cached fleet records, ownership, locked current count and
// authorized selections precede writes. P15 bounds additions by that
// count; all writes delegate to placeReplicaRecord. No direct record Put.
// Slice 3b, author inspection; independent approval pending: Skips legacy siblings at count one; serial includes P16 conversion. Existing cached inventory and current count under app locks.
- {"internal/console/replicaplacement.go", "Server.reconcileReplicaFleet", "key-site", "key:replicaRecordKey", "59dbabf8432bb031503eb8c0510d7cec475abc8670e5987379a70a2ad2ff062f"},
+ // Fix round 1 I1/P17: dispatches apps independently under the fleet lock, using cached inventory stamps only to skip unchanged work. Errors are joined after peers run. Serial bumps only for actual typed actions. No new record read. Independent approval pending.
+ {"internal/console/replicaplacement.go", "Server.reconcileReplicaFleet", "key-site", "key:replicaRecordKey", "d353e70ba01181173d64235ed2e5436844ccbaa89e837eee6d524c0e0e56372b"},
// Pure candidate calculation from the supplied view and authorized
// manifest. Preserves retirement obligations and selects distinct boxes.
// Slice 3b, author inspection; independent approval pending: Retains eligible coordinator, freezes membership during active swap, and identifies losses from the existing complete view. No store read.
- {"internal/console/replicaplacement.go", "Server.replicaNext", "key-site", "key:replicaRecordKey", "10b4530bece97840dfc74b37de4d69b62b5d1199cedbecd3b7923f0eaad10bac"},
+ // Fix round 1 m5: pure stable placement is evaluated once after evidence. Candidate eligibility shares the same read-free helper as the cache trigger; swap decisions belong to replicaAction. Independent approval pending.
+ {"internal/console/replicaplacement.go", "Server.replicaNext", "key-site", "key:replicaRecordKey", "4259edff6601a36b7842b69ef3fee86475e61edbd643a6e8eb459236aec9b040"},
// Pure key construction for the inventory record; no store read/write.
{"internal/console/replicaplacement.go", "replicaRecordKey", "key-site", "key:RecordKey,key:replicaRecordKey", "a98e902f0e2b91ce6b26bce277bde1b74cf42a1d36b60e26f241cbcc3dd85b0c"},
// Fix round 1, P10: unknown assignment members survive ordinary writes;
diff --git a/internal/provision/testdata/plan14-root-reads-chain.tsv b/internal/provision/testdata/plan14-root-reads-chain.tsv
index 25228ac6a..1f3470a2e 100644
--- a/internal/provision/testdata/plan14-root-reads-chain.tsv
+++ b/internal/provision/testdata/plan14-root-reads-chain.tsv
@@ -58,4 +58,4 @@ plan14-root-reads-rootfs-default-home.tsv 7a0a3da3d6fe7e3c77abb22676db000af2a276
plan14-root-reads-probe-burst-limit.tsv 5f805400717bad7726bd9d62744b8103a40eb5f5823b0ab7c960a5c0965cb3bc
plan14-root-reads-region-ha-p1b3a.tsv 5d20b3777026e43906bfba301186bce0ae58daa9d8ad5019879b7833f14dc6ff
plan14-root-reads-stateless-replicas-1.tsv df8bf8056d80b9d78edc957fe7f2adbc75885e15f581e58167768346c4e05771
-plan14-root-reads-stateless-replicas-2.tsv 1d704149c47d2cdb710aaf7dfc9a0aa4256cfbf69349afa23fa7f06997674879
+plan14-root-reads-stateless-replicas-2.tsv 125f7cbab86efcf81600ee0ae08c10d29acaa49e46f69422daa078d58dd85731
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 8eadeaf1d..5f64c4c98 100644
--- a/internal/provision/testdata/plan14-root-reads-stateless-replicas-2.tsv
+++ b/internal/provision/testdata/plan14-root-reads-stateless-replicas-2.tsv
@@ -10,7 +10,7 @@
@legacy c2884b0d5b53dc03c9be18f949be500c2cf8a6be869b99c6f63a8bcf6dda68a6 internal/activator/wakeidentity.go Service.CheckReplicaAssignment legacy accepted-legacy accepted-legacy;rev3=census-ruling-stateless-replicas-2;basis=Only set rows invoke existing registry/instance-record wake recheck. Legacy returns without reading; not a new polling loop. registry:FleetBoxes@93,whole:Route@169 43e922e015b61f736ed118ad44113802ca1944b676e9586388d6f9e00d691eba
@legacy 072ae1402ea5fdb49413a17fbc0de9cf8987b930a899d24c353f878a664edf2d internal/host/fleetbind.go validReplicaFleetBinding legacy accepted-legacy accepted-legacy;rev3=census-ruling-stateless-replicas-2;basis=Slice 3b: validates canonical boxes, host, fleet, lifetime and exact assignment revision against existing route; local registry fleet owner and active labels must match. No bucket call; no writer. registry:Account@643,registry:Account@657,registry:Copies@481,registry:FleetBoxes@132,registry:FleetBoxes@540,registry:Host@373,registry:Label@856,registry:Region@331,registry:ReplicaIncarnation@188,registry:ReplicaRevision@230,registry:Status@878,whole:FleetBox@842 2c20af701cc19717ba83d02c9361c3a34da18fe68e8fac862deaa9787b025ebb
@legacy 0209cc9c5299a0027e5a4334ddf745b648e911ef89850656f8d596cb621ef7e2 internal/host/fleetidentity.go recheckReplicaPickup legacy accepted-legacy accepted-legacy;rev3=census-ruling-stateless-replicas-2;basis=Only set rows require a launcher with the activator current-membership check; missing check refuses pickup. Reads supplied Route only. registry:FleetBoxes@98,whole:Route@322 7af336690a854d75b8a68b2f8031f8fb2cbd8441117e73c30610307d8f0dd7ca
-@legacy 3aadd15d52c7f7534b3a31b611d1e10399e1306b53e55b5fc0339a9f78009dd5 internal/host/replicaplacement.go replicaPlacementWorker.run legacy accepted-legacy accepted-legacy;rev3=census-ruling-stateless-replicas-2;basis=Slice 3b: existing tick processes already-read records with bounded exponential backoff. Reads local registry only. Under reconcile exclusion, absent row plus activator quiet plus both cgroup layouts empty precede authenticated retired API POST for exact lifetime/revision. Members only acquire for the deterministic chosen coordinator; others do no publication. API timeout/cancellation bounds shutdown; successful or fenced ACKs leave the queue, while transient failures retry with backoff. A new record observation can queue a new revision. No new bucket polling. registry:ReplicaIncarnation@1190,registry:ReplicaRevision@1222,whole:Route@1177,whole:Route@1539,whole:Route@830,whole:Route@982 de7cf90d73351ab66574136e24ff9614fce158d676b6351d4ef510dac46e419a
+@legacy 5e4fb943f3a2df9f21a84953f3601012eedd9b26243878caf32d61edba592f34 internal/host/replicaplacement.go replicaPlacementWorker.run legacy accepted-legacy accepted-legacy;rev3=census-ruling-stateless-replicas-2;basis=Slice 3b: existing tick processes already-read records with bounded exponential backoff. Reads local registry only. Under reconcile exclusion, absent row plus activator quiet plus both cgroup layouts empty precede authenticated retired API POST for exact lifetime/revision. Members only acquire for the deterministic chosen coordinator; others do no publication. API timeout/cancellation bounds shutdown; successful or fenced ACKs leave the queue, while transient failures retry with backoff. A new record observation can queue a new revision. No new bucket polling. Fix round 1 I3: reconcileMu protects only the registry observation and local quiet/cgroup proof. Unlock before retired POST, coordinator Acquire and binding publication. The ACK remains bound to the same lifetime/revision and the server CAS refuses intervening assignment changes. Existing local read sites unchanged; no new polling. registry:ReplicaIncarnation@1235,registry:ReplicaRevision@1267,whole:Route@1000,whole:Route@1222,whole:Route@1584,whole:Route@848 88bd40ca3d72c93b4973bf294ff1c32ed48d45049bef2964206e611bdcc264d1
@legacy 9ee0215e87836c375afd79bb0afd249425eaf6ae649f80003172ef145f960e79 internal/provision/forward.go forwardRowFor legacy accepted-legacy accepted-legacy;rev3=census-ruling-stateless-replicas-2;basis=Projects declarative set fields from supplied record; keeps socket, database, execution and all other forbidden fields zero. whole:Route@436,whole:Route@453 9ba6c562aa2b720af029d069b5855b8d1dc32ff76c742c90ad13604f8f19970d
@legacy 1c2e463b33d41c6d7eb010c2cf99c5d9d1e607065ebfa9bba0766476ccf0b31d internal/provision/replicaassignment.go projectReplicaAssignment legacy accepted-legacy accepted-legacy;rev3=census-ruling-stateless-replicas-2;basis=P12: pure projection marks a present assignment invalid before validation, so an invalid shape cannot silently become the legacy empty set. No store read or path authority. registry:Copies@465,registry:FleetBox@616,registry:FleetBoxes@254,registry:FleetBoxes@450,registry:FleetLabel@629,registry:ReplicaIncarnation@496,registry:ReplicaRevision@476,registry:Stateless@595 be1287470cf6b9cfbef39e9740c21b461d952b265098d72c9e32c37e6326e383
@legacy 9ddce30c4b6dd6b38b67adc32c93cbc530cf7daaea612100893877de65f63d0f internal/provision/replicaassignment.go replicaRowLifetimeAllowed legacy accepted-legacy accepted-legacy;rev3=census-ruling-stateless-replicas-2;basis=P11: pure comparison of the already-read record and local route. Requires same owner and managed instance kind; accepts unprojected legacy rows for membership, matching lifetimes, or a proven older monotonic counter. Newer/unknown ordering refuses. registry:Account@145,registry:App@174,registry:Canary@132,registry:FleetBoxes@387,registry:Host@195,registry:Incarnation@218,registry:Kind@92,registry:Platform@117,registry:Provisioned@74,registry:ReplicaIncarnation@410,registry:ReplicaIncarnation@442,whole:Route@495 03c64806b231b7af2844dc47eaeefc52549bbce0e6afd56ed3d103d87f2f42a0
@@ -31,7 +31,7 @@
@legacy be13da7e0d2a07dee196e48ef757c031984dca615586f773f1349e8ae6b41af8 internal/activator/startrule.go ExecBackend.startAllowed legacy accepted-legacy accepted-legacy;rev3=census-ruling-managed-fleets-1b;basis=new (Task 3, rule 6): the start rule: an unlabelled or restored start is allowed; a kept local copy must match rt.Assigned in its marker; an empty start of a labelled row is refused (ErrNothingToRestore) when a set-aside entry exists for the host or rt.Moved is set. Only refuses. Agent, not root.;rev3=census-ruling-stateless-replicas-2;basis=A set projection refuses this SQLite empty-start rule; does not turn a route hint into bypass authority. Legacy rule unchanged. registry:Assigned@211,registry:Assigned@668,registry:Assigned@820,registry:FleetBoxes@163,registry:Host@268,registry:Moved@1407,whole:Route@315 c0576b3af038f2a714e43ae6263d259110825f3ea18f5c9798214d7baf6958e4
@legacy 8a1cdcb513d1b84a59949d90b575f60448a6010d2ffb38381e6d82cf4b1bcbeb internal/activator/wakeidentity.go Service.currentWakeRoute legacy accepted-legacy accepted-legacy;rev3=census-ruling-stateless-replicas-1;basis=Extract existing registry and labelled fleet record recheck for reuse without a serving lease; return the observed row and record and refuse a nil record. No writer or new path.;rev3=census-ruling-stateless-replicas-2;basis=Existing registry/record recheck validates canonical set, membership, lifetime, revision, owner and managed stateless shape. Reuses the one wake record read; unknown fleet and malformed projection refuse. registry:Account@1846,registry:App@1871,registry:Assigned@2821,registry:Assigned@3031,registry:Assigned@510,registry:Channel@2015,registry:Copies@2407,registry:Environment@2077,registry:FleetBoxes@1523,registry:FleetBoxes@2357,registry:FleetBoxes@531,registry:FleetBoxes@641,registry:Host@1114,registry:Host@1243,registry:Host@1410,registry:Host@1893,registry:Host@281,registry:Host@2956,registry:Host@379,registry:Host@971,registry:Kind@1592,registry:Region@1918,registry:Region@1949,registry:ReplicaIncarnation@2323,registry:ReplicaRevision@2454,registry:Runtime@2044,whole:Route@1327,whole:Route@229,whole:Route@2751,whole:Route@3056,whole:Route@427,whole:Route@431,whole:Route@488,whole:Route@499,whole:Route@563,whole:Route@721 abf3135d80b76a02b2047a9bcedc85852d38625eab20f550848878485b4d2e16
@legacy 82e2db3ec3ff76eedea214649dba1a3ce0f2824d358cf46bf1bf0415534bf262 internal/activator/wakeidentity.go leaseRouteChanged legacy accepted-legacy accepted-legacy;rev3=census-ruling-managed-fleets-1b;basis=new (branch review R1 P1-1): a pure comparison of the row a wake began from (began) with the row doWake read under the lease (now): nil now is a row that is gone; then wakeRouteChanged's identity checks; then Assigned and Moved; then Region. It answers an error naming the change, wrapping errRouteChangedUnderLease, or nil. No read beyond its arguments. Agent, not root; it only refuses.;rev3=census-ruling-stateless-replicas-2;basis=Pure comparison adds set/count/revision/lifetime changes to existing wake fence; no new input source. registry:Assigned@559,registry:Assigned@577,registry:Assigned@771,registry:Assigned@796,registry:Copies@388,registry:Copies@404,registry:FleetBoxes@350,registry:FleetBoxes@370,registry:Host@164,registry:Host@732,registry:Host@940,registry:Moved@593,registry:Moved@608,registry:Moved@785,registry:Moved@812,registry:Region@831,registry:Region@847,registry:Region@979,registry:Region@991,registry:ReplicaIncarnation@466,registry:ReplicaIncarnation@494,registry:ReplicaRevision@418,registry:ReplicaRevision@443,whole:Route@234,whole:Route@242,whole:Route@91 692ba8509b2b5dc40a1bd39bf5038b68c5d8c41e8fdc264a1f4041892d300210
-@legacy 926fe010631c13d9163f2e469645502d8757893e02917ce41bc5241c5b449822 internal/host/fleetbind.go ReconcileFleetBindings legacy accepted-legacy accepted-legacy;rev3=J1;basis=root-route;rev3=census-ruling-fleet-public-routes;basis=fleet public routes (spec 2026-10-29 rev 4, §4.2 writer rule): §4.5: runs on the hub only (hubArmed); a binding whose object key is not fleetBindingKey(b.Fleet, b.Host) is skipped and logged before anything else; the stamp is SetFleetBoxIf, one conditional write judging placement, kind and active fleet membership at the instant of the write (SetFleetBox removed); a write that changes nothing is logged. Read sites unchanged (3); it stamps less, never more.;rev3=census-ruling-stateless-replicas-2;basis=Slice 3b: same existing binding list/Get. Key checked before join; set bindings validate current local projection and fleet ownership/membership. Legacy stamps cannot change a set, set stamps cannot change legacy routes. Current declarative assignment stays authoritative. registry:FleetBox@2407,registry:FleetBoxes@2104,registry:Region@1896,whole:Route@1030,whole:Route@2354 9177e697b3cbbaff3665cab486a1c663fdb5c6d3d8b5f13b5c0da74f0f3f91f2
+@legacy 3fa6833439be7f0b86af4efe2e51520a41089f57978143b1bf667e58accd1bed internal/host/fleetbind.go ReconcileFleetBindings legacy accepted-legacy accepted-legacy;rev3=J1;basis=root-route;rev3=census-ruling-fleet-public-routes;basis=fleet public routes (spec 2026-10-29 rev 4, §4.2 writer rule): §4.5: runs on the hub only (hubArmed); a binding whose object key is not fleetBindingKey(b.Fleet, b.Host) is skipped and logged before anything else; the stamp is SetFleetBoxIf, one conditional write judging placement, kind and active fleet membership at the instant of the write (SetFleetBox removed); a write that changes nothing is logged. Read sites unchanged (3); it stamps less, never more.;rev3=census-ruling-stateless-replicas-2;basis=Slice 3b: same existing binding list/Get. Key checked before join; set bindings validate current local projection and fleet ownership/membership. Legacy stamps cannot change a set, set stamps cannot change legacy routes. Current declarative assignment stays authoritative. Fix round 1 m1: a set stamp must pass the key/lifetime/revision/current-owner/member validator to be accepted without error. Invalid set stamps contribute ErrFenced after all other bindings are processed; legacy stamps on set rows remain ignored. Existing FleetOwners/ListFleetBoxes reads now decide that verdict; no new read or routing authority. registry:FleetBox@2768,registry:FleetBoxes@1265,registry:Region@2559,whole:Route@1187,whole:Route@1679 66e7b52d2548ff14039f1b7add0d81f95b8765d3eff7856922e6f99e0669cad6
@legacy 37bf1c69ed631e5e8755fcf427823463217524bb8437b9cc274db60c2d0d66da internal/host/fleetbind.go statelessBindingPublisher.publish legacy accepted-legacy accepted-legacy;rev3=census-ruling-stateless-replicas-1;basis=Task 3b: consume the applied record and serving route already read by reconcile, check instance/account/app/assignment/status/fleet/box and exact held coordinator lifetime, then publish the existing binding key. A per-host state cache excludes expiry-only renewals and avoids unchanged binding I/O. No instance-record scan or root exec; no typed record writer added.;rev3=census-ruling-stateless-replicas-2;basis=Slice 3b: existing coordinator authority gates one binding object per host. Set fields come from matching record and route lifetime/revision. Cached assignment/deploy state prevents periodic bucket work; legacy path retains previous encoding with new fields omitted. registry:Account@273,registry:App@302,registry:Assigned@323,registry:Host@250,registry:Provisioned@208,registry:ReplicaIncarnation@1422,registry:ReplicaRevision@1462,registry:ServingVersion@1091,registry:Stateless@155,registry:Status@226 3f9b0440c0c690de0b7f8fba52c05d8f9a4a3e715a39a379fec9890aa7790eab
@legacy 122fa7f57714580041b4e16316fc152a4156a94f1caf344f19a385a1a12d5021 internal/provision/forward.go forwardCurrent legacy accepted-legacy accepted-legacy;rev3=census-ruling-fleet-public-routes;basis=fleet public routes (spec 2026-10-29 rev 4, §4.2 writer rule): Task 10: compares the existing forward row's declared fields with the wanted one (+registry:Account, App, Channel, Provisioned, RateLimit, Region, Slug, Status, each x2). Pure.;rev3=census-ruling-managed-fleets-1b;basis=managed fleets 1b (Task 5): the forward row is current only if FleetLabel also matches and, for a labelled want, FleetBox equals the label (+registry:FleetBox x2, +registry:FleetLabel x3). The hub's forward phase in the agent, not root; it may write a row it skipped before, never fewer checks.;rev3=census-ruling-stateless-replicas-2;basis=Pure comparison covers explicit count/set/revision/lifetime and assigned mode; legacy nil-assignment mode comparison remains unchanged. registry:Account@550,registry:Account@570,registry:App@520,registry:App@536,registry:Channel@624,registry:Channel@644,registry:Copies@137,registry:Copies@156,registry:FleetBox@376,registry:FleetBox@774,registry:FleetBox@795,registry:FleetBoxes@118,registry:FleetBoxes@282,registry:FleetBoxes@351,registry:FleetBoxes@95,registry:FleetLabel@704,registry:FleetLabel@727,registry:FleetLabel@749,registry:Provisioned@442,registry:Provisioned@466,registry:RateLimit@662,registry:RateLimit@684,registry:Region@588,registry:Region@607,registry:ReplicaIncarnation@223,registry:ReplicaIncarnation@254,registry:ReplicaRevision@171,registry:ReplicaRevision@199,registry:Slug@488,registry:Slug@505,registry:Stateless@307,registry:Stateless@329,registry:Status@406,registry:Status@425 35f2010c3c11b810e2a7f06c0575c2d08cf1777b71b091d9c432f1835f187c5a
@legacy 7296e6ba689212172bbf4d6e02e7b45068371d41feecd784ac50209497e1de8e internal/provision/reconcile.go Reconcile legacy accepted-legacy accepted-legacy;rev3=census-ruling-self-serve-moves-1;basis=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos), from its reconcile loops: each listed record is observed through the box's lifetime judge (ObserveWith: the record, then its host incarnation slot) before the shape, channel and scope checks, a stale record is left out and an unjudgeable one protected; the removal phase observes a row's own record key when the pass holds none for it under that key, and deletes a held row whose record is gone or stale through DeleteIfHold; a nil judge (claims on) is main's body; registry read sites unchanged, offsets moved; fix round 1: the removal phase observes a row's own key only under an account the listing trusts, so a retired or unmaterialised account's row keeps record gone, and the pass arms its own context with the judge; Task 7: under a judge an existing provisioned row of the record's own app and account follows the existing-row rules (heldByVanishedPredecessor and retireHeldPredecessor's DeleteIfHold first, the record then minted on the same pass; the hold; installRowLifetime), each a separate write under the host's hold lock; registry read sites unchanged, offsets moved;rev3=census-ruling-instance-egress-sizes-328-329;identity=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos);basis=#328/#329 plan 1 Task 7: the pass reads its apps' policy objects (control/app-policy/<sqid>/<app>.json in the bucket) through the agent's PolicyCache, each verified with ReleasePub by apppolicy.VerifyKey (ed25519 over the policy's own domain line, bound to the account and app, unexpired, not future-dated; anything else is no policy), and carries the columns into its rows. New kinds registry:EgressAllow, registry:Size and registry:PolicyExpiresAt, one site each, all the assignment of a fresh row's columns (nr) from policies.cols; plus one whole:Route site, the existing row handed to policies.forRow. Other read sites unchanged, offsets moved; the agent's own pass, no root decision;rev3=census-ruling-region-ha-p1a;basis=the agent as carlos, from its reconcile loops: after the scan, hands the in-scope records to cfg.Lifetimes (the box's lifetime index): Merge after a failed read or partial listing, Replace after a complete one, nothing on a dry run or with no index; the scan, judge and removal phases unchanged; the same 166 sites, no read added;rev3=census-ruling-rootfs-apps-3;basis=rootfs Plan 3 Tasks 2 and 5 (D5, spec §5.0): a seeded record over a row with a runtime is skipped and logged; a row with a runtime (or a new record with one) takes no seed; runtime and a rootfs row's hibernation are never converged from a record (a mismatch is logged; a record claiming a runtime its row lacks is not applied); reads Runtime of the record and the row; the box writes less; fix wave 1 (ceea6353, whole-branch P1-2): before minting a row for a record with no runtime and no row (both mint paths), the pass reads the app's kind marker once per app per pass (release.ReadAppKindMarker: one GET of the create-only kind.json from the release store s, through freshStore, validated by readAppKindMarker); a rootfs marker leaves the record unmaterialized and logged (an older console stripped its runtime), and a marker that cannot be read defers the mint this pass; a refusal before minting only, registry read sites unchanged, the box writes less; fix wave 2 (whole-branch r2 P1): the kind-marker read and its refusal apply only to a socket-backed instance record (DerivesPaths), so a static or upstream-backed record of a rootfs app, which carries no runtime by design, is minted as before with no read; fewer reads, registry read sites unchanged;rev3=census-ruling-fleet-public-routes;basis=fleet public routes (spec 2026-10-29 rev 4, §4.2 writer rule): Task 10: the forward phase on the hub (FleetOwners set): the scan keeps the fleet-placed records it skips and counts records per host; a trash-only marker prefetch; disputed (failed-GET) hosts; armed, a host an in-scope and a fleet record both name is given neither, its journal waits and the removal phase keeps its row (+registry:Account, +registry:App, +registry:Host x2: the collision guard, its log line and report mark); the instance loop leaves a forward host; retirable excludes forward rows. Same record keys; writes only the registry (PutForward, DeleteForward); no bucket write.;rev3=census-ruling-managed-fleets-1b;basis=managed fleets 1b (Task 4, rules 2 and 9): after inScope, a record failing cfg.ownsRecord (on a fleet box, labelled for another box: rec.FleetBox != "" and != cfg.FleetBox) is skipped as out of scope, so it is never minted here; in the removal phase such a record no longer keeps the row (inScope && ownsRecord), so the row goes as record gone. Off a fleet ownsRecord is always true. Read sites unchanged (178). The agent's reconcile loops, not root; it mints less, never more.;rev3=census-ruling-rootfs-apps-6;basis=rootfs Plan 6 Task 3: in the per-record loop, beside the RunSeen call, calls cfg.InteractiveSeen(rec) when the hook is set and the in-scope record carries an interactive-session marker (rec.Interactive != nil), once per record per pass, before the pass acts on it; the hook is the box worker's non-blocking note (Task 12). Same record keys and literal; no read added (registry read sites unchanged, 178); nothing written by the call; merge of origin/main 6f1f6ca6: main's fleet-box ownsRecord skip in the record scan and in the removal phase is kept as main has it (census-ruling-managed-fleets-1b); this branch's change is the same as above; read sites unchanged (178);rev3=census-ruling-stateless-replicas-1;basis=Task 3b: call the optional binding callback only for applied, owned stateless rows outside dry run. Reuses this pass record and route reads after existing collision, scope, hold, policy and shape checks; no new record read or typed writer. Fix 3b round 1 I1: binding callback failure is logged and falls through to pr.applied; same per-host callback, record writers, scope and removal gates. TestStatelessBindingFailureContinuesReconcile covers second-record convergence, removal, applied bookkeeping and next-pass retry.;rev3=census-ruling-stateless-replicas-2;basis=Slice 3b: reports validated scoped assignments from the existing complete record scan to the worker; validated legacy observations cancel stale queued ACKs after a lost reply and P16 conversion; no termination ACK inferred from route deletion. Existing local removal unchanged. Applied set routes can use the coordinator-gated binding callback. Prior P11/P14 claims remain applicable. registry:Account@38334,registry:Account@40090,registry:Account@58408,registry:Account@58454,registry:Account@59765,registry:Account@60142,registry:Account@60368,registry:Account@60435,registry:Account@60481,registry:Account@60574,registry:Account@60616,registry:Account@61264,registry:Account@61522,registry:Account@62424,registry:Account@62472,registry:Account@62881,registry:Account@62927,registry:Account@63172,registry:Account@63597,registry:Account@64085,registry:Account@64821,registry:Account@65014,registry:Account@65426,registry:Account@65605,registry:Account@65928,registry:Account@66493,registry:App@38307,registry:App@40063,registry:App@58428,registry:App@58466,registry:App@59777,registry:App@60154,registry:App@60380,registry:App@60455,registry:App@60493,registry:App@60594,registry:App@61276,registry:App@61534,registry:App@62436,registry:App@62484,registry:App@62901,registry:App@62939,registry:App@63184,registry:App@63609,registry:App@64097,registry:App@64833,registry:App@65026,registry:App@65438,registry:App@65617,registry:App@65940,registry:App@66505,registry:Canary@58921,registry:ClaimOwnership@38921,registry:DBPath@48269,registry:DBPath@48284,registry:DBPath@48530,registry:DBPath@49133,registry:DBPath@49146,registry:EgressAllow@37420,registry:FleetBoxes@58882,registry:FleetBoxes@59030,registry:FleetBoxes@65214,registry:Gate@44614,registry:Gate@44754,registry:Gate@45041,registry:Hibernate@43286,registry:Hibernate@43484,registry:Hibernate@43549,registry:Hibernate@43888,registry:Hibernate@44239,registry:Hibernate@44549,registry:HoldOp@29513,registry:HoldOp@64566,registry:HoldOp@64657,registry:HoldOp@64792,registry:HoldOp@65168,registry:Host@27410,registry:Host@29916,registry:Host@30056,registry:Host@58387,registry:Host@58981,registry:Host@59741,registry:Host@60118,registry:Host@60282,registry:Host@60388,registry:Host@61284,registry:Host@61490,registry:Host@62764,registry:Host@63036,registry:Host@63151,registry:Host@63474,registry:Host@63571,registry:Host@63962,registry:Host@64059,registry:Host@64273,registry:Host@64648,registry:Host@64783,registry:Host@64987,registry:Host@65060,registry:Host@65159,registry:Host@65399,registry:Host@65578,registry:Host@65657,registry:Host@65744,registry:Host@65902,registry:Host@65977,registry:Host@66063,registry:Host@66470,registry:Incarnation@29689,registry:Kind@29901,registry:Kind@30041,registry:Kind@39063,registry:Kind@39315,registry:Kind@39597,registry:Kind@39817,registry:Kind@48187,registry:Kind@48200,registry:Kind@48310,registry:Kind@48323,registry:Kind@49044,registry:Kind@49055,registry:Kind@57511,registry:Kind@64264,registry:Kind@64774,registry:Kind@65150,registry:Kind@65390,registry:Kind@65735,registry:Kind@65893,registry:Kind@66054,registry:Platform@58906,registry:PolicyExpiresAt@37445,registry:Pool@57597,registry:Provisioned@38283,registry:Provisioned@40039,registry:Provisioned@57556,registry:RateLimit@45127,registry:RateLimit@45278,registry:RateLimit@45565,registry:Region@57586,registry:ReplicaIncarnation@29397,registry:ReplicaIncarnation@29434,registry:Replication@43973,registry:Replication@44100,registry:Runtime@31085,registry:Runtime@31263,registry:Runtime@33468,registry:Runtime@42653,registry:Runtime@42707,registry:Runtime@42911,registry:Seed@46667,registry:SeedSource@46150,registry:Size@37436,registry:Socket@48235,registry:Socket@48250,registry:Socket@48547,registry:Socket@49103,registry:Socket@49116,registry:Stateless@49204,registry:Unit@48153,registry:Unit@48166,registry:Unit@49070,registry:Unit@49081,whole:ClaimOwnership@38924,whole:ClaimOwnership@38941,whole:Route@27392,whole:Route@27403,whole:Route@27421,whole:Route@28702,whole:Route@29289,whole:Route@29500,whole:Route@29815,whole:Route@30101,whole:Route@30115,whole:Route@30128,whole:Route@30151,whole:Route@31580,whole:Route@31587,whole:Route@31627,whole:Route@31988,whole:Route@32326,whole:Route@32773,whole:Route@32824,whole:Route@32861,whole:Route@34533,whole:Route@34742,whole:Route@35081,whole:Route@35090,whole:Route@35136,whole:Route@37369,whole:Route@37928,whole:Route@38399,whole:Route@38409,whole:Route@38766,whole:Route@38773,whole:Route@38841,whole:Route@39146,whole:Route@39216,whole:Route@39227,whole:Route@39655,whole:Route@40688,whole:Route@43639,whole:Route@48379,whole:Route@49317,whole:Route@50204,whole:Route@50249,whole:Route@50259,whole:Route@51129,whole:Route@52156,whole:Route@57622,whole:Route@57770,whole:Route@58867,whole:Route@59159,whole:Route@59693,whole:Route@60075,whole:Route@61926,whole:Route@65305,whole:Route@65815,whole:Route@66400,whole:Route@66450 ab45b30440cea54723225f647943b534396ce9f3f0494efa95b0698051fb0fe6
@@ -49,7 +49,7 @@ internal/activator/replicaretirement.go ExecBackend.ReplicaRetirementEmpty legac
internal/activator/wakeidentity.go Service.CheckReplicaAssignment legacy accepted-legacy accepted-legacy;rev3=census-ruling-stateless-replicas-2;basis=Only set rows invoke existing registry/instance-record wake recheck. Legacy returns without reading; not a new polling loop. registry:FleetBoxes@93,whole:Route@169 43e922e015b61f736ed118ad44113802ca1944b676e9586388d6f9e00d691eba
internal/host/fleetbind.go validReplicaFleetBinding legacy accepted-legacy accepted-legacy;rev3=census-ruling-stateless-replicas-2;basis=Slice 3b: validates canonical boxes, host, fleet, lifetime and exact assignment revision against existing route; local registry fleet owner and active labels must match. No bucket call; no writer. registry:Account@643,registry:Account@657,registry:Copies@481,registry:FleetBoxes@132,registry:FleetBoxes@540,registry:Host@373,registry:Label@856,registry:Region@331,registry:ReplicaIncarnation@188,registry:ReplicaRevision@230,registry:Status@878,whole:FleetBox@842 2c20af701cc19717ba83d02c9361c3a34da18fe68e8fac862deaa9787b025ebb
internal/host/fleetidentity.go recheckReplicaPickup legacy accepted-legacy accepted-legacy;rev3=census-ruling-stateless-replicas-2;basis=Only set rows require a launcher with the activator current-membership check; missing check refuses pickup. Reads supplied Route only. registry:FleetBoxes@98,whole:Route@322 7af336690a854d75b8a68b2f8031f8fb2cbd8441117e73c30610307d8f0dd7ca
-internal/host/replicaplacement.go replicaPlacementWorker.run legacy accepted-legacy accepted-legacy;rev3=census-ruling-stateless-replicas-2;basis=Slice 3b: existing tick processes already-read records with bounded exponential backoff. Reads local registry only. Under reconcile exclusion, absent row plus activator quiet plus both cgroup layouts empty precede authenticated retired API POST for exact lifetime/revision. Members only acquire for the deterministic chosen coordinator; others do no publication. API timeout/cancellation bounds shutdown; successful or fenced ACKs leave the queue, while transient failures retry with backoff. A new record observation can queue a new revision. No new bucket polling. registry:ReplicaIncarnation@1190,registry:ReplicaRevision@1222,whole:Route@1177,whole:Route@1539,whole:Route@830,whole:Route@982 de7cf90d73351ab66574136e24ff9614fce158d676b6351d4ef510dac46e419a
+internal/host/replicaplacement.go replicaPlacementWorker.run legacy accepted-legacy accepted-legacy;rev3=census-ruling-stateless-replicas-2;basis=Slice 3b: existing tick processes already-read records with bounded exponential backoff. Reads local registry only. Under reconcile exclusion, absent row plus activator quiet plus both cgroup layouts empty precede authenticated retired API POST for exact lifetime/revision. Members only acquire for the deterministic chosen coordinator; others do no publication. API timeout/cancellation bounds shutdown; successful or fenced ACKs leave the queue, while transient failures retry with backoff. A new record observation can queue a new revision. No new bucket polling. Fix round 1 I3: reconcileMu protects only the registry observation and local quiet/cgroup proof. Unlock before retired POST, coordinator Acquire and binding publication. The ACK remains bound to the same lifetime/revision and the server CAS refuses intervening assignment changes. Existing local read sites unchanged; no new polling. registry:ReplicaIncarnation@1235,registry:ReplicaRevision@1267,whole:Route@1000,whole:Route@1222,whole:Route@1584,whole:Route@848 88bd40ca3d72c93b4973bf294ff1c32ed48d45049bef2964206e611bdcc264d1
internal/provision/forward.go forwardRowFor legacy accepted-legacy accepted-legacy;rev3=census-ruling-stateless-replicas-2;basis=Projects declarative set fields from supplied record; keeps socket, database, execution and all other forbidden fields zero. whole:Route@436,whole:Route@453 9ba6c562aa2b720af029d069b5855b8d1dc32ff76c742c90ad13604f8f19970d
internal/provision/replicaassignment.go projectReplicaAssignment legacy accepted-legacy accepted-legacy;rev3=census-ruling-stateless-replicas-2;basis=P12: pure projection marks a present assignment invalid before validation, so an invalid shape cannot silently become the legacy empty set. No store read or path authority. registry:Copies@465,registry:FleetBox@616,registry:FleetBoxes@254,registry:FleetBoxes@450,registry:FleetLabel@629,registry:ReplicaIncarnation@496,registry:ReplicaRevision@476,registry:Stateless@595 be1287470cf6b9cfbef39e9740c21b461d952b265098d72c9e32c37e6326e383
internal/provision/replicaassignment.go replicaRowLifetimeAllowed legacy accepted-legacy accepted-legacy;rev3=census-ruling-stateless-replicas-2;basis=P11: pure comparison of the already-read record and local route. Requires same owner and managed instance kind; accepts unprojected legacy rows for membership, matching lifetimes, or a proven older monotonic counter. Newer/unknown ordering refuses. registry:Account@145,registry:App@174,registry:Canary@132,registry:FleetBoxes@387,registry:Host@195,registry:Incarnation@218,registry:Kind@92,registry:Platform@117,registry:Provisioned@74,registry:ReplicaIncarnation@410,registry:ReplicaIncarnation@442,whole:Route@495 03c64806b231b7af2844dc47eaeefc52549bbce0e6afd56ed3d103d87f2f42a0
@@ -70,7 +70,7 @@ internal/activator/startrule.go ExecBackend.reconcileAssignment legacy accepted-
internal/activator/startrule.go ExecBackend.startAllowed legacy accepted-legacy accepted-legacy;rev3=census-ruling-managed-fleets-1b;basis=new (Task 3, rule 6): the start rule: an unlabelled or restored start is allowed; a kept local copy must match rt.Assigned in its marker; an empty start of a labelled row is refused (ErrNothingToRestore) when a set-aside entry exists for the host or rt.Moved is set. Only refuses. Agent, not root.;rev3=census-ruling-stateless-replicas-2;basis=A set projection refuses this SQLite empty-start rule; does not turn a route hint into bypass authority. Legacy rule unchanged. registry:Assigned@211,registry:Assigned@668,registry:Assigned@820,registry:FleetBoxes@163,registry:Host@268,registry:Moved@1407,whole:Route@315 c0576b3af038f2a714e43ae6263d259110825f3ea18f5c9798214d7baf6958e4
internal/activator/wakeidentity.go Service.currentWakeRoute legacy accepted-legacy accepted-legacy;rev3=census-ruling-stateless-replicas-1;basis=Extract existing registry and labelled fleet record recheck for reuse without a serving lease; return the observed row and record and refuse a nil record. No writer or new path.;rev3=census-ruling-stateless-replicas-2;basis=Existing registry/record recheck validates canonical set, membership, lifetime, revision, owner and managed stateless shape. Reuses the one wake record read; unknown fleet and malformed projection refuse. registry:Account@1846,registry:App@1871,registry:Assigned@2821,registry:Assigned@3031,registry:Assigned@510,registry:Channel@2015,registry:Copies@2407,registry:Environment@2077,registry:FleetBoxes@1523,registry:FleetBoxes@2357,registry:FleetBoxes@531,registry:FleetBoxes@641,registry:Host@1114,registry:Host@1243,registry:Host@1410,registry:Host@1893,registry:Host@281,registry:Host@2956,registry:Host@379,registry:Host@971,registry:Kind@1592,registry:Region@1918,registry:Region@1949,registry:ReplicaIncarnation@2323,registry:ReplicaRevision@2454,registry:Runtime@2044,whole:Route@1327,whole:Route@229,whole:Route@2751,whole:Route@3056,whole:Route@427,whole:Route@431,whole:Route@488,whole:Route@499,whole:Route@563,whole:Route@721 abf3135d80b76a02b2047a9bcedc85852d38625eab20f550848878485b4d2e16
internal/activator/wakeidentity.go leaseRouteChanged legacy accepted-legacy accepted-legacy;rev3=census-ruling-managed-fleets-1b;basis=new (branch review R1 P1-1): a pure comparison of the row a wake began from (began) with the row doWake read under the lease (now): nil now is a row that is gone; then wakeRouteChanged's identity checks; then Assigned and Moved; then Region. It answers an error naming the change, wrapping errRouteChangedUnderLease, or nil. No read beyond its arguments. Agent, not root; it only refuses.;rev3=census-ruling-stateless-replicas-2;basis=Pure comparison adds set/count/revision/lifetime changes to existing wake fence; no new input source. registry:Assigned@559,registry:Assigned@577,registry:Assigned@771,registry:Assigned@796,registry:Copies@388,registry:Copies@404,registry:FleetBoxes@350,registry:FleetBoxes@370,registry:Host@164,registry:Host@732,registry:Host@940,registry:Moved@593,registry:Moved@608,registry:Moved@785,registry:Moved@812,registry:Region@831,registry:Region@847,registry:Region@979,registry:Region@991,registry:ReplicaIncarnation@466,registry:ReplicaIncarnation@494,registry:ReplicaRevision@418,registry:ReplicaRevision@443,whole:Route@234,whole:Route@242,whole:Route@91 692ba8509b2b5dc40a1bd39bf5038b68c5d8c41e8fdc264a1f4041892d300210
-internal/host/fleetbind.go ReconcileFleetBindings legacy accepted-legacy accepted-legacy;rev3=J1;basis=root-route;rev3=census-ruling-fleet-public-routes;basis=fleet public routes (spec 2026-10-29 rev 4, §4.2 writer rule): §4.5: runs on the hub only (hubArmed); a binding whose object key is not fleetBindingKey(b.Fleet, b.Host) is skipped and logged before anything else; the stamp is SetFleetBoxIf, one conditional write judging placement, kind and active fleet membership at the instant of the write (SetFleetBox removed); a write that changes nothing is logged. Read sites unchanged (3); it stamps less, never more.;rev3=census-ruling-stateless-replicas-2;basis=Slice 3b: same existing binding list/Get. Key checked before join; set bindings validate current local projection and fleet ownership/membership. Legacy stamps cannot change a set, set stamps cannot change legacy routes. Current declarative assignment stays authoritative. registry:FleetBox@2407,registry:FleetBoxes@2104,registry:Region@1896,whole:Route@1030,whole:Route@2354 9177e697b3cbbaff3665cab486a1c663fdb5c6d3d8b5f13b5c0da74f0f3f91f2
+internal/host/fleetbind.go ReconcileFleetBindings legacy accepted-legacy accepted-legacy;rev3=J1;basis=root-route;rev3=census-ruling-fleet-public-routes;basis=fleet public routes (spec 2026-10-29 rev 4, §4.2 writer rule): §4.5: runs on the hub only (hubArmed); a binding whose object key is not fleetBindingKey(b.Fleet, b.Host) is skipped and logged before anything else; the stamp is SetFleetBoxIf, one conditional write judging placement, kind and active fleet membership at the instant of the write (SetFleetBox removed); a write that changes nothing is logged. Read sites unchanged (3); it stamps less, never more.;rev3=census-ruling-stateless-replicas-2;basis=Slice 3b: same existing binding list/Get. Key checked before join; set bindings validate current local projection and fleet ownership/membership. Legacy stamps cannot change a set, set stamps cannot change legacy routes. Current declarative assignment stays authoritative. Fix round 1 m1: a set stamp must pass the key/lifetime/revision/current-owner/member validator to be accepted without error. Invalid set stamps contribute ErrFenced after all other bindings are processed; legacy stamps on set rows remain ignored. Existing FleetOwners/ListFleetBoxes reads now decide that verdict; no new read or routing authority. registry:FleetBox@2768,registry:FleetBoxes@1265,registry:Region@2559,whole:Route@1187,whole:Route@1679 66e7b52d2548ff14039f1b7add0d81f95b8765d3eff7856922e6f99e0669cad6
internal/host/fleetbind.go statelessBindingPublisher.publish legacy accepted-legacy accepted-legacy;rev3=census-ruling-stateless-replicas-1;basis=Task 3b: consume the applied record and serving route already read by reconcile, check instance/account/app/assignment/status/fleet/box and exact held coordinator lifetime, then publish the existing binding key. A per-host state cache excludes expiry-only renewals and avoids unchanged binding I/O. No instance-record scan or root exec; no typed record writer added.;rev3=census-ruling-stateless-replicas-2;basis=Slice 3b: existing coordinator authority gates one binding object per host. Set fields come from matching record and route lifetime/revision. Cached assignment/deploy state prevents periodic bucket work; legacy path retains previous encoding with new fields omitted. registry:Account@273,registry:App@302,registry:Assigned@323,registry:Host@250,registry:Provisioned@208,registry:ReplicaIncarnation@1422,registry:ReplicaRevision@1462,registry:ServingVersion@1091,registry:Stateless@155,registry:Status@226 3f9b0440c0c690de0b7f8fba52c05d8f9a4a3e715a39a379fec9890aa7790eab
internal/provision/forward.go forwardCurrent legacy accepted-legacy accepted-legacy;rev3=census-ruling-fleet-public-routes;basis=fleet public routes (spec 2026-10-29 rev 4, §4.2 writer rule): Task 10: compares the existing forward row's declared fields with the wanted one (+registry:Account, App, Channel, Provisioned, RateLimit, Region, Slug, Status, each x2). Pure.;rev3=census-ruling-managed-fleets-1b;basis=managed fleets 1b (Task 5): the forward row is current only if FleetLabel also matches and, for a labelled want, FleetBox equals the label (+registry:FleetBox x2, +registry:FleetLabel x3). The hub's forward phase in the agent, not root; it may write a row it skipped before, never fewer checks.;rev3=census-ruling-stateless-replicas-2;basis=Pure comparison covers explicit count/set/revision/lifetime and assigned mode; legacy nil-assignment mode comparison remains unchanged. registry:Account@550,registry:Account@570,registry:App@520,registry:App@536,registry:Channel@624,registry:Channel@644,registry:Copies@137,registry:Copies@156,registry:FleetBox@376,registry:FleetBox@774,registry:FleetBox@795,registry:FleetBoxes@118,registry:FleetBoxes@282,registry:FleetBoxes@351,registry:FleetBoxes@95,registry:FleetLabel@704,registry:FleetLabel@727,registry:FleetLabel@749,registry:Provisioned@442,registry:Provisioned@466,registry:RateLimit@662,registry:RateLimit@684,registry:Region@588,registry:Region@607,registry:ReplicaIncarnation@223,registry:ReplicaIncarnation@254,registry:ReplicaRevision@171,registry:ReplicaRevision@199,registry:Slug@488,registry:Slug@505,registry:Stateless@307,registry:Stateless@329,registry:Status@406,registry:Status@425 35f2010c3c11b810e2a7f06c0575c2d08cf1777b71b091d9c432f1835f187c5a
internal/provision/reconcile.go Reconcile legacy accepted-legacy accepted-legacy;rev3=census-ruling-self-serve-moves-1;basis=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos), from its reconcile loops: each listed record is observed through the box's lifetime judge (ObserveWith: the record, then its host incarnation slot) before the shape, channel and scope checks, a stale record is left out and an unjudgeable one protected; the removal phase observes a row's own record key when the pass holds none for it under that key, and deletes a held row whose record is gone or stale through DeleteIfHold; a nil judge (claims on) is main's body; registry read sites unchanged, offsets moved; fix round 1: the removal phase observes a row's own key only under an account the listing trusts, so a retired or unmaterialised account's row keeps record gone, and the pass arms its own context with the judge; Task 7: under a judge an existing provisioned row of the record's own app and account follows the existing-row rules (heldByVanishedPredecessor and retireHeldPredecessor's DeleteIfHold first, the record then minted on the same pass; the hold; installRowLifetime), each a separate write under the host's hold lock; registry read sites unchanged, offsets moved;rev3=census-ruling-instance-egress-sizes-328-329;identity=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos);basis=#328/#329 plan 1 Task 7: the pass reads its apps' policy objects (control/app-policy/<sqid>/<app>.json in the bucket) through the agent's PolicyCache, each verified with ReleasePub by apppolicy.VerifyKey (ed25519 over the policy's own domain line, bound to the account and app, unexpired, not future-dated; anything else is no policy), and carries the columns into its rows. New kinds registry:EgressAllow, registry:Size and registry:PolicyExpiresAt, one site each, all the assignment of a fresh row's columns (nr) from policies.cols; plus one whole:Route site, the existing row handed to policies.forRow. Other read sites unchanged, offsets moved; the agent's own pass, no root decision;rev3=census-ruling-region-ha-p1a;basis=the agent as carlos, from its reconcile loops: after the scan, hands the in-scope records to cfg.Lifetimes (the box's lifetime index): Merge after a failed read or partial listing, Replace after a complete one, nothing on a dry run or with no index; the scan, judge and removal phases unchanged; the same 166 sites, no read added;rev3=census-ruling-rootfs-apps-3;basis=rootfs Plan 3 Tasks 2 and 5 (D5, spec §5.0): a seeded record over a row with a runtime is skipped and logged; a row with a runtime (or a new record with one) takes no seed; runtime and a rootfs row's hibernation are never converged from a record (a mismatch is logged; a record claiming a runtime its row lacks is not applied); reads Runtime of the record and the row; the box writes less; fix wave 1 (ceea6353, whole-branch P1-2): before minting a row for a record with no runtime and no row (both mint paths), the pass reads the app's kind marker once per app per pass (release.ReadAppKindMarker: one GET of the create-only kind.json from the release store s, through freshStore, validated by readAppKindMarker); a rootfs marker leaves the record unmaterialized and logged (an older console stripped its runtime), and a marker that cannot be read defers the mint this pass; a refusal before minting only, registry read sites unchanged, the box writes less; fix wave 2 (whole-branch r2 P1): the kind-marker read and its refusal apply only to a socket-backed instance record (DerivesPaths), so a static or upstream-backed record of a rootfs app, which carries no runtime by design, is minted as before with no read; fewer reads, registry read sites unchanged;rev3=census-ruling-fleet-public-routes;basis=fleet public routes (spec 2026-10-29 rev 4, §4.2 writer rule): Task 10: the forward phase on the hub (FleetOwners set): the scan keeps the fleet-placed records it skips and counts records per host; a trash-only marker prefetch; disputed (failed-GET) hosts; armed, a host an in-scope and a fleet record both name is given neither, its journal waits and the removal phase keeps its row (+registry:Account, +registry:App, +registry:Host x2: the collision guard, its log line and report mark); the instance loop leaves a forward host; retirable excludes forward rows. Same record keys; writes only the registry (PutForward, DeleteForward); no bucket write.;rev3=census-ruling-managed-fleets-1b;basis=managed fleets 1b (Task 4, rules 2 and 9): after inScope, a record failing cfg.ownsRecord (on a fleet box, labelled for another box: rec.FleetBox != "" and != cfg.FleetBox) is skipped as out of scope, so it is never minted here; in the removal phase such a record no longer keeps the row (inScope && ownsRecord), so the row goes as record gone. Off a fleet ownsRecord is always true. Read sites unchanged (178). The agent's reconcile loops, not root; it mints less, never more.;rev3=census-ruling-rootfs-apps-6;basis=rootfs Plan 6 Task 3: in the per-record loop, beside the RunSeen call, calls cfg.InteractiveSeen(rec) when the hook is set and the in-scope record carries an interactive-session marker (rec.Interactive != nil), once per record per pass, before the pass acts on it; the hook is the box worker's non-blocking note (Task 12). Same record keys and literal; no read added (registry read sites unchanged, 178); nothing written by the call; merge of origin/main 6f1f6ca6: main's fleet-box ownsRecord skip in the record scan and in the removal phase is kept as main has it (census-ruling-managed-fleets-1b); this branch's change is the same as above; read sites unchanged (178);rev3=census-ruling-stateless-replicas-1;basis=Task 3b: call the optional binding callback only for applied, owned stateless rows outside dry run. Reuses this pass record and route reads after existing collision, scope, hold, policy and shape checks; no new record read or typed writer. Fix 3b round 1 I1: binding callback failure is logged and falls through to pr.applied; same per-host callback, record writers, scope and removal gates. TestStatelessBindingFailureContinuesReconcile covers second-record convergence, removal, applied bookkeeping and next-pass retry.;rev3=census-ruling-stateless-replicas-2;basis=Slice 3b: reports validated scoped assignments from the existing complete record scan to the worker; validated legacy observations cancel stale queued ACKs after a lost reply and P16 conversion; no termination ACK inferred from route deletion. Existing local removal unchanged. Applied set routes can use the coordinator-gated binding callback. Prior P11/P14 claims remain applicable. registry:Account@38334,registry:Account@40090,registry:Account@58408,registry:Account@58454,registry:Account@59765,registry:Account@60142,registry:Account@60368,registry:Account@60435,registry:Account@60481,registry:Account@60574,registry:Account@60616,registry:Account@61264,registry:Account@61522,registry:Account@62424,registry:Account@62472,registry:Account@62881,registry:Account@62927,registry:Account@63172,registry:Account@63597,registry:Account@64085,registry:Account@64821,registry:Account@65014,registry:Account@65426,registry:Account@65605,registry:Account@65928,registry:Account@66493,registry:App@38307,registry:App@40063,registry:App@58428,registry:App@58466,registry:App@59777,registry:App@60154,registry:App@60380,registry:App@60455,registry:App@60493,registry:App@60594,registry:App@61276,registry:App@61534,registry:App@62436,registry:App@62484,registry:App@62901,registry:App@62939,registry:App@63184,registry:App@63609,registry:App@64097,registry:App@64833,registry:App@65026,registry:App@65438,registry:App@65617,registry:App@65940,registry:App@66505,registry:Canary@58921,registry:ClaimOwnership@38921,registry:DBPath@48269,registry:DBPath@48284,registry:DBPath@48530,registry:DBPath@49133,registry:DBPath@49146,registry:EgressAllow@37420,registry:FleetBoxes@58882,registry:FleetBoxes@59030,registry:FleetBoxes@65214,registry:Gate@44614,registry:Gate@44754,registry:Gate@45041,registry:Hibernate@43286,registry:Hibernate@43484,registry:Hibernate@43549,registry:Hibernate@43888,registry:Hibernate@44239,registry:Hibernate@44549,registry:HoldOp@29513,registry:HoldOp@64566,registry:HoldOp@64657,registry:HoldOp@64792,registry:HoldOp@65168,registry:Host@27410,registry:Host@29916,registry:Host@30056,registry:Host@58387,registry:Host@58981,registry:Host@59741,registry:Host@60118,registry:Host@60282,registry:Host@60388,registry:Host@61284,registry:Host@61490,registry:Host@62764,registry:Host@63036,registry:Host@63151,registry:Host@63474,registry:Host@63571,registry:Host@63962,registry:Host@64059,registry:Host@64273,registry:Host@64648,registry:Host@64783,registry:Host@64987,registry:Host@65060,registry:Host@65159,registry:Host@65399,registry:Host@65578,registry:Host@65657,registry:Host@65744,registry:Host@65902,registry:Host@65977,registry:Host@66063,registry:Host@66470,registry:Incarnation@29689,registry:Kind@29901,registry:Kind@30041,registry:Kind@39063,registry:Kind@39315,registry:Kind@39597,registry:Kind@39817,registry:Kind@48187,registry:Kind@48200,registry:Kind@48310,registry:Kind@48323,registry:Kind@49044,registry:Kind@49055,registry:Kind@57511,registry:Kind@64264,registry:Kind@64774,registry:Kind@65150,registry:Kind@65390,registry:Kind@65735,registry:Kind@65893,registry:Kind@66054,registry:Platform@58906,registry:PolicyExpiresAt@37445,registry:Pool@57597,registry:Provisioned@38283,registry:Provisioned@40039,registry:Provisioned@57556,registry:RateLimit@45127,registry:RateLimit@45278,registry:RateLimit@45565,registry:Region@57586,registry:ReplicaIncarnation@29397,registry:ReplicaIncarnation@29434,registry:Replication@43973,registry:Replication@44100,registry:Runtime@31085,registry:Runtime@31263,registry:Runtime@33468,registry:Runtime@42653,registry:Runtime@42707,registry:Runtime@42911,registry:Seed@46667,registry:SeedSource@46150,registry:Size@37436,registry:Socket@48235,registry:Socket@48250,registry:Socket@48547,registry:Socket@49103,registry:Socket@49116,registry:Stateless@49204,registry:Unit@48153,registry:Unit@48166,registry:Unit@49070,registry:Unit@49081,whole:ClaimOwnership@38924,whole:ClaimOwnership@38941,whole:Route@27392,whole:Route@27403,whole:Route@27421,whole:Route@28702,whole:Route@29289,whole:Route@29500,whole:Route@29815,whole:Route@30101,whole:Route@30115,whole:Route@30128,whole:Route@30151,whole:Route@31580,whole:Route@31587,whole:Route@31627,whole:Route@31988,whole:Route@32326,whole:Route@32773,whole:Route@32824,whole:Route@32861,whole:Route@34533,whole:Route@34742,whole:Route@35081,whole:Route@35090,whole:Route@35136,whole:Route@37369,whole:Route@37928,whole:Route@38399,whole:Route@38409,whole:Route@38766,whole:Route@38773,whole:Route@38841,whole:Route@39146,whole:Route@39216,whole:Route@39227,whole:Route@39655,whole:Route@40688,whole:Route@43639,whole:Route@48379,whole:Route@49317,whole:Route@50204,whole:Route@50249,whole:Route@50259,whole:Route@51129,whole:Route@52156,whole:Route@57622,whole:Route@57770,whole:Route@58867,whole:Route@59159,whole:Route@59693,whole:Route@60075,whole:Route@61926,whole:Route@65305,whole:Route@65815,whole:Route@66400,whole:Route@66450 ab45b30440cea54723225f647943b534396ce9f3f0494efa95b0698051fb0fe6
@@ -84,7 +84,7 @@ internal/provision/reconcile.go RouteFor authority C,E3 rev3=census-ruling-self-
@coverage . d70f08d0dbf9d4774987f8ae730dc6135b164cc5c683071abe013de1f0c3a88c
@coverage internal/activator dd73a47a08fc338a3737c648edf593ec08de33969015db834bbb5c4f4fdb3d6d
@coverage internal/appconfig 32d5f27628b319917ed88ac39e0b22e25292f8f16ba5ef4e69a57ea35471bf77
-@coverage internal/host f79df715a6ed937c868ec49a9fa3b642de3855f0ecb51817f32142a6638518f6
+@coverage internal/host 28bf0d5c5dd74233d438314f3211226632747d6f2e442501ab99e69672310d0e
@coverage internal/provision 512f01ecfa8b96c2c146a05e8ef1be3ef849afbdddd5285c0ad04bfb3da5f451
@coverage internal/registry ac1e84b43cc87318a62bee42e08693201edfa0553799d8daa6e661922871b83d
@coverage internal/release 6c7784eb02f9c2b68045266dabf5a79fb656bcb11a06427787d74ca8f3f96dd6