carlos / platform Public

console: coordinate a one-box fleet's unlabelled record by its binding

Fix stateless replicas Plan 1 dev smoke F8 (#511) without labelling
one-box records. Labels would disable the edge's connected-box fallback
after a box replacement and add recurring fleet-wide bucket reads.

Read one host binding per unlabelled coordinator or release request,
after fleet identity and region validation. Recheck identity and the
record under the app lock, then pass explicit typed evidence to the
writers. Each CAS attempt requires the same fleet, host, coordinating
box and record lifetime, no label or assignment, and a fresh binding.
Neither writer assigns FleetBox. Calls without evidence keep their
existing behaviour, including assignment, lease and replay checks.

Cover the real edge-to-console release flow, unchanged refusal responses,
request read counts, locked record changes and CAS conflicts. Preserve
the old periodic labelling path and its zero-read one-box budget.
Prepare the root census envelope proposal; independent #280 approval
remains controller-owned.
Co-Authored-By: Codex (gpt-6-astra) <noreply@openai.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev 24e3687d5b2b84cf0760979a94291f27719df5a0 parent da71d01
10 files changed, +546 −12
  • docs/superpowers/notes/census-proposal-stateless-coordinator-oneboxfleet.md +53 −0
  • internal/console/replicacoordinator.go +30 −7
  • internal/console/replicacoordinator_test.go +228 −0
  • internal/provision/onebox_coordinator_census_test.go +24 −0
  • internal/provision/plan9_b8_census_test.go +1 −1
  • internal/provision/replica_binding_test.go +182 −0
  • internal/provision/replicacoordinator.go +18 −2
  • internal/provision/replicadeploy.go +5 −2
  • internal/provision/testdata/plan14-root-reads-chain.tsv +1 −0
  • internal/provision/testdata/plan14-root-reads-stateless-coordinator-oneboxfleet.tsv +4 −0

Intent

Attributed to this commit: 8.83 g CO₂e (1,044,572 tokens). This is an attribution, not a measurement — usage counted from this commit's own marker forward to the next one on stateless-coordinator-oneboxfleet, 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-coordinator-oneboxfleet.md b/docs/superpowers/notes/census-proposal-stateless-coordinator-oneboxfleet.md
new file mode 100644
index 000000000..91c6289fe
--- /dev/null
+++ b/docs/superpowers/notes/census-proposal-stateless-coordinator-oneboxfleet.md
@@ -0,0 +1,53 @@
+# Census approval: stateless-coordinator-oneboxfleet
+
+Ruling `census-ruling-stateless-coordinator-oneboxfleet`. The independent reviewer approves or rejects every change below, 0 with a new disposition; nothing goes to the census owner (Paul, #280, 2026-10-26).
+
+Envelopes re-pinned: `internal/provision`.
+
+Review: a model from the other family than the author reads the branch's diff against main on the amadan.net remote (`origin` or `amadan`, whichever points at amadan.net) and gives a verdict for every unit and every re-pinned envelope above. For a unit, compare the change with its recorded disposition and basis below; for an envelope, read every changed function in the package and what it reaches. Reject if the change lets root open, run, query or follow anything it did not before from a path or input a tenant, an app or a box agent can create, write or name; if it weakens a check, refusal, validation, argument or environment the basis relies on; or if the diff cannot settle either. Otherwise approve. Record each verdict on #280 with the tip. A rejected unit goes back to the author to correct; nothing escalates to the census owner.
+
+Seal: `59c0891618b9befae27ebe04d0a67b08c7f7658bca9f1c78bf6d05eb7a708e82` → `59c0891618b9befae27ebe04d0a67b08c7f7658bca9f1c78bf6d05eb7a708e82`.
+
+Overlay: `internal/provision/testdata/plan14-root-reads-stateless-coordinator-oneboxfleet.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`.
+
+## Author context — independent approval pending
+
+This is a proposal, not a #280 approval. The scanner reports only the
+`internal/provision` envelope; the new evidence helper and both writers
+must still be reviewed as authority code. Author notes are also retained
+as comments in `/home/paulca/.cache/sr-f8/claims.tsv`.
+
+The manager replaced the first-labelling design with explicit binding
+evidence. `da71d010` reverts `ad35f1a5`; fleet labelling, moves and their
+periodic read budget match `6209ce43`. The console reads one binding per
+unlabelled request after authenticating fleet identity and record region.
+It rechecks identity and the current record under the app lock, using
+that request's evidence rather than a second binding GET.
+
+Review `ReplicaBindingEvidence.matches`, `SetRecordCoordinator` and
+`SetRecordReplicaRelease` in the two provision files, and both console
+handlers in `internal/console/replicacoordinator.go`. Evidence is an
+explicit optional typed argument, never a client payload field. Each CAS
+attempt requires the current record to remain unlabelled, unassigned,
+for the same fleet and host, with the coordinating box matching the
+binding and BoundAt no older than CreatedAt. Lifetime checks remain.
+The release writer checks evidence before the committed-success replay
+shortcut. Neither writer assigns FleetBox. Calls without evidence keep
+the prior gates and replay behaviour. Record-write census fingerprints
+for these four writers/callers are in `onebox_coordinator_census_test.go`;
+their existing classifications and site kinds are retained.
+
+Known review history: `/home/paulca/.cache/sr-f8/review.md` rejected the
+labelling approach with C1 (authoritative labels prevent replacement-box
+fallback), I1 (lost-box outage window), I2 (recurring one-box bucket reads),
+and minor m3 (404 provenance). The revert removes the new label semantics
+and periodic reads. The new HTTP witness checks the console route's
+version header on refusals. No independent review of this replacement
+has been performed here; the controller owns the next review and must
+carry the existing round count, including any reviews not supplied here.
+
+Use `docs/superpowers/reviews/REVIEW-BRIEF-TEMPLATE.md`: stop at the first
+round with no P1, fix that round's P2s without reopening it, and put P3s
+on the follow-up list. A fourth review needs Paul's go; a replacement
+brief does not reset the budget. Return READY, READY AFTER FIXES or NOT
+READY, with a verdict on this envelope and citations to the code read.
diff --git a/internal/console/replicacoordinator.go b/internal/console/replicacoordinator.go
index 7e4c09798..a7ab351cb 100644
--- a/internal/console/replicacoordinator.go
+++ b/internal/console/replicacoordinator.go
@@ -17,9 +17,15 @@ import (
const replicaReleaseChanged = "this instance changed before the operation finished. the app keeps serving"
const replicaCoordinatorChanged = "this instance changed before the coordination update finished. try again"
+// replicaFleetRequest keeps the one binding read local to this HTTP request.
+// Record and fleet identity checks still run again under the app lock.
+type replicaFleetRequest struct {
+ binding []provision.ReplicaBindingEvidence
+}
+
// replicaFleetRecord authenticates before exposing any record information. The
// same check runs again under the app lock immediately before the typed writer.
-func (s *Server) replicaFleetRecord(r *http.Request) (*provision.Record, string, bool) {
+func (s *Server) replicaFleetRecord(r *http.Request, auth *replicaFleetRequest) (*provision.Record, string, bool) {
account, app, host := r.PathValue("account"), r.PathValue("app"), r.PathValue("host")
if !release.ValidAccount(account) || !release.ValidApp(app) || !provision.ValidHostShape(host) {
return nil, "", false
@@ -38,10 +44,25 @@ func (s *Server) replicaFleetRecord(r *http.Request) (*provision.Record, string,
if err != nil || rec == nil || rec.Retired || rec.Region != "fleet/"+fleet {
return nil, "", false
}
+ if len(auth.binding) != 0 && (rec.FleetBox != "" || rec.ReplicaAssignment != nil) {
+ return nil, "", false
+ }
if a := rec.ReplicaAssignment; a != nil {
if !a.Contains(box) && !slices.Contains(a.Retiring, box) && !(rec.Coordinator != nil && rec.Coordinator.Box == box) {
return nil, "", false
}
+ } else if rec.FleetBox == "" {
+ if len(auth.binding) == 0 {
+ b, ok, err := s.readFleetBinding(r.Context(), fleet, rec.Host)
+ if err != nil || !ok {
+ return nil, "", false
+ }
+ auth.binding = []provision.ReplicaBindingEvidence{{Fleet: b.Fleet, Host: b.Host, Box: b.Box, BoundAt: b.BoundAt}}
+ }
+ b := auth.binding[0]
+ if b.Fleet != fleet || b.Host != rec.Host || b.Box != box || b.BoundAt < rec.CreatedAt.UnixMilli() {
+ return nil, "", false
+ }
} else if rec.FleetBox != box {
return nil, "", false
}
@@ -58,7 +79,8 @@ func replicaPayload(r *http.Request, dst any) bool {
}
func (s *Server) handleReplicaCoordinator(w http.ResponseWriter, r *http.Request) {
- rec, box, ok := s.replicaFleetRecord(r)
+ auth := &replicaFleetRequest{}
+ rec, box, ok := s.replicaFleetRecord(r, auth)
if !ok {
http.NotFound(w, r)
return
@@ -77,7 +99,7 @@ func (s *Server) handleReplicaCoordinator(w http.ResponseWriter, r *http.Request
var result *provision.Record
unauthorized := false
err := s.withRecordLock(id.Account, id.App, func() error {
- current, _, ok := s.replicaFleetRecord(r)
+ current, _, ok := s.replicaFleetRecord(r, auth)
if !ok {
unauthorized = true
return replicas.ErrFenced
@@ -92,7 +114,7 @@ func (s *Server) handleReplicaCoordinator(w http.ResponseWriter, r *http.Request
return err
}
var err error
- result, err = provision.SetRecordCoordinator(r.Context(), s.cfg.Releases, id, req.CoordinatorChange, time.Now())
+ result, err = provision.SetRecordCoordinator(r.Context(), s.cfg.Releases, id, req.CoordinatorChange, time.Now(), auth.binding...)
return err
})
if unauthorized {
@@ -134,7 +156,8 @@ func (s *Server) handleReplicaCoordinator(w http.ResponseWriter, r *http.Request
}
func (s *Server) handleReplicaRelease(w http.ResponseWriter, r *http.Request) {
- rec, box, ok := s.replicaFleetRecord(r)
+ auth := &replicaFleetRequest{}
+ rec, box, ok := s.replicaFleetRecord(r, auth)
if !ok {
http.NotFound(w, r)
return
@@ -152,7 +175,7 @@ func (s *Server) handleReplicaRelease(w http.ResponseWriter, r *http.Request) {
unauthorized := false
changed := false
err := s.withRecordLock(id.Account, id.App, func() error {
- current, _, ok := s.replicaFleetRecord(r)
+ current, _, ok := s.replicaFleetRecord(r, auth)
if !ok {
unauthorized = true
return replicas.ErrFenced
@@ -168,7 +191,7 @@ func (s *Server) handleReplicaRelease(w http.ResponseWriter, r *http.Request) {
next.Previous = current.ReplicaDeploy.Previous
}
var err error
- result, err = provision.SetRecordReplicaRelease(r.Context(), s.cfg.Releases, id, req.Revision, next)
+ result, err = provision.SetRecordReplicaRelease(r.Context(), s.cfg.Releases, id, req.Revision, next, auth.binding...)
if err == nil {
changed = result.RecordSeq != current.RecordSeq
}
diff --git a/internal/console/replicacoordinator_test.go b/internal/console/replicacoordinator_test.go
index beabddf68..3c35661e1 100644
--- a/internal/console/replicacoordinator_test.go
+++ b/internal/console/replicacoordinator_test.go
@@ -4,12 +4,16 @@ import (
"bytes"
"context"
"encoding/json"
+ "errors"
"io"
"net/http"
+ "net/http/httptest"
"strings"
+ "sync/atomic"
"testing"
"time"
+ "github.com/carlosframework/platform/internal/edge"
"github.com/carlosframework/platform/internal/provision"
"github.com/carlosframework/platform/internal/registry"
"github.com/carlosframework/platform/internal/replicas"
@@ -334,3 +338,227 @@ func TestReplicaRetiredACKsUseLatestRevision(t *testing.T) {
t.Fatalf("ACKs: %+v %v", got, err)
}
}
+
+func TestReplicaCoordinatorOneBoxFleetBinding(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ change func(*provision.Record, *fleetBinding)
+ want int
+ reads int32
+ }{
+ {name: "matching", want: 200, reads: 1},
+ {name: "newer", change: func(_ *provision.Record, b *fleetBinding) { b.BoundAt++ }, want: 200, reads: 1},
+ {name: "other-box", change: func(_ *provision.Record, b *fleetBinding) { b.Box = "b2" }, want: 404, reads: 1},
+ {name: "older", change: func(_ *provision.Record, b *fleetBinding) { b.BoundAt-- }, want: 404, reads: 1},
+ {name: "other-host", change: func(_ *provision.Record, b *fleetBinding) { b.Host = "other.example.com" }, want: 404, reads: 1},
+ {name: "other-fleet", change: func(_ *provision.Record, b *fleetBinding) { b.Fleet = "away" }, want: 404, reads: 1},
+ {name: "missing-binding", want: 404, reads: 1},
+ {name: "binding-read-error", want: 404, reads: 1},
+ {name: "labelled-other-box", change: func(r *provision.Record, _ *fleetBinding) { r.FleetBox = "b2" }, want: 404},
+ {name: "labelled-caller", change: func(r *provision.Record, b *fleetBinding) { r.FleetBox = "b1"; b.Box = "b2" }, want: 200},
+ {name: "bad-token", want: 404},
+ {name: "other-region", change: func(r *provision.Record, _ *fleetBinding) { r.Region = "fleet/away" }, want: 404},
+ {name: "set-row-caller", change: func(r *provision.Record, _ *fleetBinding) {
+ r.RecordSeq = 1
+ r.ReplicaAssignment = &replicas.Assignment{Revision: 1, Desired: 1, Boxes: []string{"b1"}}
+ }, want: 200},
+ {name: "set-row-other-box", change: func(r *provision.Record, _ *fleetBinding) {
+ r.RecordSeq = 1
+ r.ReplicaAssignment = &replicas.Assignment{Revision: 1, Desired: 1, Boxes: []string{"b2"}}
+ }, want: 404},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ fx := newIxFx(t, "replica-onebox")
+ token, _, _ := ixFleetWorld(t, fx, fx.acct)
+ reg, err := registry.Open(fx.regPath)
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { reg.Close() })
+ boxes, err := reg.ListFleetBoxes("home")
+ if err != nil {
+ t.Fatal(err)
+ }
+ active := 0
+ for _, b := range boxes {
+ if b.Status == "active" {
+ active++
+ }
+ }
+ if active != 1 {
+ t.Fatalf("active boxes = %d, want 1", active)
+ }
+ rec, _ := ixRecord(t, fx, ixHost)
+ binding := fleetBinding{Fleet: "home", Host: ixHost, Box: "b1", BoundAt: rec.CreatedAt.UnixMilli()}
+ if tc.change != nil {
+ tc.change(&rec, &binding)
+ ixPutRecord(t, fx, rec)
+ }
+ inc, err := provision.Incarnation(rec.Account, rec.App, rec.Host, rec.CreatedAt)
+ if err != nil {
+ t.Fatal(err)
+ }
+ bindingKey := "fleets/home/bindings/" + ixHost + ".json"
+ if tc.name != "missing-binding" {
+ body, err := json.Marshal(binding)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := fx.rel.Put(context.Background(), bindingKey, body, ""); err != nil {
+ t.Fatal(err)
+ }
+ }
+ var reads atomic.Int32
+ ds := fx.rel.(*deletableStore)
+ ds.setGetHook(func(_ context.Context, key string) error {
+ if key == bindingKey {
+ reads.Add(1)
+ if tc.name == "binding-read-error" {
+ return errors.New("injected binding read failure")
+ }
+ }
+ return nil
+ })
+ t.Cleanup(func() { ds.setGetHook(nil) })
+ if tc.name == "bad-token" {
+ token = "revoked"
+ }
+ if err := reg.Upsert(registry.Route{Host: "console.test", App: "console", Unit: "console.service", Kind: "service", Addr: fx.ts.Listener.Addr().String(), Status: "ready", Version: "v-f8-test"}); err != nil {
+ t.Fatal(err)
+ }
+ e, err := edge.New(reg, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ e.EnableTunnels(edge.NewTunnelHub("tunnel.test", nil))
+ post := func(door string, payload any) []byte {
+ t.Helper()
+ _, before := ixRecord(t, fx, ixHost)
+ body, err := json.Marshal(payload)
+ if err != nil {
+ t.Fatal(err)
+ }
+ reads.Store(0)
+ req := httptest.NewRequest(http.MethodPost, "https://tunnel.test/api/fleet/replicas/"+fx.acct+"/shop/"+ixHost+"/"+door, bytes.NewReader(body))
+ req.Header.Set("Authorization", "Bearer "+token)
+ req.Header.Set("Carlos-Tunnel-Name", "home/b1")
+ req.Header.Set("Content-Type", "application/json")
+ w := httptest.NewRecorder()
+ e.ServeHTTP(w, req)
+ if w.Header().Get("X-Carlos-Version") != "v-f8-test" {
+ t.Fatalf("%s: response did not come through the console route: %d %v", door, w.Code, w.Header())
+ }
+ if n := reads.Load(); n != tc.reads {
+ t.Errorf("%s: binding reads = %d, want %d", door, n, tc.reads)
+ }
+ if w.Code != tc.want || tc.want == 404 && w.Body.String() != "404 page not found\n" {
+ t.Fatalf("%s: %d %s, want %d", door, w.Code, w.Body.String(), tc.want)
+ }
+ if tc.want == 404 {
+ _, after := ixRecord(t, fx, ixHost)
+ if !bytes.Equal(before, after) {
+ t.Fatal("refused request changed the record")
+ }
+ }
+ return w.Body.Bytes()
+ }
+ raw := post("coordinator", map[string]any{"incarnation": inc, "op": "acquire", "boot_id": "boot"})
+ if tc.want == 404 {
+ post("release", map[string]any{"incarnation": inc, "op": "begin"})
+ return
+ }
+ var reply replicas.CoordinatorReply
+ if err := json.Unmarshal(raw, &reply); err != nil {
+ t.Fatal(err)
+ }
+ if reply.Lease.Box != "b1" || reply.RemainingMS <= 0 {
+ t.Fatalf("coordinator reply: %+v", reply)
+ }
+ var deploy replicas.Deploy
+ for _, op := range []string{"begin", "releasing", "released"} {
+ raw = post("release", map[string]any{"incarnation": inc, "op": op, "id": "onebox-deploy", "term": reply.Lease.Term, "revision": deploy.Revision, "target": replicas.Build{Version: "v2", Digest: "digest"}})
+ if err := json.Unmarshal(raw, &deploy); err != nil {
+ t.Fatal(err)
+ }
+ }
+ after, _ := ixRecord(t, fx, ixHost)
+ if after.FleetBox != rec.FleetBox || after.FleetBoxAt != rec.FleetBoxAt || after.FleetBoxMoved != rec.FleetBoxMoved || after.ReplicaDeploy == nil || after.ReplicaDeploy.Phase != "released" {
+ t.Fatalf("released record: %+v", after)
+ }
+ })
+ }
+}
+
+func TestReplicaCoordinatorBindingRecheckedUnderLock(t *testing.T) {
+ for _, kind := range []string{"labelled", "assigned", "recreated", "region", "detached"} {
+ t.Run(kind, func(t *testing.T) {
+ fx := newIxFx(t, "replica-binding-race")
+ token, _, _ := ixFleetWorld(t, fx, fx.acct)
+ rec, before := ixRecord(t, fx, ixHost)
+ inc, err := provision.Incarnation(rec.Account, rec.App, rec.Host, rec.CreatedAt)
+ if err != nil {
+ t.Fatal(err)
+ }
+ bindingKey := "fleets/home/bindings/" + ixHost + ".json"
+ body, err := json.Marshal(fleetBinding{Fleet: "home", Host: ixHost, Box: "b1", BoundAt: rec.CreatedAt.UnixMilli()})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := fx.rel.Put(context.Background(), bindingKey, body, ""); err != nil {
+ t.Fatal(err)
+ }
+ reg, err := openRegistry(fx.regPath)
+ if err != nil {
+ t.Fatal(err)
+ }
+ ds := fx.rel.(*deletableStore)
+ var reads atomic.Int32
+ var raced atomic.Value
+ ds.setGetHook(func(ctx context.Context, key string) error {
+ if key != bindingKey {
+ return nil
+ }
+ reads.Add(1)
+ if kind == "detached" {
+ raced.Store(before)
+ return reg.SetFleetBoxStatus("home", "b1", "detached")
+ }
+ switch kind {
+ case "labelled":
+ rec.FleetBox = "b1"
+ case "assigned":
+ rec.RecordSeq = 2
+ rec.ReplicaAssignment = &replicas.Assignment{Revision: 1, Desired: 1, Boxes: []string{"b1"}}
+ case "recreated":
+ rec.CreatedAt = rec.CreatedAt.Add(time.Second)
+ case "region":
+ rec.Region = "fleet/away"
+ }
+ recordKey := provision.RecordKey(fx.acct, "shop", ixHost)
+ _, tag, err := ds.Store.Get(ctx, recordKey)
+ if err != nil {
+ return err
+ }
+ changed, err := json.Marshal(rec)
+ if err != nil {
+ return err
+ }
+ _, err = ds.Store.Put(ctx, recordKey, changed, tag)
+ if err == nil {
+ raced.Store(changed)
+ }
+ return err
+ })
+ t.Cleanup(func() { ds.setGetHook(nil) })
+ code, raw := replicaPost(t, fx, "/api/fleet/replicas/"+fx.acct+"/shop/"+ixHost+"/coordinator", "home/b1", token, map[string]any{"incarnation": inc, "op": "acquire", "boot_id": "boot"})
+ changed, _ := raced.Load().([]byte)
+ if code != 404 || string(raw) != "404 page not found\n" || reads.Load() != 1 || len(changed) == 0 {
+ t.Fatalf("locked recheck: %d %s, reads %d, raced %t", code, raw, reads.Load(), len(changed) != 0)
+ }
+ _, after := ixRecord(t, fx, ixHost)
+ if !bytes.Equal(after, changed) {
+ t.Fatal("refused request changed the raced record")
+ }
+ })
+ }
+}
diff --git a/internal/provision/onebox_coordinator_census_test.go b/internal/provision/onebox_coordinator_census_test.go
new file mode 100644
index 000000000..7b5cfaa2f
--- /dev/null
+++ b/internal/provision/onebox_coordinator_census_test.go
@@ -0,0 +1,24 @@
+package provision
+
+// F8 binding evidence: author-inspected; independent approval is controller-owned.
+func oneBoxCoordinatorWriteCensusInventory() []censusEntry {
+ entries := append([]censusEntry(nil), statelessPlacementWriteCensusInventory()...)
+ for _, next := range []censusEntry{
+ // Evidence authorizes only the current unlabelled legacy record; every CAS attempt rechecks host, fleet, box and binding age. No-evidence rules and lease/lifetime checks remain unchanged.
+ {"internal/provision/replicacoordinator.go", "SetRecordCoordinator", "record-writer", "key:SetRecordCoordinator,key:updateRecord", "4e7f81265c7a32e4e1e026e6999a260f4aae0337cab4b58391ce7a749c2d10e3"},
+ // Evidence is rechecked inside CAS, before replay and release mutation; default replay, term, revision and assignment rules remain. No label is written.
+ {"internal/provision/replicadeploy.go", "SetRecordReplicaRelease", "record-writer", "key:SetRecordReplicaRelease,key:updateRecord", "669ccd055065c7742a4cd87e57c3a2b2117ee64f26d3a66b573bd3b799b0a014"},
+ // Pass request-local verified binding evidence to the typed writer after the locked identity/record recheck; no payload can supply evidence. One binding GET per unlabelled request.
+ {"internal/console/replicacoordinator.go", "Server.handleReplicaCoordinator", "record-writer", "key:RecordReplicaRetired,key:SetRecordCoordinator", "1030bdda0da3e8ed87662b4eb436eed8ab0f83da045c3584c1c2bcac2862b2ab"},
+ // Pass the same explicit evidence after the locked identity/record/current-term checks. The existing typed release writer remains the sole record write.
+ {"internal/console/replicacoordinator.go", "Server.handleReplicaRelease", "record-writer", "key:SetRecordReplicaRelease", "80af24346d95ee7391f62c4681a1b20110f3f8fbb0a6d9f73ef3b76cebb6979f"},
+ } {
+ for i, old := range entries {
+ if old.File == next.File && old.Unit == next.Unit {
+ entries[i] = next
+ break
+ }
+ }
+ }
+ return entries
+}
diff --git a/internal/provision/plan9_b8_census_test.go b/internal/provision/plan9_b8_census_test.go
index 57efdca44..c4287ffb8 100644
--- a/internal/provision/plan9_b8_census_test.go
+++ b/internal/provision/plan9_b8_census_test.go
@@ -366,7 +366,7 @@ func TestPlan9B8RecordWriteCensus(t *testing.T) {
if len(got) < 100 {
t.Fatalf("census found only %d units under %s; the walk is broken", len(got), root)
}
- inventory := statelessPlacementWriteCensusInventory()
+ inventory := oneBoxCoordinatorWriteCensusInventory()
problems := append(censusDiff(inventory, got), censusPolicy(inventory)...)
if len(problems) > 0 {
t.Fatalf("record-write census rejected %d site(s); update the explicit inventory only after reviewing the source:\n %s", len(problems), strings.Join(problems, "\n "))
diff --git a/internal/provision/replica_binding_test.go b/internal/provision/replica_binding_test.go
new file mode 100644
index 000000000..ae663bcdb
--- /dev/null
+++ b/internal/provision/replica_binding_test.go
@@ -0,0 +1,182 @@
+package provision
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "errors"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/replicas"
+)
+
+func TestCoordinatorBindingEvidence(t *testing.T) {
+ for _, writer := range []string{"coordinator", "release"} {
+ for _, kind := range []string{"matching", "newer", "older", "other-fleet", "other-host", "other-box", "empty-fleet", "empty-box", "missing", "duplicate"} {
+ t.Run(writer+"/"+kind, func(t *testing.T) {
+ ctx, id := replicaFixture(t)
+ s, rec := fleetBoxFixture(t)
+ id.Incarnation, _ = Incarnation(rec.Account, rec.App, rec.Host, rec.CreatedAt)
+ proof := ReplicaBindingEvidence{Fleet: "pi", Host: rec.Host, Box: "local", BoundAt: rec.CreatedAt.UnixMilli()}
+ var deploy replicas.Deploy
+ if writer == "release" {
+ got, err := SetRecordCoordinator(ctx, s, id, replicas.CoordinatorChange{Op: "acquire", Box: "local", BootID: "boot"}, time.Now(), proof)
+ if err != nil {
+ t.Fatal(err)
+ }
+ deploy = replicas.Deploy{ID: "deploy", Incarnation: id.Incarnation, Term: got.Coordinator.Term, Target: replicas.Build{Version: "v1", Digest: "digest"}, Phase: "pending"}
+ }
+ switch kind {
+ case "newer":
+ proof.BoundAt++
+ case "older":
+ proof.BoundAt--
+ case "other-fleet":
+ proof.Fleet = "away"
+ case "other-host":
+ proof.Host = "other.example.com"
+ case "other-box":
+ proof.Box = "other"
+ case "empty-fleet":
+ proof.Fleet = ""
+ case "empty-box":
+ proof.Box = ""
+ }
+ binding := []ReplicaBindingEvidence{proof}
+ if kind == "missing" {
+ binding = nil
+ } else if kind == "duplicate" {
+ binding = append(binding, proof)
+ }
+ key := RecordKey(id.Account, id.App, id.Host)
+ before, _, err := s.Get(ctx, key)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var got *Record
+ if writer == "coordinator" {
+ got, err = SetRecordCoordinator(ctx, s, id, replicas.CoordinatorChange{Op: "acquire", Box: "local", BootID: "boot"}, time.Now(), binding...)
+ } else {
+ got, err = SetRecordReplicaRelease(ctx, s, id, 0, deploy, binding...)
+ }
+ if kind == "matching" || kind == "newer" {
+ if err != nil || got.FleetBox != "" || got.FleetBoxAt != "" || got.FleetBoxMoved || got.ReplicaAssignment != nil {
+ t.Fatalf("accepted evidence: %+v, %v", got, err)
+ }
+ if writer == "release" && (got.ReplicaDeploy == nil || got.ReplicaDeploy.Phase != "pending") {
+ t.Fatal("release result was not written")
+ }
+ return
+ }
+ if !errors.Is(err, replicas.ErrFenced) {
+ t.Fatalf("invalid evidence: %v, want fenced", err)
+ }
+ after, _, err := s.Get(ctx, key)
+ if err != nil || !bytes.Equal(before, after) {
+ t.Fatalf("refused evidence changed the record: %v", err)
+ }
+ })
+ }
+ }
+}
+
+func TestCoordinatorBindingEvidenceRechecksCAS(t *testing.T) {
+ for _, writer := range []string{"coordinator", "release"} {
+ for _, kind := range []string{"labelled-same-box", "assigned-same-box", "recreated", "region"} {
+ t.Run(writer+"/"+kind, func(t *testing.T) {
+ ctx, id := replicaFixture(t)
+ base, rec := fleetBoxFixture(t)
+ id.Incarnation, _ = Incarnation(rec.Account, rec.App, rec.Host, rec.CreatedAt)
+ proof := ReplicaBindingEvidence{Fleet: "pi", Host: rec.Host, Box: "local", BoundAt: rec.CreatedAt.UnixMilli()}
+ var deploy replicas.Deploy
+ if writer == "release" {
+ got, err := SetRecordCoordinator(ctx, base, id, replicas.CoordinatorChange{Op: "acquire", Box: "local", BootID: "boot"}, time.Now(), proof)
+ if err != nil {
+ t.Fatal(err)
+ }
+ deploy = replicas.Deploy{ID: "deploy", Incarnation: id.Incarnation, Term: got.Coordinator.Term, Target: replicas.Build{Version: "v1", Digest: "digest"}, Phase: "pending"}
+ }
+ store := &replicaConflictStore{Store: base}
+ var raced []byte
+ store.hook = func(ctx context.Context, key string, _ []byte, _ string) {
+ raw, tag, err := base.Get(ctx, key)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var current Record
+ if err := json.Unmarshal(raw, &current); err != nil {
+ t.Fatal(err)
+ }
+ switch kind {
+ case "labelled-same-box":
+ current.FleetBox = "local"
+ case "assigned-same-box":
+ current.RecordSeq = 2
+ current.ReplicaAssignment = &replicas.Assignment{Revision: 1, Desired: 1, Boxes: []string{"local"}}
+ case "recreated":
+ current.CreatedAt = current.CreatedAt.Add(time.Second)
+ case "region":
+ current.Region = "fleet/away"
+ }
+ raced, err = json.Marshal(current)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := base.Put(ctx, key, raced, tag); err != nil {
+ t.Fatal(err)
+ }
+ }
+ var err error
+ if writer == "coordinator" {
+ _, err = SetRecordCoordinator(ctx, store, id, replicas.CoordinatorChange{Op: "acquire", Box: "local", BootID: "boot"}, time.Now(), proof)
+ } else {
+ _, err = SetRecordReplicaRelease(ctx, store, id, 0, deploy, proof)
+ }
+ if !errors.Is(err, replicas.ErrFenced) || len(raced) == 0 {
+ t.Fatalf("CAS retry: %v, raced %t; want fenced after conflict", err, len(raced) != 0)
+ }
+ raw, _, err := base.Get(ctx, RecordKey(id.Account, id.App, id.Host))
+ if err != nil || !bytes.Equal(raw, raced) {
+ t.Fatalf("fenced retry changed the raced record: %v", err)
+ }
+ })
+ }
+ }
+}
+
+func TestReplicaReleaseBindingEvidenceRechecksReplay(t *testing.T) {
+ ctx, id := replicaFixture(t)
+ s, rec := fleetBoxFixture(t)
+ id.Incarnation, _ = Incarnation(rec.Account, rec.App, rec.Host, rec.CreatedAt)
+ proof := ReplicaBindingEvidence{Fleet: "pi", Host: rec.Host, Box: "local", BoundAt: rec.CreatedAt.UnixMilli()}
+ got, err := SetRecordCoordinator(ctx, s, id, replicas.CoordinatorChange{Op: "acquire", Box: "local", BootID: "boot"}, time.Now(), proof)
+ if err != nil {
+ t.Fatal(err)
+ }
+ d := replicas.Deploy{ID: "deploy", Incarnation: id.Incarnation, Term: got.Coordinator.Term, Target: replicas.Build{Version: "v1", Digest: "digest"}, Phase: "pending"}
+ got, err = SetRecordReplicaRelease(ctx, s, id, 0, d, proof)
+ if err != nil {
+ t.Fatal(err)
+ }
+ d.Phase = "released"
+ got, err = SetRecordReplicaRelease(ctx, s, id, got.ReplicaDeploy.Revision, d, proof)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := SetRecordFleetBox(ctx, s, id.Account, id.App, id.Host, FleetBoxExpect{Region: rec.Region, CreatedAt: rec.CreatedAt}, "local", time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ key := RecordKey(id.Account, id.App, id.Host)
+ before, _, err := s.Get(ctx, key)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := SetRecordReplicaRelease(ctx, s, id, got.ReplicaDeploy.Revision, d, proof); !errors.Is(err, replicas.ErrFenced) {
+ t.Fatalf("labelled replay accepted old binding evidence: %v", err)
+ }
+ after, _, err := s.Get(ctx, key)
+ if err != nil || !bytes.Equal(before, after) {
+ t.Fatalf("refused replay changed record: %v", err)
+ }
+}
diff --git a/internal/provision/replicacoordinator.go b/internal/provision/replicacoordinator.go
index 569b8cb71..076f6f5a4 100644
--- a/internal/provision/replicacoordinator.go
+++ b/internal/provision/replicacoordinator.go
@@ -13,6 +13,19 @@ import (
type replicaWriteKey struct{}
+// ReplicaBindingEvidence is a binding verified by the console for this request.
+// It authorizes only an unlabelled legacy record; each CAS attempt checks it again.
+type ReplicaBindingEvidence struct {
+ Fleet, Host, Box string
+ BoundAt int64
+}
+
+func (b ReplicaBindingEvidence) matches(rec *Record, box string) bool {
+ return b.Fleet != "" && b.Box != "" && b.Host == rec.Host &&
+ rec.FleetBox == "" && rec.ReplicaAssignment == nil &&
+ rec.Region == "fleet/"+b.Fleet && b.BoundAt >= rec.CreatedAt.UnixMilli() && box == b.Box
+}
+
func replicaIdentity(rec *Record, id replicas.Identity) error {
incarnation, err := Incarnation(rec.Account, rec.App, rec.Host, rec.CreatedAt)
if err != nil || rec.Retired || id.Account != rec.Account || id.App != rec.App || id.Host != rec.Host || id.Incarnation != incarnation {
@@ -21,7 +34,7 @@ func replicaIdentity(rec *Record, id replicas.Identity) error {
return nil
}
-func SetRecordCoordinator(ctx context.Context, s release.Store, id replicas.Identity, change replicas.CoordinatorChange, now time.Time) (*Record, error) {
+func SetRecordCoordinator(ctx context.Context, s release.Store, id replicas.Identity, change replicas.CoordinatorChange, now time.Time, binding ...ReplicaBindingEvidence) (*Record, error) {
started := time.Now()
var result *Record
err := release.WithAppMutation(ctx, s, id.Account, id.App, "provision.SetRecordCoordinator", func(ctx context.Context) error {
@@ -31,6 +44,9 @@ func SetRecordCoordinator(ctx context.Context, s release.Store, id replicas.Iden
if err := replicaIdentity(rec, id); err != nil {
return err
}
+ if len(binding) != 0 && (len(binding) != 1 || !binding[0].matches(rec, change.Box)) {
+ return replicas.ErrFenced
+ }
if rec.ReplicaAssignment != nil {
if !(change.Op == "release" && rec.Coordinator != nil && rec.Coordinator.Box == change.Box) && ReplicaCoordinatorBox(rec, now.Add(time.Since(started))) != change.Box {
if change.Op == "acquire" && rec.ReplicaAssignment.Contains(change.Box) && !rec.ReplicaAssignment.HasUnknownFields() && replicas.ValidateAssignment(*rec.ReplicaAssignment) == nil {
@@ -42,7 +58,7 @@ func SetRecordCoordinator(ctx context.Context, s release.Store, id replicas.Iden
}
return replicas.ErrFenced
}
- } else if (strings.HasPrefix(rec.Region, "fleet/") && rec.FleetBox == "") || (rec.FleetBox != "" && rec.FleetBox != change.Box) {
+ } else if (strings.HasPrefix(rec.Region, "fleet/") && rec.FleetBox == "" && len(binding) == 0) || (rec.FleetBox != "" && rec.FleetBox != change.Box) {
return replicas.ErrFenced
}
next, err := replicas.ChangeCoordinator(rec.Coordinator, change, now.Add(time.Since(started)))
diff --git a/internal/provision/replicadeploy.go b/internal/provision/replicadeploy.go
index 67ccc8679..b64a97aca 100644
--- a/internal/provision/replicadeploy.go
+++ b/internal/provision/replicadeploy.go
@@ -11,7 +11,7 @@ import (
// SetRecordReplicaRelease persists one-copy release evidence through the judged
// record CAS. Every retry checks the lifetime, current term and pinned build.
-func SetRecordReplicaRelease(ctx context.Context, s release.Store, id replicas.Identity, expectedRevision uint64, next replicas.Deploy) (*Record, error) {
+func SetRecordReplicaRelease(ctx context.Context, s release.Store, id replicas.Identity, expectedRevision uint64, next replicas.Deploy, binding ...ReplicaBindingEvidence) (*Record, error) {
var result *Record
err := release.WithAppMutation(ctx, s, id.Account, id.App, "provision.SetRecordReplicaRelease", func(ctx context.Context) error {
ctx = context.WithValue(ctx, replicaWriteKey{}, "replica_deploy")
@@ -23,6 +23,9 @@ func SetRecordReplicaRelease(ctx context.Context, s release.Store, id replicas.I
if next.Incarnation != id.Incarnation || next.ID == "" || next.Term == "" || next.Target.Version == "" || next.Target.Digest == "" || len(next.Order) != 0 || len(next.Completed) != 0 || next.ActiveBox != "" {
return replicas.ErrInvalid
}
+ if len(binding) != 0 && (len(binding) != 1 || rec.Coordinator == nil || !binding[0].matches(rec, rec.Coordinator.Box)) {
+ return replicas.ErrFenced
+ }
old := rec.ReplicaDeploy
// A committed success is evidence even when its reply was lost. Do not
// advance either revision or record sequence on this exact replay.
@@ -30,7 +33,7 @@ func SetRecordReplicaRelease(ctx context.Context, s release.Store, id replicas.I
return errRecordUnchanged
}
c := rec.Coordinator
- if c == nil || c.Term != next.Term || !time.Now().Before(c.ExpiresAt) || (rec.ReplicaAssignment != nil && ReplicaCoordinatorBox(rec, time.Now()) != c.Box) || (rec.ReplicaAssignment == nil && ((rec.FleetBox != "" && rec.FleetBox != c.Box) || (rec.FleetBox == "" && len(rec.Region) >= 6 && rec.Region[:6] == "fleet/"))) {
+ if c == nil || c.Term != next.Term || !time.Now().Before(c.ExpiresAt) || (rec.ReplicaAssignment != nil && ReplicaCoordinatorBox(rec, time.Now()) != c.Box) || (rec.ReplicaAssignment == nil && ((rec.FleetBox != "" && rec.FleetBox != c.Box) || (rec.FleetBox == "" && len(rec.Region) >= 6 && rec.Region[:6] == "fleet/" && len(binding) == 0))) {
return replicas.ErrFenced
}
revision := uint64(0)
diff --git a/internal/provision/testdata/plan14-root-reads-chain.tsv b/internal/provision/testdata/plan14-root-reads-chain.tsv
index bf4021847..514f77001 100644
--- a/internal/provision/testdata/plan14-root-reads-chain.tsv
+++ b/internal/provision/testdata/plan14-root-reads-chain.tsv
@@ -82,3 +82,4 @@ plan14-root-reads-region-ha-followups.tsv cfb026f1f9d59f325937cbddf26df2d94d5240
plan14-root-reads-region-ha-p3a.tsv f44d209a054eee55fdee54227d419b74c34a9b2fc174c7a0bb74d5c2711a68bb
plan14-root-reads-stateless-coordinator-route.tsv 7974cb078e82272605cbc8ef6809c9ae5e0b02edc22ca843cd2ef4b38d9e44e9
plan14-root-reads-stateless-replicas-2.tsv 59c0891618b9befae27ebe04d0a67b08c7f7658bca9f1c78bf6d05eb7a708e82
+plan14-root-reads-stateless-coordinator-oneboxfleet.tsv 59c0891618b9befae27ebe04d0a67b08c7f7658bca9f1c78bf6d05eb7a708e82
diff --git a/internal/provision/testdata/plan14-root-reads-stateless-coordinator-oneboxfleet.tsv b/internal/provision/testdata/plan14-root-reads-stateless-coordinator-oneboxfleet.tsv
new file mode 100644
index 000000000..c0b11ade5
--- /dev/null
+++ b/internal/provision/testdata/plan14-root-reads-stateless-coordinator-oneboxfleet.tsv
@@ -0,0 +1,4 @@
+# Census overlay stateless-coordinator-oneboxfleet, written by census-propose (#369). census-ruling-stateless-coordinator-oneboxfleet, approved on #280 before the merge; the approval card is docs/superpowers/notes/census-proposal-stateless-coordinator-oneboxfleet.md.
+# 0 body, 0 sites, 1 envelope: each changed unit re-frozen at its existing disposition with its claim appended.
+@coverage internal/provision 5f3d19183457f1e05acfa7ae85301731d4f9681732ef94f52c4f57fdf58822ff
+# Proposal only: independent #280 approval remains pending with the controller.