carlos / platform Public

fix: judge replica retries before writing; halt swaps on removed boxes

Task 1 fix round 1 (review r0 findings 1-4, as amended by the controller).

- Retries (finding 2): ReplicaRetryTargets judges every affected instance
  read-only and refuses an open switch before anything is signed or
  written. The host retry arms intent after its grant and before the
  serial; promote --retry (API and proposal) arms only after
  PromoteOnLadder accepted. Arming is an idempotent replay, so running
  the same request again finishes a partial one.
- Direct-bucket promote --retry (finding 3) refuses on a channel with a
  copy assignment or a stateless replica deploy and points at the console
  (SR-4-C40, pending copy review), instead of renewing a pointer that
  would leave the failed attempt in place.
- A box removed from the assignment between an ack and its permit
  (finding 4) gets no permit: the coordinator persists a halt and stops.
- The swap order (finding 1, part) leaves out roster-active boxes whose
  heartbeat is stale (fleetBoxView.Fresh, as replicaMemberLost judges);
  per-copy app health stays with Task 3.

Record-write census updated; root-read census envelopes re-pinned
(stateless-replicas-4-task1-fix1).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev c3d74b1d97f0cc7dd17c0a942619f5a7303ecaef parent 3f856c4
18 files changed, +515 −118
  • cli.go +30 −2
  • docs/superpowers/notes/census-proposal-stateless-replicas-4-task1-fix1.md +11 −0
  • docs/superpowers/plans/2026-11-01-stateless-replicas-copy.md +2 −1
  • internal/console/apicli.go +17 −3
  • internal/console/apiretry.go +12 −5
  • internal/console/browserretry.go +2 −2
  • internal/console/pendinghandlers.go +14 −2
  • internal/console/replicadeploy.go +48 −60
  • internal/console/replicadeploy_test.go +149 −35
  • internal/host/replicadeploy.go +5 −0
  • internal/host/replicadeploy_test.go +48 −0
  • internal/provision/plan9_b8_census_test.go +2 −1
  • internal/provision/replicadeploy.go +49 −2
  • internal/provision/stateless_replicas_4_task1_census_test.go +24 −5
  • internal/provision/testdata/plan14-root-reads-chain.tsv +1 −0
  • internal/provision/testdata/plan14-root-reads-stateless-replicas-4-task1-fix1.tsv +5 −0
  • internal/replicas/deploy_test.go +1 −0
  • replica_promote_retry_test.go +95 −0

Intent

Human

<task-notification> <task-id>bxf75p58z</task-id> <tool-use-id>toolu_01JLEk8WQoeo7PTsmMmX2LVr</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/72128d15-58b8-452f-9f7e-8e864e8854d2/tasks/bxf75p58z.output</output-file> <status>completed</status> <summary>Background command "Run Astra Task 1 review" completed (exit code 0)</summary> </task-notification>

Human

OK, are we continuing with builidng stateless replicas?

Human

Fable 5.2 might have an unblocking opinion too if we want a steer on direction

Human

<task-notification> <task-id>bc9d0kcek</task-id> <tool-use-id>toolu_01SHNQQvxe7jkjkK8Pz4CCYP</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/72128d15-58b8-452f-9f7e-8e864e8854d2/tasks/bc9d0kcek.output</output-file> <status>completed</status> <summary>Background command "Ask Fable 5.2 for a scope and direction steer" completed (exit code 0)</summary> </task-notification>

Human

<paseo-system version="1" kind="agent-message" source-agent-id="09cca118-043b-44a3-94aa-a983228e744d" message-id="e0843385-131f-4fbb-9115-200ebbcc4795"> From the Tito session, answering platform-a9&apos;s two questions for #511: (1) Instances per app. On Tito staging, one instance per app: web and Sidekiq run together in it (processes.json: web plus a sidekiq worker). With --copies 2 that&apos;s 2 instances per app, one on each box of fleet classic. Apps: Classic, ID, Billing and Pro (rootfs --jit), plus imgproxy (static Go binary). (2) Does xlarge fit web plus Sidekiq per copy? On staging, yes. Resident memory at staging load: Classic about 1.1 GiB, Pro about 1.2 GiB, ID about 0.6 GiB, Billing about 0.6 GiB, imgproxy about 0.1 GiB. So for staging, v0.35.0 can ship with xlarge as the top fleet size. Don&apos;t block on 6g+. But production is a different shape. Kubernetes production today: - Classic: 20 web pods (request 1.5 GiB, limit 2 GiB, 5 threads each), 10 Sidekiq pods (2 GiB request) and 3 mailer Sidekiq pods (1 GiB). - Pro: 16 web pods (1 GiB) and 6 Sidekiq pods (2 GiB request, no limit). - ID: 3 web (1 GiB) and 1 Sidekiq (400 MiB). - Billing: 3 web (1 GiB) and 2 Sidekiq (1 GiB). So production Classic and Pro will need web and workers as separate instances (a Sidekiq process alone wants about 2 GiB), and many more than 2 copies. Production cutover needs that later, not v0.35.0. Please note it on #511 as a follow-up (separate worker instances or worker-only copies, copy counts well above 2, and per-process sizes) so it doesn&apos;t get lost. </paseo-system>

diff --git a/cli.go b/cli.go
index b92e3e5de..3145ba9ce 100644
--- a/cli.go
+++ b/cli.go
@@ -15,6 +15,7 @@ import (
"fmt"
"io"
"log"
+ "math"
"net/http"
"os"
"path/filepath"
@@ -2989,8 +2990,14 @@ func runPromote(args []string) {
if *app == "" {
log.Fatal(usage)
}
- res, err := releaseSigner().PromoteOnLadder(context.Background(), openStore(),
- acctOf(), *app, channel, version,
+ store, acctSqid := openStore(), acctOf()
+ if *retry {
+ if err := directRetryRefusal(context.Background(), store, acctSqid, *app, channel); err != nil {
+ log.Fatal(err)
+ }
+ }
+ res, err := releaseSigner().PromoteOnLadder(context.Background(), store,
+ acctSqid, *app, channel, version,
release.PromoteOptions{Hotfix: *hotfix, Retry: *retry, Actor: promoteActor()})
if err != nil {
log.Fatal(err)
@@ -4232,3 +4239,24 @@ func humanFloat(v *float64) string {
}
return fmt.Sprintf("%.2f", *v)
}
+
+// copy SR-4-C40 (provisional)
+var errDirectReplicaRetry = errors.New("this app runs stateless replicas, so retry it through the console: carlos instances retry <host>, or carlos promote --retry while logged in to the console")
+
+// directRetryRefusal refuses a direct-bucket `promote --retry` on a channel
+// that has a copy assignment or a stateless replica deploy. That retry is
+// durable intent the console writes under its record lock (stateless
+// replicas R1); a pointer renewal alone would leave the failed attempt in
+// place. An unreadable listing refuses too. Nothing is written.
+func directRetryRefusal(ctx context.Context, store release.Store, acct, app, channel string) error {
+ recs, _, err := provision.ListRecords(ctx, store, acct, app, math.MaxInt)
+ if err != nil {
+ return err
+ }
+ for _, rec := range recs {
+ if rec.Channel == channel && (rec.ReplicaAssignment != nil || rec.ReplicaDeploy != nil) {
+ return errDirectReplicaRetry
+ }
+ }
+ return nil
+}
diff --git a/docs/superpowers/notes/census-proposal-stateless-replicas-4-task1-fix1.md b/docs/superpowers/notes/census-proposal-stateless-replicas-4-task1-fix1.md
new file mode 100644
index 000000000..991c0da44
--- /dev/null
+++ b/docs/superpowers/notes/census-proposal-stateless-replicas-4-task1-fix1.md
@@ -0,0 +1,11 @@
+# Census approval: stateless-replicas-4-task1-fix1
+
+Ruling `census-ruling-stateless-replicas-4-task1-fix1`. 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/host`, `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: `3f066208f5e5fa2b9854f30118a9a2707f3a5a51bcf55ae6b0949cb0307804f5` → `3f066208f5e5fa2b9854f30118a9a2707f3a5a51bcf55ae6b0949cb0307804f5`.
+
+Overlay: `internal/provision/testdata/plan14-root-reads-stateless-replicas-4-task1-fix1.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`.
diff --git a/docs/superpowers/plans/2026-11-01-stateless-replicas-copy.md b/docs/superpowers/plans/2026-11-01-stateless-replicas-copy.md
index d216e43bf..1d01dfd6f 100644
--- a/docs/superpowers/plans/2026-11-01-stateless-replicas-copy.md
+++ b/docs/superpowers/plans/2026-11-01-stateless-replicas-copy.md
@@ -102,7 +102,7 @@ copy too. Internal wire enums are not an excuse to expose unreviewed text.
| SR-4-C28 | docs/site/stateless-replicas.md | carlos instances list prints one row per copy with its box, build, state, health and workers. carlos run and carlos console choose a healthy copy; add --box <label> to choose one. An accepted command is not repeated on another box after a lost connection. | pending |
| SR-4-C29 | docs/site/stateless-replicas.md | Fleet sizes add 6g, 12g, 24g, 48g, 96g and 192g, measured in GiB. Each copy leaves at least 1 GiB or one eighth of its box's memory for the box, whichever is larger. An overlap also needs room for the new generation. | pending |
| SR-4-C30 | docs/site/stateless-replicas.md | More than one copy needs an always-on release. Set --copies 1 and wait for removed copies to stop before selecting a hibernating release or one with a local database. Switching to stateless leaves the old database and replica untouched. | pending |
-| SR-4-C31 | internal/console/replicadeploy.go | another deploy is still finishing a copy's switch. wait for it to finish before deploying again | pending |
+| SR-4-C31 | internal/provision/replicadeploy.go | another deploy is still finishing a copy's switch. wait for it to finish before deploying again | pending |
| SR-4-C32 | scripts/stateless-replicas-drill/main.go | spread: <a_percent>% on <box_a>, <b_percent>% on <box_b>; failed reads before headers: <failures>; cut streams: <cuts>; websocket reconnect: <seconds>s | pending |
| SR-4-C33 | scripts/stateless-replicas-drill/main.go | the dev drill did not pass: <reason>. restore the stopped box and complete cleanup before closing this session | pending |
| SR-4-C34 | docs/site/stateless-replicas.md | Stateless replicas | pending |
@@ -111,3 +111,4 @@ copy too. Internal wire enums are not an excuse to expose unreviewed text.
| SR-4-C37 | internal/console/replicadeploy.go | deploy complete | pending |
| SR-4-C38 | internal/console/replicadeploy.go | release result unknown | pending |
| SR-4-C39 | internal/console/replicadeploy.go | release complete; no copy was running, so the first copy is starting on its own | pending (added by Plan 4 Task 1 for a bootstrap order; awaiting Paul's copy review) |
+| SR-4-C40 | cli.go | this app runs stateless replicas, so retry it through the console: carlos instances retry <host>, or carlos promote --retry while logged in to the console | pending (added by Plan 4 Task 1 fix round 1 for the direct-bucket retry refusal; awaiting Paul's copy review) |
diff --git a/internal/console/apicli.go b/internal/console/apicli.go
index 831f54d22..770cbb70e 100644
--- a/internal/console/apicli.go
+++ b/internal/console/apicli.go
@@ -28,6 +28,7 @@ import (
"github.com/carlosframework/platform/internal/apppolicy"
"github.com/carlosframework/platform/internal/caps"
+ "github.com/carlosframework/platform/internal/provision"
"github.com/carlosframework/platform/internal/regionlabel"
"github.com/carlosframework/platform/internal/registry"
"github.com/carlosframework/platform/internal/release"
@@ -1132,19 +1133,32 @@ func (s *Server) handleAPIPromote(w http.ResponseWriter, r *http.Request) {
return deployScopeAllows(p, pp, channel, req.Hotfix)
}
}
+ // A replicated release retry (R1) is judged before the pointer is
+ // touched, so a refusal writes nothing.
+ var retryTargets []provision.Record
if req.Retry {
- // A replicated release retry is durable before the pointer moves (R1).
- if err := s.requestReplicaRetries(ctx, acct.Sqid, app, channel, version); errors.Is(err, errReplicaSwapOpen) {
- jsonError(w, http.StatusConflict, replicaDeploySwapOpen)
+ targets, err := s.channelReplicaRetryTargets(ctx, acct.Sqid, app, channel, version)
+ if errors.Is(err, provision.ErrReplicaSwitchOpen) {
+ jsonError(w, http.StatusConflict, err.Error())
return
} else if err != nil {
log.Printf("console: api promote %s %s -> %s: replica retry: %v", app, version, channel, err)
jsonError(w, http.StatusBadGateway, apiRetryStore)
return
}
+ retryTargets = targets
}
res, err := signer.PromoteOnLadder(ctx, s.cfg.Releases, acct.Sqid, app, channel, version,
release.PromoteOptions{Actor: addr, Hotfix: hotfix, Retry: req.Retry, Authorize: authorize})
+ if err == nil && len(retryTargets) != 0 {
+ // The renewal passed its own checks; the intent lands before the
+ // serial announces it. The same request again finishes a partial one.
+ if aerr := s.armReplicaRetriesLocked(ctx, retryTargets); aerr != nil {
+ log.Printf("console: api promote %s %s -> %s: replica retry: %v", app, version, channel, aerr)
+ jsonError(w, http.StatusBadGateway, apiRetryStore)
+ return
+ }
+ }
if err != nil {
var ae *release.AuthorizationError
if errors.As(err, &ae) {
diff --git a/internal/console/apiretry.go b/internal/console/apiretry.go
index 60e34a549..bdf922b0b 100644
--- a/internal/console/apiretry.go
+++ b/internal/console/apiretry.go
@@ -116,9 +116,11 @@ func (s *Server) requestHostRetry(ctx context.Context, acct, app, host string, h
if s.cfg.Key == nil {
return release.RestartRequest{}, errRetryNoKey
}
- // A replicated release retry is durable on the record before any box is
- // told (R1): the coordinator consumes it once, whatever its book says.
- if err := s.requestReplicaRetry(ctx, acct, app, host, held.build); err != nil {
+ // A replicated release retry (R1) is judged before anything is signed,
+ // so a refusal writes nothing, and is durable on the record before any
+ // box is told. The coordinator consumes it once, whatever its book says.
+ targets, err := s.hostReplicaRetryTargets(ctx, acct, app, host, held.build)
+ if err != nil {
return release.RestartRequest{}, err
}
signed, err := release.SignHostRetry(release.RootSigner(s.cfg.Key), acct, app, host, held.build, held.book, held.epoch, time.Now())
@@ -129,6 +131,11 @@ func (s *Server) requestHostRetry(ctx context.Context, acct, app, host string, h
if err != nil {
return release.RestartRequest{}, err
}
+ if len(targets) != 0 {
+ if err := s.withRecordLock(acct, app, func() error { return s.armReplicaRetriesLocked(ctx, targets) }); err != nil {
+ return release.RestartRequest{}, err
+ }
+ }
s.bumpSerial(ctx)
return req, nil
}
@@ -190,8 +197,8 @@ func (s *Server) handleAPIInstanceRetry(w http.ResponseWriter, r *http.Request)
}
build := held.build
rr, err := s.requestHostRetry(ctx, acct.Sqid, app, host, held)
- if errors.Is(err, errReplicaSwapOpen) {
- jsonError(w, http.StatusConflict, replicaDeploySwapOpen)
+ if errors.Is(err, provision.ErrReplicaSwitchOpen) {
+ jsonError(w, http.StatusConflict, err.Error())
return
}
if err != nil {
diff --git a/internal/console/browserretry.go b/internal/console/browserretry.go
index d4d6c1106..17bb56f46 100644
--- a/internal/console/browserretry.go
+++ b/internal/console/browserretry.go
@@ -98,8 +98,8 @@ func (s *Server) handleInstanceRetry(w http.ResponseWriter, r *http.Request) {
flash("err", swapCopy.RetryLimited)
return
}
- if _, err := s.requestHostRetry(ctx, acct.Sqid, app, host, held); errors.Is(err, errReplicaSwapOpen) {
- flash("err", replicaDeploySwapOpen)
+ if _, err := s.requestHostRetry(ctx, acct.Sqid, app, host, held); errors.Is(err, provision.ErrReplicaSwitchOpen) {
+ flash("err", err.Error())
return
} else if err != nil {
log.Printf("console: browser retry %s/%s/%s: %v", acct.Sqid, app, host, err)
diff --git a/internal/console/pendinghandlers.go b/internal/console/pendinghandlers.go
index 453499fcd..d38c1f6b2 100644
--- a/internal/console/pendinghandlers.go
+++ b/internal/console/pendinghandlers.go
@@ -36,6 +36,7 @@ import (
"strings"
"time"
+ "github.com/carlosframework/platform/internal/provision"
"github.com/carlosframework/platform/internal/release"
)
@@ -570,17 +571,28 @@ func (s *Server) executePendingPromote(ctx context.Context, acct *Account, app,
if ref := s.copiesPublicationRefusal(ctx, acct, app, nil, p.Version, false); ref != nil {
return "", &statelessSelectionError{ref}
}
+ // A replicated release retry (R1) is judged before the pointer is
+ // touched, so a refusal writes nothing.
+ var retryTargets []provision.Record
if p.Retry {
- // A replicated release retry is durable before the pointer moves (R1).
- if err := s.requestReplicaRetries(ctx, acct.Sqid, app, p.Channel, p.Version); errors.Is(err, errReplicaSwapOpen) {
+ targets, err := s.channelReplicaRetryTargets(ctx, acct.Sqid, app, p.Channel, p.Version)
+ if errors.Is(err, provision.ErrReplicaSwitchOpen) {
return "", err
} else if err != nil {
log.Printf("console: execute promote %s %s -> %s: replica retry: %v", app, p.Version, p.Channel, err)
return "", errors.New(apiRetryStore)
}
+ retryTargets = targets
}
res, err := release.PromoteOnLadder(ctx, s.cfg.Releases, s.cfg.Key, acct.Sqid, app, p.Channel, p.Version,
release.PromoteOptions{Actor: actor, Hotfix: p.Hotfix, Retry: p.Retry})
+ if err == nil && len(retryTargets) != 0 {
+ // The intent lands before the serial announces the renewal.
+ if aerr := s.armReplicaRetriesLocked(ctx, retryTargets); aerr != nil {
+ log.Printf("console: execute promote %s %s -> %s: replica retry: %v", app, p.Version, p.Channel, aerr)
+ return "", errors.New(apiRetryStore)
+ }
+ }
if err != nil {
log.Printf("console: execute promote %s %s -> %s: %v", app, p.Version, p.Channel, err)
return "", err
diff --git a/internal/console/replicadeploy.go b/internal/console/replicadeploy.go
index b3bda6ca4..29742ae85 100644
--- a/internal/console/replicadeploy.go
+++ b/internal/console/replicadeploy.go
@@ -4,6 +4,7 @@ import (
"context"
"errors"
"fmt"
+ "math"
"net/http"
"slices"
"time"
@@ -34,14 +35,8 @@ const (
replicaDeployHalted = "this copy's switch has not been confirmed. other copies keep serving and the deploy is stopped"
// copy SR-4-C37 (provisional)
replicaDeployDone = "deploy complete"
- // copy SR-4-C31 (provisional)
- replicaDeploySwapOpen = "another deploy is still finishing a copy's switch. wait for it to finish before deploying again"
)
-// errReplicaSwapOpen refuses an explicit retry while a copy's switch is
-// unresolved: the new attempt could not start until its box answers.
-var errReplicaSwapOpen = errors.New(replicaDeploySwapOpen)
-
// replicaDeployStatus is the one-line deploy state of a record with a copy
// assignment, or "" for a record whose deploys do not switch box by box.
func replicaDeployStatus(rec provision.Record) string {
@@ -112,7 +107,7 @@ func (s *Server) handleReplicaDeploy(w http.ResponseWriter, r *http.Request) {
}
if change.Op == "order" {
var err error
- if change.Order, change.Bootstrap, err = s.replicaDeployOrder(*current, box); err != nil {
+ if change.Order, change.Bootstrap, err = s.replicaDeployOrder(r.Context(), *current, box); err != nil {
return err
}
}
@@ -142,13 +137,16 @@ func (s *Server) handleReplicaDeploy(w http.ResponseWriter, r *http.Request) {
}
// replicaDeployOrder is the swap order: the record's assigned boxes that
-// the fleet roster lists as active, in label order, which leaves out boxes
-// already down and keeps the coordinator in its normal place. With none
-// active the coordinator's own copy starts first, alone, as a bootstrap.
-func (s *Server) replicaDeployOrder(rec provision.Record, coordinator string) ([]string, bool, error) {
+// the fleet roster lists as active and whose heartbeat is fresh
+// (fleetBoxView.Fresh, as replicaMemberLost judges a member), in label
+// order. A box already down, or active but silent, is left out and gets no
+// permit; the coordinator keeps its normal place. With no such box the
+// coordinator's own copy starts first, alone, as a bootstrap. Heartbeats
+// that cannot be read whole refuse.
+func (s *Server) replicaDeployOrder(ctx context.Context, rec provision.Record, coordinator string) ([]string, bool, error) {
a := rec.ReplicaAssignment
fleet, ok := registry.FleetPlacement(rec.Region)
- if a == nil || !ok {
+ if a == nil || !ok || s.cfg.Releases == nil {
return nil, false, replicas.ErrFenced
}
reg, err := openRegistry(s.cfg.Registry)
@@ -159,10 +157,24 @@ func (s *Server) replicaDeployOrder(rec provision.Record, coordinator string) ([
if err != nil {
return nil, false, err
}
- var order []string
+ var views []fleetBoxView
for _, b := range boxes {
if b.Status == "active" && a.Contains(b.Label) {
- order = append(order, b.Label)
+ views = append(views, fleetBoxViewOf(b))
+ }
+ }
+ hbs, complete, err := s.loadBoxes(ctx, s.cfg.Releases, "fleets/"+fleet+"/")
+ if err != nil {
+ return nil, false, err
+ }
+ if !complete {
+ return nil, false, replicas.ErrFenced
+ }
+ joinBeats(views, hbs, time.Now())
+ var order []string
+ for _, v := range views {
+ if v.Fresh {
+ order = append(order, v.Label)
}
}
slices.Sort(order)
@@ -176,56 +188,32 @@ func (s *Server) replicaDeployOrder(rec provision.Record, coordinator string) ([
return order, false, nil
}
-// requestReplicaRetryLocked durably asks for one explicit retry of rec's
-// replicated release attempt for build (R1): the coordinator consumes it
-// once by starting a new attempt. A record with nothing to retry is left
-// alone. The caller holds the app lock.
-func (s *Server) requestReplicaRetryLocked(ctx context.Context, rec provision.Record, build string) error {
- d := rec.ReplicaDeploy
- if d == nil || d.Target.Version != build {
- return nil
- }
- if d.PermitOutstanding() {
- return errReplicaSwapOpen
- }
- if !replicas.Retryable(d) || replicas.RetryRequested(d) {
- return nil
- }
- inc, err := provision.Incarnation(rec.Account, rec.App, rec.Host, rec.CreatedAt)
+// hostReplicaRetryTargets is the read-only half of `carlos instances
+// retry` and the instance page's Retry for a replicated release (R1): it
+// refuses an open switch before anything is written or signed.
+func (s *Server) hostReplicaRetryTargets(ctx context.Context, acct, app, host, build string) ([]provision.Record, error) {
+ rec, _, err := s.readRecord(ctx, acct, app, host)
if err != nil {
- return err
+ return nil, err
}
- id := replicas.Identity{Account: rec.Account, App: rec.App, Host: rec.Host, Incarnation: inc}
- _, err = provision.RequestRecordReplicaRetry(ctx, s.cfg.Releases, id, d.ID)
- return err
-}
-
-// requestReplicaRetry is requestReplicaRetryLocked for one host, under the
-// record lock: `carlos instances retry` and the instance page's Retry.
-func (s *Server) requestReplicaRetry(ctx context.Context, acct, app, host, build string) error {
- return s.withRecordLock(acct, app, func() error {
- rec, _, err := s.readRecord(ctx, acct, app, host)
- if err != nil {
- return err
- }
- return s.requestReplicaRetryLocked(ctx, *rec, build)
- })
+ return provision.ReplicaRetryTargets([]provision.Record{*rec}, "", build)
}
-// requestReplicaRetries is requestReplicaRetryLocked for every instance
-// on channel: `carlos promote --retry`. The caller holds the app lock.
-func (s *Server) requestReplicaRetries(ctx context.Context, acct, app, channel, build string) error {
- recs, _, err := s.listRecords(ctx, acct, app, instanceListMax)
+// channelReplicaRetryTargets is the read-only half of `carlos promote
+// --retry`: every instance on channel whose replicated attempt for build
+// would be retried. The caller holds the app lock.
+func (s *Server) channelReplicaRetryTargets(ctx context.Context, acct, app, channel, build string) ([]provision.Record, error) {
+ recs, _, err := s.listRecords(ctx, acct, app, math.MaxInt)
if err != nil {
- return err
- }
- for _, rec := range recs {
- if rec.Channel != channel || rec.Pin != "" {
- continue
- }
- if err := s.requestReplicaRetryLocked(ctx, rec, build); err != nil {
- return err
- }
+ return nil, err
}
- return nil
+ return provision.ReplicaRetryTargets(recs, channel, build)
+}
+
+// armReplicaRetriesLocked writes the retry intent once the door's own
+// preconditions passed and before any box is told. Running the same
+// request again finishes a partly written one. The caller holds the app
+// lock.
+func (s *Server) armReplicaRetriesLocked(ctx context.Context, targets []provision.Record) error {
+ return provision.RequestReplicaRetries(ctx, s.cfg.Releases, targets)
}
diff --git a/internal/console/replicadeploy_test.go b/internal/console/replicadeploy_test.go
index f4305d126..96cb7af38 100644
--- a/internal/console/replicadeploy_test.go
+++ b/internal/console/replicadeploy_test.go
@@ -4,6 +4,8 @@ import (
"context"
"encoding/json"
"errors"
+ "net/http"
+ "reflect"
"slices"
"strings"
"sync/atomic"
@@ -11,7 +13,9 @@ import (
"time"
"github.com/carlosframework/platform/internal/provision"
+ "github.com/carlosframework/platform/internal/release"
"github.com/carlosframework/platform/internal/replicas"
+ "github.com/carlosframework/platform/internal/status"
)
// replicaDeployFixture is the fleet API fixture with shop's record assigned
@@ -35,6 +39,8 @@ func replicaDeployFixture(t *testing.T) (fx *interactiveFx, b1, b2, inc, term st
if err := reg.SetFleetBoxStatus("home", "b2", "active"); err != nil {
t.Fatal(err)
}
+ replicaBeat(t, fx, "b1", time.Now())
+ replicaBeat(t, fx, "b2", time.Now())
replaceRecord(t, fx, func(r *provision.Record) {
r.ReplicaAssignment = &replicas.Assignment{Revision: r.RecordSeq, Desired: 2, Boxes: []string{"b1", "b2"}}
})
@@ -61,6 +67,14 @@ func replicaDeployFixture(t *testing.T) (fx *interactiveFx, b1, b2, inc, term st
return fx, b1, b2, inc, term
}
+// replicaBeat writes box's heartbeat in fleet home, generated at.
+func replicaBeat(t *testing.T, fx *interactiveFx, box string, at time.Time) {
+ t.Helper()
+ if err := status.WriteBox(context.Background(), release.NewPrefixStore(fx.rel, "fleets/home/"), status.Box{Label: box, GeneratedAt: at}); err != nil {
+ t.Fatal(err)
+ }
+}
+
func replaceRecord(t *testing.T, fx *interactiveFx, f func(*provision.Record)) {
t.Helper()
key := provision.RecordKey(fx.acct, "shop", ixHost)
@@ -153,33 +167,42 @@ func TestReplicaDeployFleetAPIConsole(t *testing.T) {
}
}
-// TestReplicaDeployOrderOmitsDownBoxes: a box the roster no longer lists as
-// active is left out of the order; with none active the coordinator's own
-// copy starts alone and is reported as a bootstrap.
+// TestReplicaDeployOrderOmitsDownBoxes: a box the roster no longer lists
+// as active, or one still active whose heartbeat went stale, is left out of
+// the order and gets no permit; with none up the coordinator's own copy
+// starts alone and is reported as a bootstrap, through the API.
func TestReplicaDeployOrderOmitsDownBoxes(t *testing.T) {
- fx, _, _, _, _ := replicaDeployFixture(t)
- rec, _ := ixRecord(t, fx, ixHost)
- reg, err := openRegistry(fx.regPath)
- if err != nil {
- t.Fatal(err)
- }
- if err := reg.SetFleetBoxStatus("home", "b2", "detached"); err != nil {
- t.Fatal(err)
- }
- order, bootstrap, err := fx.srv.replicaDeployOrder(rec, "b1")
- if err != nil || bootstrap || !slices.Equal(order, []string{"b1"}) {
- t.Fatalf("down box ordered: %v %t %v", order, bootstrap, err)
- }
- if err := reg.SetFleetBoxStatus("home", "b1", "detached"); err != nil {
- t.Fatal(err)
- }
- order, bootstrap, err = fx.srv.replicaDeployOrder(rec, "b1")
- if err != nil || !bootstrap || !slices.Equal(order, []string{"b1"}) {
- t.Fatalf("bootstrap: %v %t %v", order, bootstrap, err)
- }
- rec.ReplicaDeploy.Swap = replicas.Swap{Order: order, Bootstrap: true}
- if replicaDeployStatus(rec) != replicaDeployBootstrap {
- t.Fatal("bootstrap reported as a rolling deploy")
+ for _, down := range []string{"detached", "stale"} {
+ t.Run(down, func(t *testing.T) {
+ fx, b1, _, inc, term := replicaDeployFixture(t)
+ reg, err := openRegistry(fx.regPath)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if down == "detached" {
+ if err := reg.SetFleetBoxStatus("home", "b2", "detached"); err != nil {
+ t.Fatal(err)
+ }
+ } else {
+ replicaBeat(t, fx, "b2", time.Now().Add(-time.Hour))
+ }
+ rec, _ := ixRecord(t, fx, ixHost)
+ order, bootstrap, err := fx.srv.replicaDeployOrder(context.Background(), rec, "b1")
+ if err != nil || bootstrap || !slices.Equal(order, []string{"b1"}) {
+ t.Fatalf("down box ordered: %v %t %v", order, bootstrap, err)
+ }
+ // Nothing is up: the coordinator's copy bootstraps alone.
+ replicaBeat(t, fx, "b1", time.Now().Add(-time.Hour))
+ code, raw := replicaPost(t, fx, "/api/fleet/replicas/"+fx.acct+"/shop/"+ixHost+"/deploy", "home/b1", b1, map[string]any{"incarnation": inc, "op": "order", "id": "deploy-1", "term": term, "revision": rec.ReplicaDeploy.Revision, "target": replicas.Build{Version: "v1", Digest: "digest"}})
+ var d replicas.Deploy
+ if code != 200 || json.Unmarshal(raw, &d) != nil || !d.Swap.Bootstrap || !slices.Equal(d.Swap.Order, []string{"b1"}) {
+ t.Fatalf("bootstrap: %d %s", code, raw)
+ }
+ got, _ := ixRecord(t, fx, ixHost)
+ if replicaDeployStatus(got) != replicaDeployBootstrap {
+ t.Fatal("bootstrap reported as a rolling deploy")
+ }
+ })
}
}
@@ -212,7 +235,7 @@ func TestReplicaReleaseOldBoxFreshIDRefusedConsole(t *testing.T) {
t.Fatalf("old box started a second run: %d %s", code, raw)
}
rec, _ := ixRecord(t, fx, ixHost)
- err := fx.srv.requestReplicaRetry(context.Background(), fx.acct, "shop", ixHost, "v1")
+ _, err := fx.srv.requestHostRetry(context.Background(), fx.acct, "shop", ixHost, heldRestriction{build: "v1", book: "book", epoch: 1})
if end == "released" {
after, _ := ixRecord(t, fx, ixHost)
if err != nil || after.RecordSeq != rec.RecordSeq {
@@ -238,24 +261,25 @@ func TestReplicaReleaseOldBoxFreshIDRefusedConsole(t *testing.T) {
// TestReplicaRetryRefusedWhileSwitchOpen: an explicit retry, host or
// app-wide, is refused with SR-4-C31 while a copy's switch is unresolved,
-// and writes nothing.
+// and writes nothing: no retry intent, no signed grant, no pointer.
func TestReplicaRetryRefusedWhileSwitchOpen(t *testing.T) {
fx, _, _, _, _ := replicaDeployFixture(t)
replaceRecord(t, fx, func(r *provision.Record) {
r.ReplicaDeploy.Swap = replicas.Swap{Order: []string{"b1", "b2"}, ActiveBox: "b2", Permit: r.ReplicaDeploy.Revision, Halted: true}
})
- before, raw := ixRecord(t, fx, ixHost)
- err := fx.srv.requestReplicaRetry(context.Background(), fx.acct, "shop", ixHost, "v1")
- if !errors.Is(err, errReplicaSwapOpen) || err.Error() != replicaDeploySwapOpen {
+ before, _ := ixRecord(t, fx, ixHost)
+ bucket := bucketSnapshot(t, fx.rel)
+ _, err := fx.srv.requestHostRetry(context.Background(), fx.acct, "shop", ixHost, heldRestriction{build: "v1", book: "book", epoch: 1})
+ if !errors.Is(err, provision.ErrReplicaSwitchOpen) || !strings.Contains(err.Error(), "another deploy is still finishing a copy's switch") {
t.Fatalf("host retry: %v", err)
}
unlock := fx.srv.lockApp(fx.acct, "shop")
- err = fx.srv.requestReplicaRetries(context.Background(), fx.acct, "shop", before.Channel, "v1")
+ _, err = fx.srv.channelReplicaRetryTargets(context.Background(), fx.acct, "shop", before.Channel, "v1")
unlock()
- if !errors.Is(err, errReplicaSwapOpen) {
+ if !errors.Is(err, provision.ErrReplicaSwitchOpen) {
t.Fatalf("promote retry: %v", err)
}
- if _, after := ixRecord(t, fx, ixHost); string(after) != string(raw) {
+ if after := bucketSnapshot(t, fx.rel); !reflect.DeepEqual(after, bucket) {
t.Fatal("refused retry wrote")
}
if !strings.Contains(replicaDeployStatus(before), "not been confirmed") {
@@ -294,10 +318,100 @@ func TestReplicaDeployWritesHoldTheAppLock(t *testing.T) {
t.Fatalf("order: %d %s", code, raw)
}
replaceRecord(t, fx, func(r *provision.Record) { r.ReplicaDeploy.Phase = "failed"; r.ReplicaDeploy.Swap = replicas.Swap{} })
- if err := fx.srv.requestReplicaRetry(context.Background(), fx.acct, "shop", ixHost, "v1"); err != nil {
+ if _, err := fx.srv.requestHostRetry(context.Background(), fx.acct, "shop", ixHost, heldRestriction{build: "v1", book: "book", epoch: 1}); err != nil {
t.Fatal(err)
}
if writes.Load() != 2 || unlocked.Load() != 0 {
t.Fatalf("writes %d, without the app lock %d", writes.Load(), unlocked.Load())
}
}
+
+// promoteRetryWorld is titogo with abc1234 on canary/x and two instances on
+// that channel whose replicated attempts for abc1234 are a and b.
+func promoteRetryWorld(t *testing.T) (fx *consoleFixture, token, url string, put func(host string, d replicas.Deploy)) {
+ t.Helper()
+ fx = newConsoleFixture(t)
+ if _, err := fx.st.CreateAppIn(OpsAccountID, "titogo", "paul@keymail.dev", time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ shipVersion(t, fx, "titogo", "abc1234")
+ shipVersion(t, fx, "titogo", "def5678")
+ token = cliToken(t, fx, "paul@keymail.dev", "code-replica-promote-retry")
+ url = fx.ts.URL + "/api/cli/apps/bab/titogo/promote"
+ if status, out := postJSON(t, url, map[string]string{"version": "abc1234", "channel": "canary/x"}, token); status != http.StatusOK {
+ t.Fatalf("promote = %d %v", status, out)
+ }
+ put = func(host string, d replicas.Deploy) {
+ t.Helper()
+ ctx := context.Background()
+ key := provision.RecordKey(release.OpsAccount, "titogo", host)
+ raw, etag, err := fx.rel.Get(ctx, key)
+ if err != nil {
+ rec := provision.Record{Schema: 1, Account: release.OpsAccount, App: "titogo", Host: host, Slug: strings.SplitN(host, ".", 2)[0], Channel: "canary/x", CreatedAt: time.Date(2026, 11, 1, 0, 0, 0, 0, time.UTC)}
+ if err := provision.CreateRecord(provision.WithRecordSequence(ctx), fx.rel, rec); err != nil {
+ t.Fatal(err)
+ }
+ raw, etag, err = fx.rel.Get(ctx, key)
+ if err != nil {
+ t.Fatal(err)
+ }
+ }
+ var rec provision.Record
+ if err := json.Unmarshal(raw, &rec); err != nil {
+ t.Fatal(err)
+ }
+ d.Incarnation, _ = provision.Incarnation(rec.Account, rec.App, rec.Host, rec.CreatedAt)
+ rec.ReplicaDeploy = &d
+ raw, _ = json.Marshal(rec)
+ if _, err := fx.rel.Put(ctx, key, raw, etag); err != nil {
+ t.Fatal(err)
+ }
+ }
+ return fx, token, url, put
+}
+
+// TestReplicaPromoteRetryRefusalWritesNothing: `carlos promote --retry`
+// judges every affected instance and the ladder before it arms any retry.
+// An open switch on one instance, or a renewal the ladder refuses, leaves
+// the bucket exactly as it was; an accepted retry arms every failed
+// attempt on the channel before the serial is bumped.
+func TestReplicaPromoteRetryRefusalWritesNothing(t *testing.T) {
+ fx, token, url, put := promoteRetryWorld(t)
+ failed := replicas.Deploy{ID: "deploy-a", Target: replicas.Build{Version: "abc1234", Digest: "d"}, Phase: "failed", Term: "t", Revision: 3}
+ put("a.titogo.example.com", failed)
+ open := failed
+ open.ID, open.Phase, open.Swap = "deploy-b", "released", replicas.Swap{Order: []string{"pi-1"}, ActiveBox: "pi-1", Permit: 3}
+ put("b.titogo.example.com", open)
+ before := bucketSnapshot(t, fx.rel)
+ status, out := postJSON(t, url, map[string]any{"version": "abc1234", "channel": "canary/x", "retry": true}, token)
+ if status != http.StatusConflict || !strings.Contains(str(t, out, "error"), "another deploy is still finishing a copy's switch") {
+ t.Fatalf("open switch: %d %v", status, out)
+ }
+ if !reflect.DeepEqual(bucketSnapshot(t, fx.rel), before) {
+ t.Fatal("a refused retry armed an instance or moved the pointer")
+ }
+ // The ladder refuses a renewal of a version the channel does not name.
+ put("b.titogo.example.com", replicas.Deploy{ID: "deploy-b", Target: replicas.Build{Version: "def5678", Digest: "d"}, Phase: "failed", Term: "t", Revision: 3})
+ put("a.titogo.example.com", failed)
+ before = bucketSnapshot(t, fx.rel)
+ status, out = postJSON(t, url, map[string]any{"version": "def5678", "channel": "canary/x", "retry": true}, token)
+ if status == http.StatusOK {
+ t.Fatalf("ladder accepted a renewal of a version the channel does not name: %v", out)
+ }
+ if !reflect.DeepEqual(bucketSnapshot(t, fx.rel), before) {
+ t.Fatal("a ladder refusal armed a retry")
+ }
+ // Accepted: the failed attempt on the channel is armed, the other build's is not.
+ status, out = postJSON(t, url, map[string]any{"version": "abc1234", "channel": "canary/x", "retry": true}, token)
+ if status != http.StatusOK {
+ t.Fatalf("retry = %d %v", status, out)
+ }
+ a, err := provision.GetRecord(context.Background(), fx.rel, release.OpsAccount, "titogo", "a.titogo.example.com")
+ if err != nil || !replicas.RetryRequested(a.ReplicaDeploy) {
+ t.Fatalf("accepted retry did not arm a: %+v %v", a, err)
+ }
+ b, err := provision.GetRecord(context.Background(), fx.rel, release.OpsAccount, "titogo", "b.titogo.example.com")
+ if err != nil || replicas.RetryRequested(b.ReplicaDeploy) {
+ t.Fatalf("another build was armed: %+v %v", b, err)
+ }
+}
diff --git a/internal/host/replicadeploy.go b/internal/host/replicadeploy.go
index 6c4a39353..78121d254 100644
--- a/internal/host/replicadeploy.go
+++ b/internal/host/replicadeploy.go
@@ -136,6 +136,11 @@ func replicaDeployStep(rec provision.Record, box, term string) (replicas.DeployC
switch next := d.Swap.NextSwapBox(); {
case len(d.Swap.Order) == 0:
change.Op = "order"
+ case next != "" && !a.Contains(next):
+ // The box left the assignment after the order was made. The writer
+ // would refuse its permit, so the deploy stops here, durably; an
+ // explicit retry starts a new attempt over the current members.
+ change.Op = "halt"
case next != "":
change.Op, change.Grant = "permit", next
default:
diff --git a/internal/host/replicadeploy_test.go b/internal/host/replicadeploy_test.go
index 30f135c49..31cc01ba7 100644
--- a/internal/host/replicadeploy_test.go
+++ b/internal/host/replicadeploy_test.go
@@ -25,6 +25,20 @@ type deployStoreWorld struct {
term string
}
+// reassign replaces the assignment, as console placement does between permits.
+func (w *deployStoreWorld) reassign(next replicas.Assignment) {
+ w.t.Helper()
+ rec := w.record()
+ ctx, err := provision.WithReplicaAssignmentManifest(provision.WithRecordSequence(context.Background()), rec, &release.Manifest{Schema: 1, App: "shop", Version: "v2", Kind: "binary", Stateless: true})
+ if err != nil {
+ w.t.Fatal(err)
+ }
+ next.Revision = rec.ReplicaAssignment.Revision
+ if _, err := provision.SetRecordReplicaAssignment(ctx, w.s, w.id, replicas.Expect{Incarnation: w.id.Incarnation, Region: rec.Region, RecordSeq: rec.RecordSeq, Revision: rec.ReplicaAssignment.Revision}, next); err != nil {
+ w.t.Fatal(err)
+ }
+}
+
func newDeployStoreWorld(t *testing.T) *deployStoreWorld {
t.Helper()
ctx := provision.WithRecordSequence(context.Background())
@@ -250,3 +264,37 @@ func TestReplicaDeployPermitReachesWorkerThroughReconcile(t *testing.T) {
t.Fatal("the permit never reached the box's worker")
}
}
+
+// TestReplicaDeployWorkerHaltsOnRemovedBox: a box placement removes
+// between an ack and the next permit is never asked for; the coordinator
+// persists a halt and stops there, leaving the attempt to an explicit retry.
+func TestReplicaDeployWorkerHaltsOnRemovedBox(t *testing.T) {
+ w := newDeployStoreWorld(t)
+ client := &deployStoreClient{w: w}
+ worker := newReplicaDeployWorker(client, "a", nil)
+ worker.terms = fixedTerm(w.term)
+ pass := func() {
+ worker.Note(w.record())
+ worker.Pass(context.Background())
+ }
+ pass() // order
+ pass() // permit a
+ w.ack("a")
+ // Placement removes b between a's ack and b's permit.
+ w.reassign(replicas.Assignment{Desired: 1, Boxes: []string{"a"}, Retiring: []string{"b"}})
+ pass()
+ d := w.record().ReplicaDeploy
+ if !d.Swap.Halted || d.Swap.ActiveBox != "" || d.Phase != "released" || !slices.Equal(d.Swap.Completed, []string{"a"}) || !replicas.Retryable(d) {
+ t.Fatalf("removed box did not halt the deploy: %+v", d)
+ }
+ calls := len(client.calls)
+ pass()
+ if len(client.calls) != calls {
+ t.Fatal("a halted deploy kept moving")
+ }
+ for _, c := range client.calls {
+ if c.Op == "permit" && c.Grant == "b" {
+ t.Fatal("a permit was asked for a removed box")
+ }
+ }
+}
diff --git a/internal/provision/plan9_b8_census_test.go b/internal/provision/plan9_b8_census_test.go
index e1e4d21cc..bb82926e7 100644
--- a/internal/provision/plan9_b8_census_test.go
+++ b/internal/provision/plan9_b8_census_test.go
@@ -53,7 +53,7 @@ var censusMethods = map[string]bool{
// typed-record-writer touchpoint. Keep these names aligned with the APIs above.
var (
censusKeySuffixes = []string{"recordkey", "recordsprefix", "sidecarsprefix", "sidecarkey", "sidecarmanifestkey", "writerecord", "sequencedrecord"}
- censusKeyExact = map[string]bool{"createrecord": true, "updaterecord": true, "setrecordregion": true, "setrecordmove": true, "setrecordrun": true, "setrecordinteractive": true, "setrecordseed": true, "setrecordfleetbox": true, "setrecordcoordinator": true, "setrecordreplicarelease": true, "setrecordreplicaassignment": true, "recordreplicaretired": true, "clearrecordreplicaassignment": true, "haltrecordreplicadeploy": true, "setrecordreplicadeploy": true, "requestrecordreplicaretry": true, "setrecordassetgen": true, "mintrecordassetgen": true, "createsidecarrecord": true, "claimrawupdaterecord": true}
+ censusKeyExact = map[string]bool{"createrecord": true, "updaterecord": true, "setrecordregion": true, "setrecordmove": true, "setrecordrun": true, "setrecordinteractive": true, "setrecordseed": true, "setrecordfleetbox": true, "setrecordcoordinator": true, "setrecordreplicarelease": true, "setrecordreplicaassignment": true, "recordreplicaretired": true, "clearrecordreplicaassignment": true, "haltrecordreplicadeploy": true, "setrecordreplicadeploy": true, "requestrecordreplicaretry": true, "requestreplicaretries": true, "setrecordassetgen": true, "mintrecordassetgen": true, "createsidecarrecord": true, "claimrawupdaterecord": true}
censusLitWords = []string{"instances", "sidecars"}
)
@@ -428,6 +428,7 @@ func Reviewed(ctx context.Context, s Store, k string) error {
{"retirement writer callsite", base + "\nfunc Retired() { provision.RecordReplicaRetired() }\n", "unlisted site x.go:Retired [key:RecordReplicaRetired]"},
{"swap writer callsite", base + "\nfunc Swapped() { provision.SetRecordReplicaDeploy() }\n", "unlisted site x.go:Swapped [key:SetRecordReplicaDeploy]"},
{"retry request callsite", base + "\nfunc Retried() { provision.RequestRecordReplicaRetry() }\n", "unlisted site x.go:Retried [key:RequestRecordReplicaRetry]"},
+ {"retry batch callsite", base + "\nfunc Batched() { provision.RequestReplicaRetries() }\n", "unlisted site x.go:Batched [key:RequestReplicaRetries]"},
{"record path literal", base + "\nfunc Lit(h string) string { return \"apps/a/b/instances/\" + h + \".json\" }\n", "unlisted site x.go:Lit [lit:instances]"},
{"sidecar path literal", base + "\nconst sidecarDir = \"sidecars\"\n", "unlisted site x.go:const sidecarDir [lit:sidecars]"},
{"reflective name", base + "\nfunc Reflect(v any) { _ = reflect.ValueOf(v).MethodByName(\"Put\") }\n", "unlisted site x.go:Reflect [str:Put]"},
diff --git a/internal/provision/replicadeploy.go b/internal/provision/replicadeploy.go
index 5caa58197..aad05e6e3 100644
--- a/internal/provision/replicadeploy.go
+++ b/internal/provision/replicadeploy.go
@@ -2,6 +2,7 @@ package provision
import (
"context"
+ "errors"
"math"
"slices"
"time"
@@ -141,7 +142,7 @@ func SetRecordReplicaDeploy(ctx context.Context, s release.Store, id replicas.Id
return replicas.ErrInvalid
}
}
- if change.Grant != "" && !a.Contains(change.Grant) {
+ if change.Op == "permit" && !a.Contains(change.Grant) {
return replicas.ErrInvalid
}
next, err := replicas.NextDeploy(*d, change, coordinator, at)
@@ -177,7 +178,7 @@ func RequestRecordReplicaRetry(ctx context.Context, s release.Store, id replicas
return errRecordUnchanged
}
if d.PermitOutstanding() {
- return replicas.ErrFenced
+ return ErrReplicaSwitchOpen
}
if !replicas.Retryable(d) || d.Revision == math.MaxUint64 {
return replicas.ErrInvalid
@@ -192,3 +193,49 @@ func RequestRecordReplicaRetry(ctx context.Context, s release.Store, id replicas
})
return result, err
}
+
+// ErrReplicaSwitchOpen refuses an explicit retry while a copy's switch is
+// unresolved: the new attempt could not start until its box answers.
+// copy SR-4-C31 (provisional)
+var ErrReplicaSwitchOpen = errors.New("another deploy is still finishing a copy's switch. wait for it to finish before deploying again")
+
+// ReplicaRetryTargets is the read-only half of an explicit retry of build:
+// the records among recs (on channel and unpinned, unless channel is "")
+// whose replicated attempt for build can be retried and is not yet asked
+// for. It refuses with ErrReplicaSwitchOpen, having written nothing, when
+// any record it would retry has an unresolved permit, so a refused retry
+// never leaves part of its intent behind.
+func ReplicaRetryTargets(recs []Record, channel, build string) ([]Record, error) {
+ var out []Record
+ for _, rec := range recs {
+ d := rec.ReplicaDeploy
+ if d == nil || d.Target.Version != build || (channel != "" && (rec.Channel != channel || rec.Pin != "")) {
+ continue
+ }
+ if d.PermitOutstanding() {
+ return nil, ErrReplicaSwitchOpen
+ }
+ if replicas.Retryable(d) && !replicas.RetryRequested(d) {
+ out = append(out, rec)
+ }
+ }
+ return out, nil
+}
+
+// RequestReplicaRetries arms the retries ReplicaRetryTargets chose, after
+// the caller's own preconditions passed. Each write is an idempotent replay
+// of the same request, so a caller that fails part way through runs the
+// same request again to finish it.
+func RequestReplicaRetries(ctx context.Context, s release.Store, targets []Record) error {
+ for _, rec := range targets {
+ inc, err := Incarnation(rec.Account, rec.App, rec.Host, rec.CreatedAt)
+ if err != nil {
+ return err
+ }
+ id := replicas.Identity{Account: rec.Account, App: rec.App, Host: rec.Host, Incarnation: inc}
+ if _, err := RequestRecordReplicaRetry(ctx, s, id, rec.ReplicaDeploy.ID); err != nil {
+ return err
+ }
+ }
+ return nil
+}
diff --git a/internal/provision/stateless_replicas_4_task1_census_test.go b/internal/provision/stateless_replicas_4_task1_census_test.go
index fc40c605d..7f1260cd9 100644
--- a/internal/provision/stateless_replicas_4_task1_census_test.go
+++ b/internal/provision/stateless_replicas_4_task1_census_test.go
@@ -30,24 +30,43 @@ package provision
// - prepareStateless: the ID selector moved after term acquisition; no
// record write here. routeDecls: one /deploy route. replicaAction,
// handleAPIInstanceList, handleInstanceRetry: reads and a refusal only.
+//
+// Fix round 1 (review r0 findings 1-4 as amended), self-review:
+// - RequestReplicaRetries is the arming half of an explicit retry: one
+// idempotent RequestRecordReplicaRetry per target chosen by the
+// read-only ReplicaRetryTargets. Its only caller is
+// armReplicaRetriesLocked, run after every target and the door's own
+// preconditions passed, so a refusal writes nothing: the host retry
+// under withRecordLock after the signed grant, promote --retry under
+// the promote door's app lock after PromoteOnLadder accepted.
+// requestReplicaRetryLocked is gone. The direct-bucket CLI writes no
+// record: it refuses a retry on a replicated channel.
+// - RequestRecordReplicaRetry answers an open permit with
+// ErrReplicaSwitchOpen instead of ErrFenced; same CAS and checks.
+// - SetRecordReplicaDeploy: the grant-membership check is keyed on op
+// permit (Grant is read by no other op); same CAS, keys and lock.
+// handleReplicaDeploy: the order
+// now reads the fleet's heartbeats (fleetBoxView.Fresh) under the same
+// lock before the same typed write.
func statelessReplicas4Task1WriteCensusInventory() []censusEntry {
entries := append([]censusEntry(nil), billingOverviewSpeedWriteCensusInventory()...)
for _, r := range []censusEntry{
{"internal/activator/stateless.go", "Service.prepareStateless", "reference", "key:statelessRecordKey", "c5bcac73de222c9e4a6c9b76ec541bad32c37a66eff1e5638cb68b2fc0592a5d"},
{"internal/console/apiinstances.go", "Server.handleAPIInstanceList", "key-site", "lit:instances", "0d04c22e1f8b2cddc7180209ad72a736cc7cf86767d2e80d7e5a66e1281def27"},
- {"internal/console/browserretry.go", "Server.handleInstanceRetry", "key-site", "lit:instances", "01aaaf179641d30c361dec338ff3b8d00d815c01198c74a718af58bdf83c49fc"},
+ {"internal/console/browserretry.go", "Server.handleInstanceRetry", "key-site", "lit:instances", "5bb3b3c0a6719b57bc4f97a3f0ed64cec48c6917b0bf5a22e322bbdeb0f6b3e2"},
{"internal/console/replicacoordinator.go", "Server.handleReplicaRelease", "record-writer", "key:SetRecordReplicaRelease", "7545f866084af5d8069df94d978de65791d5acf18601371193ea445edb765110"},
- {"internal/console/replicadeploy.go", "Server.handleReplicaDeploy", "record-writer", "key:SetRecordReplicaDeploy", "38418bf94d94e8cbded10800c7656def229453f63759b57274f8982bc91170eb"},
- {"internal/console/replicadeploy.go", "Server.requestReplicaRetryLocked", "record-writer", "key:RequestRecordReplicaRetry", "630d09e107a85ae68d06e44dbd32fb008487c2ae45185d7dd5e6fe0d9837d4be"},
+ {"internal/console/replicadeploy.go", "Server.handleReplicaDeploy", "record-writer", "key:SetRecordReplicaDeploy", "f1a98b514a08ff9cf5ddae4eab48e027e00ad9d0406f36073943b35c46fd48cd"},
{"internal/console/replicaplacement.go", "Server.replicaAction", "key-site", "key:replicaRecordKey", "4ea765ce2d3131f8a9b26fb256493c2b68efebe928711f11e9570ec2c3212321"},
{"internal/console/routedecls.go", "var routeDecls", "key-site", "lit:instances,lit:sidecars", "71de6f3bd690ea07da6b2740429dbe90e1925174709807087b9274aa80454040"},
{"internal/host/replicacoordinator.go", "replicaCoordinatorStore.releaseState", "record-writer", "key:SetRecordReplicaRelease", "e1ae48005ee0663fa337cdeb50dcda09a9c5c34ad41eace7fc2db4b946f7b065"},
{"internal/provision/replicaassignment.go", "HaltRecordReplicaDeploy", "record-writer", "key:HaltRecordReplicaDeploy,key:updateRecord", "f8044b6f03638c0098266b603a49203537980572438a9d657a1474998d2ab6b8"},
{"internal/provision/replicaassignment.go", "RecordReplicaRetired", "record-writer", "key:RecordReplicaRetired,key:updateRecord", "c5ee5437291b4f39966cb6bd7e155ae98a9eaa041125be0b6195a488bd6da9e9"},
{"internal/provision/replicaassignment.go", "SetRecordReplicaAssignment", "record-writer", "key:SetRecordReplicaAssignment,key:updateRecord", "504fc1b4e3e2af75fe2088d033370e881d7e8be7ecc291b4a60c81eb16283754"},
- {"internal/provision/replicadeploy.go", "RequestRecordReplicaRetry", "record-writer", "key:RequestRecordReplicaRetry,key:updateRecord", "41d3f84b0301455bf0a02c32fa52e10ebd979b69509bb3365229a11dc1847fba"},
- {"internal/provision/replicadeploy.go", "SetRecordReplicaDeploy", "record-writer", "key:SetRecordReplicaDeploy,key:updateRecord", "65dc3acdfc55671b18e82936237da4fa013216ac95b1bec42ef9c41fadbc384d"},
+ {"internal/provision/replicadeploy.go", "RequestRecordReplicaRetry", "record-writer", "key:RequestRecordReplicaRetry,key:updateRecord", "accd7b18ab0edd0c9ac67992b1594a4c59ae89866e6472465e650fa2811cf333"},
+ {"internal/provision/replicadeploy.go", "SetRecordReplicaDeploy", "record-writer", "key:SetRecordReplicaDeploy,key:updateRecord", "483c43a7982c699d0939910786ca9d01f41760a5724965d0ef4a6106a08844c1"},
{"internal/provision/replicadeploy.go", "SetRecordReplicaRelease", "record-writer", "key:SetRecordReplicaRelease,key:updateRecord", "a43483f00d489665844cd469b937c30d9a2aae5f0eaddb5b6b42dd917e5b6ad9"},
+ {"internal/console/replicadeploy.go", "Server.armReplicaRetriesLocked", "record-writer", "key:RequestReplicaRetries", "b4f544ab698e115ed1ae2069e842c96401d20044145588995a4062a306fbfc9f"},
+ {"internal/provision/replicadeploy.go", "RequestReplicaRetries", "record-writer", "key:RequestRecordReplicaRetry,key:RequestReplicaRetries", "6befe09ed6ba676c633da20db9917497ec8c0dca8372e0fc503786c1012aa684"},
} {
replaced := false
for i, e := range entries {
diff --git a/internal/provision/testdata/plan14-root-reads-chain.tsv b/internal/provision/testdata/plan14-root-reads-chain.tsv
index b368f732a..2816becb9 100644
--- a/internal/provision/testdata/plan14-root-reads-chain.tsv
+++ b/internal/provision/testdata/plan14-root-reads-chain.tsv
@@ -169,3 +169,4 @@ plan14-root-reads-group-capacity-damping.tsv 0c649af234a7b89a75479e59e705307e329
plan14-root-reads-group-verb-followups.tsv 9c74b9876a13a3a3802860fe44406898c8bcbfd3bd22e8172a59a02674c3b4af
plan14-root-reads-group-read-transport-retry.tsv 9c74b9876a13a3a3802860fe44406898c8bcbfd3bd22e8172a59a02674c3b4af
plan14-root-reads-stateless-replicas-4-task1.tsv 3f066208f5e5fa2b9854f30118a9a2707f3a5a51bcf55ae6b0949cb0307804f5
+plan14-root-reads-stateless-replicas-4-task1-fix1.tsv 3f066208f5e5fa2b9854f30118a9a2707f3a5a51bcf55ae6b0949cb0307804f5
diff --git a/internal/provision/testdata/plan14-root-reads-stateless-replicas-4-task1-fix1.tsv b/internal/provision/testdata/plan14-root-reads-stateless-replicas-4-task1-fix1.tsv
new file mode 100644
index 000000000..076c5bca3
--- /dev/null
+++ b/internal/provision/testdata/plan14-root-reads-stateless-replicas-4-task1-fix1.tsv
@@ -0,0 +1,5 @@
+# Census overlay stateless-replicas-4-task1-fix1, written by census-propose (#369). census-ruling-stateless-replicas-4-task1-fix1, approved on #280 before the merge; the approval card is docs/superpowers/notes/census-proposal-stateless-replicas-4-task1-fix1.md.
+# 0 body, 0 sites, 3 envelope: each changed unit re-frozen at its existing disposition with its claim appended.
+@coverage . dc1c74fb50aa7854194bb8418be7d69387d4adbf2a87e7ab16ee0b4a39ca8b77
+@coverage internal/host 935eb28883486b5c0ffcc7eb1ee82f607afa80cb6bcc498cbc559c633d12d7bf
+@coverage internal/provision de2fd746808c2ba6e22d1ee8acd17f8dd9303ef285a4c72dd8c9a64453526efb
diff --git a/internal/replicas/deploy_test.go b/internal/replicas/deploy_test.go
index 4f9ae220d..615f7dbae 100644
--- a/internal/replicas/deploy_test.go
+++ b/internal/replicas/deploy_test.go
@@ -86,6 +86,7 @@ func TestReplicaDeployTransitionCAS(t *testing.T) {
{name: "ack with a term", cur: granted, base: ack, c: func(c DeployChange) DeployChange { c.Term = "term-a"; return c }},
{name: "late ack", cur: acked, base: ack, c: func(c DeployChange) DeployChange { c.Revision = acked.Revision; return c }},
{name: "unknown op", cur: ordered, base: permit, c: func(c DeployChange) DeployChange { c.Op = "released"; return c }},
+ {name: "no skip op", cur: acked, base: coordinatorChange(acked, "skip"), c: func(c DeployChange) DeployChange { c.Grant = "b"; return c }},
}
for _, phase := range []string{"pending", "releasing", "failed", "unknown", "done"} {
cur := d
diff --git a/replica_promote_retry_test.go b/replica_promote_retry_test.go
new file mode 100644
index 000000000..d725f2606
--- /dev/null
+++ b/replica_promote_retry_test.go
@@ -0,0 +1,95 @@
+package main
+
+import (
+ "context"
+ "encoding/json"
+ "reflect"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/provision"
+ "github.com/carlosframework/platform/internal/release"
+ "github.com/carlosframework/platform/internal/replicas"
+)
+
+// dirSnapshot is every key in a local deployment bucket with its bytes.
+func dirSnapshot(t *testing.T, s release.Store) map[string]string {
+ t.Helper()
+ keys, err := s.List(context.Background(), "")
+ if err != nil {
+ t.Fatal(err)
+ }
+ out := map[string]string{}
+ for _, k := range keys {
+ raw, _, err := s.Get(context.Background(), k)
+ if err == nil {
+ out[k] = string(raw)
+ }
+ }
+ return out
+}
+
+// TestReplicaDirectPromoteRetry: direct-bucket `carlos promote --retry`
+// refuses, writing nothing, when the channel has an instance with a copy
+// assignment or a stateless replica deploy, and points at the console. The
+// same command still renews the pointer for a channel without one.
+func TestReplicaDirectPromoteRetry(t *testing.T) {
+ run, bucket := versioningCLI(t)
+ if out, err := run("version", "target", "-app", "kass", "0.5.0"); err != nil {
+ t.Fatalf("version target: %v\n%s", err, out)
+ }
+ if out, err := run("ship", "-app", "kass", versioningArtifact(t, "build one")); err != nil {
+ t.Fatalf("ship: %v\n%s", err, out)
+ }
+ for _, ch := range []string{"edge", "beta"} {
+ if out, err := run("promote", "-app", "kass", "0.5.0-1", ch); err != nil {
+ t.Fatalf("promote %s: %v\n%s", ch, err, out)
+ }
+ }
+ store := release.NewDirStore(bucket)
+ ctx := provision.WithRecordSequence(context.Background())
+ put := func(host string, f func(*provision.Record)) {
+ t.Helper()
+ rec := provision.Record{Schema: 1, Account: release.OpsAccount, App: "kass", Host: host, Slug: strings.SplitN(host, ".", 2)[0], Channel: "edge", CreatedAt: time.Date(2026, 11, 1, 0, 0, 0, 0, time.UTC)}
+ if err := provision.CreateRecord(ctx, store, rec); err != nil {
+ t.Fatal(err)
+ }
+ key := provision.RecordKey(release.OpsAccount, "kass", host)
+ raw, etag, err := store.Get(ctx, key)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := json.Unmarshal(raw, &rec); err != nil {
+ t.Fatal(err)
+ }
+ f(&rec)
+ raw, _ = json.Marshal(rec)
+ if _, err := store.Put(ctx, key, raw, etag); err != nil {
+ t.Fatal(err)
+ }
+ }
+ put("a.kass.example.com", func(r *provision.Record) {
+ r.ReplicaDeploy = &replicas.Deploy{ID: "deploy-a", Target: replicas.Build{Version: "0.5.0-1", Digest: "canonical"}, Phase: "failed", Term: "t", Revision: 3}
+ })
+ put("b.kass.example.com", func(r *provision.Record) {
+ r.ReplicaAssignment = &replicas.Assignment{Revision: 1, Desired: 1, Boxes: []string{"pi-1"}}
+ })
+ for _, refused := range []string{"a.kass.example.com", "b.kass.example.com"} {
+ before := dirSnapshot(t, store)
+ out, err := run("promote", "-app", "kass", "-retry", "0.5.0-1", "edge")
+ if err == nil || !strings.Contains(out, "retry it through the console: carlos instances retry <host>") {
+ t.Fatalf("%s: direct retry was not refused: %v\n%s", refused, err, out)
+ }
+ if !reflect.DeepEqual(dirSnapshot(t, store), before) {
+ t.Fatalf("%s: a refused retry wrote", refused)
+ }
+ if err := store.Delete(ctx, provision.RecordKey(release.OpsAccount, "kass", refused)); err != nil {
+ t.Fatal(err)
+ }
+ }
+ // beta has no replicated instance: the direct retry renews as before.
+ if out, err := run("promote", "-app", "kass", "-retry", "0.5.0-1", "beta"); err != nil {
+ t.Fatalf("plain retry: %v\n%s", err, out)
+ }
+}