carlos / platform Public

feat: set app copy counts behind the replica floor

Store the default-bundle count through the existing CAS and app mutation
boundaries. Add API-only copies edits, complete fleet and release admission,
shared assignment wire fields, and ordinary-writer preservation.

Keep counts above one behind the reserved replica floor. This is Plan 2
Task 1 slice 1a; publication-door checks, assignment writers, and root
census approval remain in their designated later slices.

Verify targeted and race tests, claim/route and request-budget gates,
approved copy, build/vet, and Darwin, Windows, and Linux arm64 builds.
Co-Authored-By: Codex (gpt-6-astra) <noreply@openai.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev 572d75389d29b07b4cea6bd19a5e830f56d05572 parent 89a4085
25 files changed, +970 −24
  • apimode.go +19 −0
  • approved_stateless_replicas_copy_test.go +1 −1
  • apps_copies.go +28 −0
  • apps_copies_test.go +59 −0
  • apps_swap.go +18 −5
  • apps_swap_test.go +2 −2
  • docs/site/cli.md +4 −0
  • docs/superpowers/plans/2026-10-07-zero-downtime-deploys-6-copy.json +2 −2
  • docs/superpowers/plans/2026-10-21-instance-policy-copy.json +2 −2
  • docs/superpowers/plans/2026-10-24-rootfs-apps-copy.md +2 −2
  • docs/superpowers/plans/2026-11-01-stateless-replicas-copy.md +1 −1
  • internal/appconfig/appconfig.go +2 −0
  • internal/appconfig/copies.go +56 −0
  • internal/appconfig/copies_test.go +61 −0
  • internal/console/appcopies.go +293 −0
  • internal/console/appcopies_test.go +328 −0
  • internal/console/authcli.go +1 −0
  • internal/console/claim_invariant_fixtures_test.go +4 −0
  • internal/console/fleetbox.go +6 −5
  • internal/console/testdata/claim-routes.txt +1 −0
  • internal/provision/lifetimeindex.go +6 −0
  • internal/provision/provision.go +3 −2
  • internal/provision/replicaassignment_test.go +48 −0
  • internal/provision/replicacoordinator.go +6 −2
  • internal/replicas/assignment.go +17 −0

CI failed — run details

Intent

Attributed to this commit: 19.3 g CO₂e (1,959,476 tokens). This is an attribution, not a measurement — usage counted from this commit's own marker forward to the next one on stateless-replicas-2-placement, never backward from it. A turn that produced more than one commit books all of its tokens to the last one, and a concurrent session on this branch can add to the same figure. Some of it was priced using the shared default rate, because no model-specific factor row exists yet for at least one model involved. The Carbon view has the repo total, which is never derived from this attribution.

diff --git a/apimode.go b/apimode.go
index f701dbe40..5122ce1ae 100644
--- a/apimode.go
+++ b/apimode.go
@@ -5697,3 +5697,22 @@ func (s *apiSession) envOwnership(ctx context.Context, path string, in map[strin
}
return out, nil
}
+
+// setCopies uses the console's app-wide admission and echoes its requested count.
+func (s *apiSession) setCopies(ctx context.Context, a apiAcct, app string, n int, message string) (int, error) {
+ status, body, err := s.putJSON(ctx, apiPath(a, app, "/copies"), struct {
+ Copies int `json:"copies"`
+ Message string `json:"message,omitempty"`
+ }{n, message})
+ if err != nil {
+ return 0, err
+ }
+ if status != http.StatusOK {
+ return 0, apiErrorFromBody(status, body)
+ }
+ var out apiCopies
+ if err := json.Unmarshal(body, &out); err != nil {
+ return 0, fmt.Errorf(appsCopiesMismatch, n)
+ }
+ return out.Copies, nil
+}
diff --git a/approved_stateless_replicas_copy_test.go b/approved_stateless_replicas_copy_test.go
index 3fd9b1200..c24419dcc 100644
--- a/approved_stateless_replicas_copy_test.go
+++ b/approved_stateless_replicas_copy_test.go
@@ -9,7 +9,7 @@ import (
const statelessReplicaCopyDeck = "docs/superpowers/plans/2026-11-01-stateless-replicas-copy.md"
-var statelessReplicaBuiltCopy = []string{"SR-1-C08", "SR-1-C06", "SR-1-C07", "SR-1-C01", "SR-1-C02", "SR-1-C03", "SR-1-C04", "SR-1-C05", "SR-1-C12", "SR-1-C09", "SR-1-C10", "SR-1-C13"}
+var statelessReplicaBuiltCopy = []string{"SR-2-C01", "SR-2-C02", "SR-2-C03", "SR-2-C04", "SR-2-C05", "SR-2-C06", "SR-2-C07", "SR-2-C08", "SR-2-C09", "SR-2-C12", "SR-2-C13", "SR-2-C14", "SR-2-C15", "SR-2-C16", "SR-2-C17", "SR-1-C08", "SR-1-C06", "SR-1-C07", "SR-1-C01", "SR-1-C02", "SR-1-C03", "SR-1-C04", "SR-1-C05", "SR-1-C12", "SR-1-C09", "SR-1-C10", "SR-1-C13"}
func statelessReplicaCopyRows(t *testing.T) []copyRow {
t.Helper()
diff --git a/apps_copies.go b/apps_copies.go
new file mode 100644
index 000000000..a4e0fa6eb
--- /dev/null
+++ b/apps_copies.go
@@ -0,0 +1,28 @@
+package main
+
+import (
+ "context"
+ "fmt"
+)
+
+const (
+ appsSetFlagCopies = "number of copies for each instance on different boxes in the app's fleet (default 1)"
+ appsCopiesDone = "%s: %d copies requested for each instance"
+ appsCopiesMismatch = "the console did not confirm %d copies, so the change could not be verified"
+)
+
+type apiCopies struct {
+ Copies int `json:"copies"`
+}
+
+func appsCopiesRun(ctx context.Context, sess *apiSession, acct apiAcct, app string, n int, message string) error {
+ got, err := sess.setCopies(ctx, acct, app, n, message)
+ if err != nil {
+ return err
+ }
+ if got != n {
+ return fmt.Errorf(appsCopiesMismatch, n)
+ }
+ fmt.Fprintf(stdout, appsCopiesDone+"\n", app, n)
+ return nil
+}
diff --git a/apps_copies_test.go b/apps_copies_test.go
new file mode 100644
index 000000000..b2399b5b9
--- /dev/null
+++ b/apps_copies_test.go
@@ -0,0 +1,59 @@
+package main
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "fmt"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "os/exec"
+ "strings"
+ "testing"
+)
+
+func TestCopiesCLI(t *testing.T) {
+ for _, reply := range []string{`{"copies":2}`, `{"copies":1}`, `{}`, `invalid`} {
+ t.Run(reply, func(t *testing.T) {
+ var body struct {
+ Copies int
+ Message string
+ }
+ ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.Method != http.MethodPut || r.URL.Path != "/api/cli/apps/bab/shop/copies" {
+ t.Errorf("request: %s %s", r.Method, r.URL.Path)
+ }
+ if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
+ t.Error(err)
+ }
+ io.WriteString(w, reply)
+ }))
+ defer ts.Close()
+ old := stdout
+ var out bytes.Buffer
+ stdout = &out
+ defer func() { stdout = old }()
+ err := appsCopiesRun(context.Background(), newTestSession(ts.URL), apiAcct{Seg: "bab"}, "shop", 2, "add capacity")
+ if body.Copies != 2 || body.Message != "add capacity" {
+ t.Fatalf("body: %+v", body)
+ }
+ if reply == `{"copies":2}` {
+ if err != nil || out.String() != "shop: 2 copies requested for each instance\n" {
+ t.Fatalf("success: %q %v", out.String(), err)
+ }
+ } else if err == nil || err.Error() != fmt.Sprintf(appsCopiesMismatch, 2) || out.Len() != 0 {
+ t.Fatalf("mismatch: %q %v", out.String(), err)
+ }
+ })
+ }
+}
+func TestCopiesNeverFallsBackToBucket(t *testing.T) {
+ cmd := exec.Command(sharedCarlos(t), "apps", "set", "shop", "--copies", "2", "--no-prompt")
+ cmd.Dir = t.TempDir()
+ cmd.Env = carlosTestEnv(t, "CARLOS_DEPLOYMENT_DIR="+t.TempDir())
+ out, err := cmd.CombinedOutput()
+ if err == nil || !strings.Contains(string(out), appsSetDirectMode) {
+ t.Fatalf("direct mode: %v %s", err, out)
+ }
+}
diff --git a/apps_swap.go b/apps_swap.go
index 4d5deb514..1a96bd75d 100644
--- a/apps_swap.go
+++ b/apps_swap.go
@@ -19,7 +19,7 @@ import (
"github.com/carlosframework/platform/internal/updatewords"
)
-const appsSetUsage = `usage: carlos apps set <app> [--swap overlap|hold] [--swap-concurrency <n>] [--interactive on|off] [--account <sqid|name>] [--account-id <sqid>] [--console <origin>] [--egress-allow <ip,...>] [--size small|standard|large|xlarge|default]
+const appsSetUsage = `usage: carlos apps set <app> [--copies <n>] [--swap overlap|hold] [--swap-concurrency <n>] [--interactive on|off] [--account <sqid|name>] [--account-id <sqid>] [--console <origin>] [--egress-allow <ip,...>] [--size <size>]
--swap overlap|hold how a running instance takes a new build. overlap
starts the new build beside the old one and switches
@@ -38,7 +38,7 @@ const (
appsSetFlagApp = "app whose swap or instance policy to set"
appsSetFlagSwap = "overlap or hold: how a running instance takes a new build"
appsSetFlagConcurrency = "how many instances of the app may swap at once on one box (1 or more)"
- appsSetNothing = "apps set: nothing to set. Pass --swap, --swap-concurrency, --egress-allow, --size or --interactive"
+ appsSetNothing = "apps set: nothing to set. pass --copies, --swap, --swap-concurrency, --egress-allow, --size or --interactive"
appsSetBadSwap = "apps set: --swap is overlap or hold, not %q"
appsSetBadConcurrency = "apps set: --swap-concurrency must be 1 or more"
appsSetTwoApps = "apps set: name the app once, either first or with --app"
@@ -164,6 +164,8 @@ func runAppsSet(args []string) {
lead, args := leadingArg(args)
fs := flag.NewFlagSet("apps set", flag.ExitOnError)
appF := appFlag(fs, appsSetFlagApp)
+ copies := fs.Int("copies", 1, appsSetFlagCopies)
+ messageFlags := addMutationMessageFlags(fs)
swap := fs.String("swap", "", appsSetFlagSwap)
concurrency := fs.Int("swap-concurrency", 0, appsSetFlagConcurrency)
acctRaw := fs.String("account", "", "account (sqid or name) the app belongs to (default: your only account, or the configured/chosen one)")
@@ -207,7 +209,7 @@ func runAppsSet(args []string) {
log.Fatal(err)
}
}
- if swapReq == nil && policy == nil && change == nil && interactive == nil {
+ if swapReq == nil && policy == nil && change == nil && interactive == nil && !flagWasSet(fs, "copies") {
log.Fatal(appsSetNothing)
}
sess, err := resolveMode(*consoleFlag)
@@ -218,8 +220,19 @@ func runAppsSet(args []string) {
log.Fatal(appsSetDirectMode)
}
acct := resolvedAccount(sess, acctRaw, acctIDRaw)
- if err := appsSetRun(context.Background(), sess, acct, app, swapReq, policy, change, interactive); err != nil {
- log.Fatal(err)
+ if flagWasSet(fs, "copies") {
+ message, err := resolveMutationMessage(fs, messageFlags)
+ if err != nil {
+ log.Fatal(err)
+ }
+ if err := appsCopiesRun(context.Background(), sess, acct, app, *copies, message); err != nil {
+ log.Fatal(err)
+ }
+ }
+ if swapReq != nil || policy != nil || change != nil || interactive != nil {
+ if err := appsSetRun(context.Background(), sess, acct, app, swapReq, policy, change, interactive); err != nil {
+ log.Fatal(err)
+ }
}
}
diff --git a/apps_swap_test.go b/apps_swap_test.go
index 1501cf893..d42c881a0 100644
--- a/apps_swap_test.go
+++ b/apps_swap_test.go
@@ -158,8 +158,8 @@ func TestAppsSetInteractive(t *testing.T) {
if err := appsSetRun(context.Background(), newTestSession("http://127.0.0.1:1"), apiAcct{Seg: "bah"}, "shop", nil, nil, nil, nil); err == nil || err.Error() != appsSetNothing {
t.Errorf("nothing given: %v, want %q", err, appsSetNothing)
}
- if appsSetNothing != "apps set: nothing to set. Pass --swap, --swap-concurrency, --egress-allow, --size or --interactive" {
- t.Errorf("appsSetNothing = %q, not RFS-6-C47", appsSetNothing)
+ if appsSetNothing != "apps set: nothing to set. pass --copies, --swap, --swap-concurrency, --egress-allow, --size or --interactive" {
+ t.Errorf("appsSetNothing = %q, not SR-2-C17", appsSetNothing)
}
var sent []string
diff --git a/docs/site/cli.md b/docs/site/cli.md
index 96c22e11b..c4046ff53 100644
--- a/docs/site/cli.md
+++ b/docs/site/cli.md
@@ -255,6 +255,10 @@ The console records a change, and the app's boxes apply it. A box that follows t
Ship with --stateless when your app keeps its data outside its box. The release gets no local database, CARLOS_DB or Litestream. You provide and operate its database and other data services.
+Set the count with carlos apps set shop --copies 2. Each instance of shop gets two copies on different eligible fleet boxes. The command refuses a count larger than the eligible fleet.
+
+If a box is lost or detached, the requested count stays the same. The platform uses a distinct spare when one is available, otherwise the app runs short until a suitable box returns.
+
If the box running the release command disappears, its result may be unknown. The deploy stops and the previous build keeps serving. Deploying again runs the command again, so release commands must be safe to repeat. Rails migrations record completed migrations in schema_migrations.
Publishes a release. The artifact is hashed, stored under its content
diff --git a/docs/superpowers/plans/2026-10-07-zero-downtime-deploys-6-copy.json b/docs/superpowers/plans/2026-10-07-zero-downtime-deploys-6-copy.json
index d15363d2c..75ac12def 100644
--- a/docs/superpowers/plans/2026-10-07-zero-downtime-deploys-6-copy.json
+++ b/docs/superpowers/plans/2026-10-07-zero-downtime-deploys-6-copy.json
@@ -46,11 +46,11 @@
{"id": "zdd.api.retry-limited", "file": "internal/console/apiretry.go", "text": "too many requests. wait a minute and try again"},
{"id": "zdd.apps.usage-line", "file": "apps.go", "text": "usage: carlos apps <create|place|build-probe|set|show|delete|restore|ttl|keep|list> [flags] <app>"},
{"id": "zdd.apps.usage-set", "file": "apps.go", "text": " set <app> [--swap overlap|hold] [--swap-concurrency <n>] how the app's\n running instances take a new build: see carlos apps set -h."},
- {"id": "zdd.apps-set.usage", "file": "apps_swap.go", "text": "usage: carlos apps set <app> [--swap overlap|hold] [--swap-concurrency <n>] [--interactive on|off] [--account <sqid|name>] [--account-id <sqid>] [--console <origin>] [--egress-allow <ip,...>] [--size small|standard|large|xlarge|default]\n\n --swap overlap|hold how a running instance takes a new build. overlap\n starts the new build beside the old one and switches\n once it answers its health check, so no request\n waits. hold stops the old one first, and requests\n wait until the new one is up. Use hold when two\n builds cannot share the database.\n --swap-concurrency <n> how many instances of the app may swap at once on\n one box, after the first has stayed up for ten\n seconds. 1 or more; it starts at 1.\n\nAny member of the app may change these. They reach the app's boxes with its\nconfig, within seconds.", "superseded_by": "RFS-6-C66", "note": "The first line was superseded by RFS-6-C66, which adds [--interactive on|off]; Paul approved it unchanged in his copy review on 2026-10-31 (docs/superpowers/plans/2026-10-24-rootfs-apps-copy.md). It read: usage: carlos apps set <app> [--swap overlap|hold] [--swap-concurrency <n>] [--account <sqid|name>] [--account-id <sqid>] [--console <origin>] [--egress-allow <ip,...>] [--size small|standard|large|xlarge|default]"},
+ {"id": "zdd.apps-set.usage", "file": "apps_swap.go", "text": "usage: carlos apps set <app> [--copies <n>] [--swap overlap|hold] [--swap-concurrency <n>] [--interactive on|off] [--account <sqid|name>] [--account-id <sqid>] [--console <origin>] [--egress-allow <ip,...>] [--size <size>]\n\n --swap overlap|hold how a running instance takes a new build. overlap\n starts the new build beside the old one and switches\n once it answers its health check, so no request\n waits. hold stops the old one first, and requests\n wait until the new one is up. Use hold when two\n builds cannot share the database.\n --swap-concurrency <n> how many instances of the app may swap at once on\n one box, after the first has stayed up for ten\n seconds. 1 or more; it starts at 1.\n\nAny member of the app may change these. They reach the app's boxes with its\nconfig, within seconds.", "superseded_by": "SR-2-C13", "note": "Replaced verbatim by SR-2-C13 in the stateless replicas copy deck for Plan 2 slice 1a."},
{"id": "zdd.apps-set.flag-swap", "file": "apps_swap.go", "text": "overlap or hold: how a running instance takes a new build"},
{"id": "zdd.apps-set.flag-concurrency", "file": "apps_swap.go", "text": "how many instances of the app may swap at once on one box (1 or more)"},
{"id": "zdd.apps-set.flag-app", "file": "apps_swap.go", "text": "app whose swap or instance policy to set"},
- {"id": "zdd.apps-set.nothing", "file": "apps_swap.go", "text": "apps set: nothing to set. Pass --swap, --swap-concurrency, --egress-allow, --size or --interactive"},
+ {"id": "zdd.apps-set.nothing", "file": "apps_swap.go", "text": "apps set: nothing to set. pass --copies, --swap, --swap-concurrency, --egress-allow, --size or --interactive", "superseded_by": "SR-2-C17", "note": "Replaced verbatim by SR-2-C17 in the stateless replicas copy deck for Plan 2 slice 1a."},
{"id": "zdd.apps-set.bad-swap", "file": "apps_swap.go", "text": "apps set: --swap is overlap or hold, not %q"},
{"id": "zdd.apps-set.bad-concurrency", "file": "apps_swap.go", "text": "apps set: --swap-concurrency must be 1 or more"},
{"id": "zdd.apps-set.two-apps", "file": "apps_swap.go", "text": "apps set: name the app once, either first or with --app"},
diff --git a/docs/superpowers/plans/2026-10-21-instance-policy-copy.json b/docs/superpowers/plans/2026-10-21-instance-policy-copy.json
index ea374f3bf..85c2cdfd2 100644
--- a/docs/superpowers/plans/2026-10-21-instance-policy-copy.json
+++ b/docs/superpowers/plans/2026-10-21-instance-policy-copy.json
@@ -79,9 +79,9 @@
{"id": "IP2-31", "file": "apps_policy.go", "text": "!"},
{"id": "IP1-55", "file": "apps.go", "text": " show <app> the app's egress allow and sizes. system operators only\n"},
{"id": "IP1-56", "file": "apps.go", "text": "usage: carlos apps <create|place|build-probe|set|show|delete|restore|ttl|keep|list> [flags] <app>"},
- {"id": "IP1-57", "file": "apps_swap.go", "text": "apps set: nothing to set. Pass --swap, --swap-concurrency, --egress-allow, --size or --interactive"},
+ {"id": "IP1-57", "file": "apps_swap.go", "text": "apps set: nothing to set. pass --copies, --swap, --swap-concurrency, --egress-allow, --size or --interactive", "superseded_by": "SR-2-C17", "note": "Replaced verbatim by SR-2-C17 in the stateless replicas copy deck for Plan 2 slice 1a."},
{"id": "GAP-1", "file": "internal/updatewords/words_surfaces.go", "text": "usage: carlos instances set <host> [--app <a>] [--updates auto|manual] [--channel <c>] [--major <n>] [--pin <build>] [--size small|standard|large|xlarge|default] (an empty value clears an update setting)"},
- {"id": "GAP-2", "file": "apps_swap.go", "text": "usage: carlos apps set <app> [--swap overlap|hold] [--swap-concurrency <n>] [--interactive on|off] [--account <sqid|name>] [--account-id <sqid>] [--console <origin>] [--egress-allow <ip,...>] [--size small|standard|large|xlarge|default]\n", "superseded_by": "RFS-6-C66", "note": "The first line was superseded by RFS-6-C66, which adds [--interactive on|off]; Paul approved it unchanged in his copy review on 2026-10-31 (docs/superpowers/plans/2026-10-24-rootfs-apps-copy.md). It read: usage: carlos apps set <app> [--swap overlap|hold] [--swap-concurrency <n>] [--account <sqid|name>] [--account-id <sqid>] [--console <origin>] [--egress-allow <ip,...>] [--size small|standard|large|xlarge|default]"},
+ {"id": "GAP-2", "file": "apps_swap.go", "text": "usage: carlos apps set <app> [--copies <n>] [--swap overlap|hold] [--swap-concurrency <n>] [--interactive on|off] [--account <sqid|name>] [--account-id <sqid>] [--console <origin>] [--egress-allow <ip,...>] [--size <size>]\n", "superseded_by": "SR-2-C13", "note": "Replaced verbatim by SR-2-C13 in the stateless replicas copy deck for Plan 2 slice 1a."},
{"id": "GAP-3", "file": "apps_swap.go", "text": "app whose swap or instance policy to set"},
{"id": "IP3-04", "file": "status_instances.go", "text": "BOX REGION HOST LAYOUT SIZE EGRESS REASON"},
{"id": "IP3-08", "file": "status_instances.go", "text": "-"},
diff --git a/docs/superpowers/plans/2026-10-24-rootfs-apps-copy.md b/docs/superpowers/plans/2026-10-24-rootfs-apps-copy.md
index 890c5b9ce..581921a4e 100644
--- a/docs/superpowers/plans/2026-10-24-rootfs-apps-copy.md
+++ b/docs/superpowers/plans/2026-10-24-rootfs-apps-copy.md
@@ -527,7 +527,7 @@ From the plan: Every string is human text the plan introduces. Existing approved
| RFS-6-C44 | apps_swap.go | %s: interactive sessions are on. any member can open a terminal on its instances with carlos run -it | approved |
| RFS-6-C45 | apps_swap.go | %s: interactive sessions are off | approved |
| RFS-6-C46 | apps_swap.go | apps set: the change did not stick (the console stored interactive %s). run it again | approved |
-| RFS-6-C47 | apps_swap.go (appsSetNothing, replacing today's IP1-57 `apps set: nothing to set. Pass --swap, --swap-concurrency, --egress-allow or --size`, also held by the zero-downtime record zdd.apps-set.nothing and the instance-policy record IP1-57, which change with it; revised 2026-10-30 by the Plan 6 preflight, PF-10, to keep --egress-allow and --size; the first draft read `apps set: nothing to set. Pass --swap, --swap-concurrency, --interactive or one of the update settings`) | apps set: nothing to set. Pass --swap, --swap-concurrency, --egress-allow, --size or --interactive | approved |
+| RFS-6-C47 | apps_swap.go (superseded verbatim by SR-2-C17 for Plan 2 slice 1a; appsSetNothing, replacing today's IP1-57 `apps set: nothing to set. Pass --swap, --swap-concurrency, --egress-allow or --size`, also held by the zero-downtime record zdd.apps-set.nothing and the instance-policy record IP1-57, which change with it; revised 2026-10-30 by the Plan 6 preflight, PF-10, to keep --egress-allow and --size; the first draft read `apps set: nothing to set. Pass --swap, --swap-concurrency, --interactive or one of the update settings`) | apps set: nothing to set. pass --copies, --swap, --swap-concurrency, --egress-allow, --size or --interactive | approved |
| RFS-6-C48 | internal/host/interactive.go (`carlos logs`, sessionStartedLine, built by Plan 6 Task 12) | interactive session %s opened by %s | approved |
| RFS-6-C49 | internal/host/interactive.go (`carlos logs`, sessionEndedLine, built by Plan 6 Task 12) | interactive session %s ended with exit %d after %s | approved |
| RFS-6-C50 | internal/host/interactive.go (`carlos logs`, sessionEndedLine, built by Plan 6 Task 12) | interactive session %s ended after %s: %s | approved |
@@ -546,7 +546,7 @@ From the plan: Every string is human text the plan introduces. Existing approved
| RFS-6-C63 | internal/host/runrelay.go (`carlos logs`, runGrantUnverifiedLine: box, a run grant that did not verify; built by Plan 6 Task 16) | run %s was not started on this box: its grant could not be verified | approved |
| RFS-6-C64 | internal/host/runrelay.go (`carlos logs`, runRelayLostLine: box, the relay dropped mid-run; built by Plan 6 Task 16) | run %s lost its connection to the console, so it was stopped | approved |
| RFS-6-C65 | run.go (parseRunArgs: `carlos run -it` or `--interactive` given with `--idempotency-key`; printed to stderr before the usage text, exit 2; added 2026-10-30 by the Plan 6 preflight, PF-11) | -it takes no --idempotency-key. a session is never repeated by a retry | approved |
-| RFS-6-C66 | apps_swap.go (a fragment: the first line of appsSetUsage, adding the --interactive flag; supersedes the approved first line of the zero-downtime record zdd.apps-set.usage and the instance-policy record GAP-2, which change with it and are marked superseded by RFS-6-C66; added 2026-10-31, the Task 4 report's concern 2) | usage: carlos apps set <app> [--swap overlap\|hold] [--swap-concurrency <n>] [--interactive on\|off] [--account <sqid\|name>] [--account-id <sqid>] [--console <origin>] [--egress-allow <ip,...>] [--size small\|standard\|large\|xlarge\|default] | approved |
+| RFS-6-C66 | apps_swap.go (a fragment: superseded verbatim by SR-2-C13 for Plan 2 slice 1a; the first line of appsSetUsage, adding the --interactive flag; supersedes the approved first line of the zero-downtime record zdd.apps-set.usage and the instance-policy record GAP-2, which change with it and are marked superseded by RFS-6-C66; added 2026-10-31, the Task 4 report's concern 2) | usage: carlos apps set <app> [--copies <n>] [--swap overlap\|hold] [--swap-concurrency <n>] [--interactive on\|off] [--account <sqid\|name>] [--account-id <sqid>] [--console <origin>] [--egress-allow <ip,...>] [--size <size>] | approved |
| RFS-6-C67 | apps_swap.go (appsSetInteractiveNotFound: `carlos apps set <app> --interactive` when the console answers 404 with no JSON error; added 2026-10-31, the Task 4 report's concern 3) | not found: either %s is not an app in this account, or this console predates --interactive (update the console, then run this again) | approved |
| RFS-6-C68 | internal/console/apiinstanceimport.go (handleAPIImportAbort: an import's abort while an interactive session is open, provision.ErrInteractiveOpen, HTTP 409, beside the open-run refusal; added 2026-10-31) | An interactive session is open on %s. Wait for it to end, then abort. | approved |
| RFS-6-C69 | internal/host/interactive.go (`carlos logs` reason, sessionEndWords, interactive.EndReplaced; added 2026-10-31) | a newer session on the same instance replaced it | approved |
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 3b8cddfec..470ed6705 100644
--- a/docs/superpowers/plans/2026-11-01-stateless-replicas-copy.md
+++ b/docs/superpowers/plans/2026-11-01-stateless-replicas-copy.md
@@ -47,7 +47,7 @@ copy too. Internal wire enums are not an excuse to expose unreviewed text.
| SR-2-C10 | internal/console/replicaplacement.go | detaching <box> leaves <running> of <desired> copies available. the requested count stays <desired> | approved by delegation (Luna pass, 2026-11-01) |
| SR-2-C11 | internal/console/appcopies.go | copies are still stopping on other boxes. wait for that to finish before selecting a release with a local database | approved by delegation (Luna pass, 2026-11-01) |
| SR-2-C12 | internal/console/appcopies.go | this instance has an import or move in progress. finish it before changing the copy count | approved provisionally (Plan 2 controller ruling P3; Luna flag open for Paul) |
-| SR-2-C13 | apps_swap.go | usage: carlos apps set <app> [--copies <n>] [--swap overlap\|hold] [--swap-concurrency <n>] [--interactive on\|off] [--account <sqid\|name>] [--account-id <sqid>] [--console <origin>] [--egress-allow <ip,...>] [--size <size>] | approved by delegation (Luna pass, 2026-11-01) |
+| SR-2-C13 | apps_swap.go (a fragment: the first line of appsSetUsage) | usage: carlos apps set <app> [--copies <n>] [--swap overlap\|hold] [--swap-concurrency <n>] [--interactive on\|off] [--account <sqid\|name>] [--account-id <sqid>] [--console <origin>] [--egress-allow <ip,...>] [--size <size>] | approved by delegation (Luna pass, 2026-11-01) |
| SR-2-C14 | docs/site/cli.md | Set the count with carlos apps set shop --copies 2. Each instance of shop gets two copies on different eligible fleet boxes. The command refuses a count larger than the eligible fleet. | approved by delegation (Luna pass, 2026-11-01) |
| SR-2-C15 | docs/site/cli.md | If a box is lost or detached, the requested count stays the same. The platform uses a distinct spare when one is available, otherwise the app runs short until a suitable box returns. | approved by delegation (Luna pass, 2026-11-01) |
| SR-2-C16 | internal/console/appcopies.go | more than one copy requires overlap deploys. select an overlap-compatible release and app policy first | approved provisionally (Plan 2 controller ruling P3; Luna flag open for Paul) |
diff --git a/internal/appconfig/appconfig.go b/internal/appconfig/appconfig.go
index b2b0ab46a..b9a3a1ac6 100644
--- a/internal/appconfig/appconfig.go
+++ b/internal/appconfig/appconfig.go
@@ -24,6 +24,8 @@ import (
// Manifest holds every config var and secret an app has set, together so a
// host materializes both with one bucket fetch.
type Manifest struct {
+ // Copies belongs to the default bundle only; zero means one copy.
+ Copies int `json:"copies,omitempty"`
Schema int `json:"schema"` // 1
App string `json:"app"`
Vars map[string]Var `json:"vars"`
diff --git a/internal/appconfig/copies.go b/internal/appconfig/copies.go
new file mode 100644
index 000000000..d6885c0df
--- /dev/null
+++ b/internal/appconfig/copies.go
@@ -0,0 +1,56 @@
+package appconfig
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+
+ "github.com/carlosframework/platform/internal/release"
+)
+
+// CopiesOf reads the default bundle's app-wide count. Omission means one.
+func CopiesOf(m *Manifest) int {
+ if m == nil || m.Copies == 0 {
+ return 1
+ }
+ return m.Copies
+}
+
+// SetCopies changes only the default bundle, preserving its other fields.
+// Restoring the default omits the key; an unchanged value writes nothing.
+func SetCopies(ctx context.Context, s release.Store, acct, app string, n int) (int, error) {
+ var stored int
+ err := release.WithAppMutation(ctx, s, acct, app, "appconfig.SetCopies", func(ctx context.Context) error {
+ if !release.ValidAccount(acct) || !release.ValidApp(app) {
+ return fmt.Errorf("config: invalid account/app %q/%q", acct, app)
+ }
+ if n < 1 {
+ return fmt.Errorf("copies must be a whole number of at least 1")
+ }
+ key := Key(acct, app)
+ m, etag, _, err := getForWriteAt(ctx, s, key, app)
+ if err != nil {
+ return err
+ }
+ if CopiesOf(&m) == n {
+ stored = n
+ return nil
+ }
+ m.Copies = n
+ if n == 1 {
+ m.Copies = 0
+ }
+ m.Schema, m.App = manifestSchema(&m), app
+ raw, err := json.MarshalIndent(m, "", " ")
+ if err != nil {
+ return err
+ }
+ if _, err = s.Put(ctx, key, raw, etag); err != nil {
+ return err
+ }
+ touchLogged(ctx, s, acct, app)
+ stored = n
+ return nil
+ })
+ return stored, err
+}
diff --git a/internal/appconfig/copies_test.go b/internal/appconfig/copies_test.go
new file mode 100644
index 000000000..4f4d1a8b1
--- /dev/null
+++ b/internal/appconfig/copies_test.go
@@ -0,0 +1,61 @@
+package appconfig
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "os"
+ "reflect"
+ "testing"
+
+ "github.com/carlosframework/platform/internal/release"
+)
+
+func TestCopiesDefaultsAndBounds(t *testing.T) {
+ ctx := context.Background()
+ s := release.NewDirStore(t.TempDir())
+ if CopiesOf(nil) != 1 || CopiesOf(&Manifest{}) != 1 {
+ t.Fatal("absent copies must resolve to one")
+ }
+ for _, n := range []int{-1, 0} {
+ if _, err := SetCopies(ctx, s, "bab", "shop", n); err == nil {
+ t.Fatalf("accepted %d", n)
+ }
+ }
+ if n, err := SetCopies(ctx, s, "bab", "shop", 1); err != nil || n != 1 {
+ t.Fatalf("default: %d %v", n, err)
+ }
+ if _, _, err := s.Get(ctx, Key("bab", "shop")); !errors.Is(err, os.ErrNotExist) {
+ t.Fatalf("default wrote config: %v", err)
+ }
+ before := Manifest{Schema: 1, App: "shop", Vars: map[string]Var{"A": {Kind: "env", Value: "1"}, "SECRET": {Kind: "secret", Envelope: "sealed", SealedTo: "key"}}, Swap: SwapHold, SwapConcurrency: 3, Interactive: true, ExecDelivery: ExecDeliveryFile}
+ raw, _ := json.Marshal(before)
+ if _, err := s.Put(ctx, Key("bab", "shop"), raw, ""); err != nil {
+ t.Fatal(err)
+ }
+ if n, err := SetCopies(ctx, s, "bab", "shop", 2); err != nil || n != 2 {
+ t.Fatalf("set: %d %v", n, err)
+ }
+ got, err := Get(ctx, s, "bab", "shop")
+ if err != nil {
+ t.Fatal(err)
+ }
+ before.Copies = 2
+ if !reflect.DeepEqual(*got, before) {
+ t.Fatalf("lost bundle fields: %+v", got)
+ }
+ if err := SetEnv(ctx, s, "bab", "shop", map[string]string{"B": "2"}); err != nil {
+ t.Fatal(err)
+ }
+ got, _ = Get(ctx, s, "bab", "shop")
+ if CopiesOf(got) != 2 {
+ t.Fatal("ordinary writer lost copies")
+ }
+ if _, err := SetCopies(ctx, s, "bab", "shop", 1); err != nil {
+ t.Fatal(err)
+ }
+ got, _ = Get(ctx, s, "bab", "shop")
+ if got.Copies != 0 {
+ t.Fatal("default was not omitted")
+ }
+}
diff --git a/internal/console/appcopies.go b/internal/console/appcopies.go
new file mode 100644
index 000000000..f9e95f1d4
--- /dev/null
+++ b/internal/console/appcopies.go
@@ -0,0 +1,293 @@
+package console
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "io"
+ "net/http"
+ "time"
+
+ "github.com/carlosframework/platform/internal/appconfig"
+ "github.com/carlosframework/platform/internal/provision"
+ "github.com/carlosframework/platform/internal/registry"
+ "github.com/carlosframework/platform/internal/release"
+ "github.com/carlosframework/platform/internal/status"
+ "github.com/carlosframework/platform/internal/version"
+)
+
+const (
+ copiesBounds = "copies must be a whole number of at least 1"
+ copiesCapacity = "%d copies need %d eligible boxes. this fleet has %d"
+ copiesRelease = "more than one copy requires a stateless, always-on release. set --copies 1 before selecting this release"
+ copiesFloor = "copies above 1 need every fleet box and the console on %s or later. update them and try again"
+ copiesUnread = "could not check every instance, release and fleet box, so the copy count was left unchanged. try again"
+ copiesManaged = "more than one copy is available for platform-managed instances on an owned fleet only"
+ copiesMoving = "this instance has an import or move in progress. finish it before changing the copy count"
+ copiesOverlap = "more than one copy requires overlap deploys. select an overlap-compatible release and app policy first"
+)
+
+func atReplicaFloor(build string) bool {
+ v, ok := release.ParseReleaseVersion(build)
+ floor, valid := release.ParseReleaseVersion(release.StatelessReplicasFloor)
+ return ok && valid && v.Compare(floor) >= 0
+}
+
+func (v *fleetView) replicasActive(consoleRelease string) bool {
+ if v == nil || !v.Active || len(v.Boxes) == 0 || !atReplicaFloor(consoleRelease) {
+ return false
+ }
+ for _, b := range v.Boxes {
+ if !b.Fresh || !b.AtReplicaFloor {
+ return false
+ }
+ }
+ return true
+}
+
+// replicaEligible is shared by count admission and copy placement.
+func (v *fleetView) replicaEligible(b fleetBoxView, rootfs bool) bool {
+ return b.AtReplicaFloor && b.destinationFor(rootfs)
+}
+
+func (s *Server) handleAPICopies(w http.ResponseWriter, r *http.Request) {
+ addr, acct, app, ok := s.apiAccountApp(w, r)
+ if !ok {
+ return
+ }
+ p, _ := principalFrom(r.Context())
+ if !s.allowWrite(p, time.Now()) {
+ jsonError(w, http.StatusTooManyRequests, apiSwapLimited)
+ return
+ }
+ var req struct {
+ Copies *int `json:"copies"`
+ Message string `json:"message,omitempty"`
+ }
+ d := json.NewDecoder(http.MaxBytesReader(w, r.Body, 8<<10))
+ d.DisallowUnknownFields()
+ if d.Decode(&req) != nil || d.Decode(new(any)) != io.EOF || req.Copies == nil || *req.Copies < 1 {
+ jsonError(w, http.StatusBadRequest, copiesBounds)
+ return
+ }
+ message, ok := checkedActivityMessage(w, req.Message)
+ if !ok {
+ return
+ }
+ if s.cfg.Releases == nil {
+ jsonError(w, http.StatusServiceUnavailable, copiesUnread)
+ return
+ }
+ ctx, cancel := context.WithTimeout(r.Context(), configStoreTimeout)
+ defer cancel()
+ // The existing app lock covers validation and publication. SetCopies joins
+ // the claim mutation through ctx and does not acquire this mutex itself.
+ defer s.lockApp(acct.Sqid, app)()
+ var ref *doorRefusal
+ var got int
+ err := s.claimAppMutation(ctx, acct, app, "copies", func(ctx context.Context) error {
+ ref = s.copiesRefusal(ctx, acct, app, *req.Copies, nil)
+ if ref != nil {
+ return &statelessSelectionError{ref}
+ }
+ var err error
+ got, err = appconfig.SetCopies(ctx, s.cfg.Releases, acct.Sqid, app, *req.Copies)
+ return err
+ })
+ if ref != nil {
+ jsonError(w, ref.Status, ref.Msg)
+ return
+ }
+ if err != nil {
+ s.configStoreError(w, "api copies", err)
+ return
+ }
+ s.auditActivity(acct, app, addr, Activity{Action: "copies", TargetType: "app", Target: app, Message: message, Detail: fmt.Sprintf("%s: %d copies requested for each instance", app, got)})
+ s.bumpSerial(ctx)
+ writeJSON(w, http.StatusOK, map[string]int{"copies": got})
+}
+
+// copiesRefusal is called under the app mutation boundary. target, when
+// present, is the canonical release about to be selected by another door.
+// A default count leaves legacy paths untouched and reads no evidence.
+func (s *Server) copiesRefusal(ctx context.Context, acct *Account, app string, n int, target *release.Manifest) *doorRefusal {
+ refuse := func(msg string) *doorRefusal { return &doorRefusal{http.StatusConflict, msg} }
+ unread := func() *doorRefusal { return &doorRefusal{http.StatusServiceUnavailable, copiesUnread} }
+ if n < 1 {
+ return &doorRefusal{http.StatusBadRequest, copiesBounds}
+ }
+ if n == 1 {
+ return nil
+ }
+ if s.cfg.Releases == nil {
+ return unread()
+ }
+ ctx = withWriteMemo(ctx)
+ placed, err := s.store.AppPlacement(acct.ID, app)
+ if err != nil {
+ return unread()
+ }
+ fleet, ok := registry.FleetPlacement(placed)
+ if !ok {
+ return refuse(copiesManaged)
+ }
+ reg, err := s.openPassRegistry()
+ if err != nil {
+ return unread()
+ }
+ own, err := ownsFleet(reg, acct, placed)
+ if err != nil {
+ return unread()
+ }
+ if !own {
+ return refuse(copiesManaged)
+ }
+ recs, err := placeRecords(ctx, s.cfg.Releases, provision.JudgeFrom(ctx), acct.Sqid, app)
+ if err != nil {
+ return unread()
+ }
+ sidecars, err := provision.ListSidecarRecordsStrict(ctx, s.cfg.Releases, acct.Sqid, app)
+ if err != nil {
+ return unread()
+ }
+ if len(sidecars) > 0 {
+ return refuse(copiesManaged)
+ }
+ m, err := appconfig.Get(ctx, s.cfg.Releases, acct.Sqid, app)
+ if err != nil {
+ return unread()
+ }
+ if appconfig.PolicyOf(m).Swap != appconfig.SwapOverlap {
+ return refuse(copiesOverlap)
+ }
+ check := func(m *release.Manifest) *doorRefusal {
+ if m == nil {
+ return unread()
+ }
+ if !m.Stateless || m.Hibernate {
+ return refuse(copiesRelease)
+ }
+ if m.Kind != "binary" && m.Kind != release.KindRootfs && m.Kind != "" {
+ return refuse(copiesManaged)
+ }
+ if release.NormalizeDemand(m.Swap) == release.DemandHold {
+ return refuse(copiesOverlap)
+ }
+ return nil
+ }
+ if target != nil {
+ if ref := check(target); ref != nil {
+ return ref
+ }
+ }
+ rootfs := target != nil && target.Kind == release.KindRootfs
+ for _, rec := range recs {
+ if rec.Retired {
+ continue
+ }
+ if rec.Move != nil || rec.Seed.BlocksRun() {
+ return refuse(copiesMoving)
+ }
+ if rec.Region != placed || rec.Pool != "" || rec.HA || rec.Role != "" || len(rec.Replicas) > 0 || !rec.DerivesPaths() {
+ return refuse(copiesManaged)
+ }
+ if rec.Runtime != provision.RuntimeRootfsV1 && (rec.Hibernate == nil || *rec.Hibernate) {
+ return refuse(copiesRelease)
+ }
+ rootfs = rootfs || rec.Runtime == provision.RuntimeRootfsV1
+ }
+ v, err := s.loadFleetView(ctx, fleet)
+ if err != nil || !v.Active {
+ return unread()
+ }
+ build := s.consoleBuild
+ if build == "" {
+ build = version.Build
+ }
+ if !v.replicasActive(build) {
+ return refuse(fmt.Sprintf(copiesFloor, release.StatelessReplicasFloor))
+ }
+ available := 0
+ for _, b := range v.Boxes {
+ if v.replicaEligible(b, rootfs) {
+ available++
+ }
+ }
+ if n > available {
+ return refuse(fmt.Sprintf(copiesCapacity, n, n, available))
+ }
+ // Reuse the heartbeat read already memoized by loadFleetView. Only this
+ // fleet's current roster can supply evidence about an instance's build.
+ beats, complete, err := s.loadBoxes(ctx, s.cfg.Releases, "fleets/"+fleet+"/")
+ if err != nil || !complete {
+ return unread()
+ }
+ versions := map[string]*release.Manifest{}
+ verify := func(ver string) *doorRefusal {
+ if ver == "" {
+ return unread()
+ }
+ m, ok := versions[ver]
+ if !ok {
+ var err error
+ m, err = release.AuthorizedManifest(ctx, s.cfg.Releases, s.cfg.ReleasePub, acct.Sqid, app, ver)
+ if err != nil {
+ return unread()
+ }
+ versions[ver] = m
+ }
+ return check(m)
+ }
+ for _, rec := range recs {
+ if rec.Retired {
+ continue
+ }
+ var reported bool
+ for _, b := range beats {
+ roster := false
+ for _, box := range v.Boxes {
+ if box.Label == b.Label && (rec.FleetBox == "" || rec.FleetBox == b.Label) {
+ roster = true
+ break
+ }
+ }
+ if !roster {
+ continue
+ }
+ j := joinBoxes([]status.Box{b}, time.Now())
+ r := j.rollout(rec.Host, acct.Sqid, app)
+ if r == nil || r.refused || !r.at.After(rec.CreatedAt) || r.Serving == "" {
+ continue
+ }
+ reported = true
+ for _, ver := range []string{r.Serving, r.Installed, r.AttemptBuild} {
+ if ver != "" {
+ if ref := verify(ver); ref != nil {
+ return ref
+ }
+ }
+ }
+ if u := j.update(rec.Host, acct.Sqid, app); u != nil && u.Desired != "" {
+ if ref := verify(u.Desired); ref != nil {
+ return ref
+ }
+ }
+ }
+ if !reported {
+ return unread()
+ }
+ head, err := release.Channel(ctx, s.cfg.Releases, s.cfg.ReleasePub, acct.Sqid, app, rec.Channel)
+ if err != nil || head == nil {
+ return unread()
+ }
+ if ref := verify(head.Version); ref != nil {
+ return ref
+ }
+ if rec.Pin != "" {
+ if ref := verify(rec.Pin); ref != nil {
+ return ref
+ }
+ }
+ }
+ return nil
+}
diff --git a/internal/console/appcopies_test.go b/internal/console/appcopies_test.go
new file mode 100644
index 000000000..3c203de7c
--- /dev/null
+++ b/internal/console/appcopies_test.go
@@ -0,0 +1,328 @@
+package console
+
+import (
+ "context"
+ "encoding/json"
+ "net/http"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/appconfig"
+ "github.com/carlosframework/platform/internal/provision"
+ "github.com/carlosframework/platform/internal/release"
+ "github.com/carlosframework/platform/internal/seeds"
+ "github.com/carlosframework/platform/internal/status"
+)
+
+func copiesWorld(t *testing.T) (*consoleFixture, string) {
+ t.Helper()
+ fx, token, _ := fleetBoxWorld(t, "copies", "pi-1", "pi-2")
+ fx.srv.consoleBuild = release.StatelessReplicasFloor
+ for i, host := range []string{"a.example.com", "b.example.com"} {
+ channel := []string{"edge", "stable"}[i]
+ putFleetRecord(t, fx, "shop", host, func(r *provision.Record) {
+ r.Channel = channel
+ r.Hibernate = new(bool)
+ r.FleetBox = []string{"pi-1", "pi-2"}[i]
+ })
+ }
+ shipStatelessFloorRelease(t, fx, "shop", "v1")
+ shipStatelessFloorRelease(t, fx, "shop", "v2")
+ if err := release.Promote(context.Background(), fx.rel, fx.priv, fx.sqid, "shop", "edge", "v1"); err != nil {
+ t.Fatal(err)
+ }
+ if err := release.Promote(context.Background(), fx.rel, fx.priv, fx.sqid, "shop", "stable", "v2"); err != nil {
+ t.Fatal(err)
+ }
+ for _, box := range []string{"pi-1", "pi-2"} {
+ copiesBeat(t, fx, box, release.StatelessReplicasFloor, time.Now())
+ }
+ return fx, token
+}
+func copiesManifest(t *testing.T, fx *consoleFixture, stateless, hibernate bool, swap string) {
+ t.Helper()
+ ctx := context.Background()
+ key := release.ManifestKey(fx.sqid, "shop", "v2")
+ raw, etag, err := fx.rel.Get(ctx, key)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var m release.Manifest
+ if err = json.Unmarshal(raw, &m); err != nil {
+ t.Fatal(err)
+ }
+ m.Stateless, m.Hibernate, m.Swap = stateless, hibernate, swap
+ art := release.Artifact{File: "app", SHA256: strings.Repeat("a", 64), Size: 3}
+ m.Kind = "binary"
+ m.Processes = nil
+ m.Artifacts = map[string]release.Artifact{"linux-amd64": art}
+ if hibernate {
+ m.Kind = release.KindRootfs
+ art.File = release.RootfsArtifactFile
+ m.Artifacts = map[string]release.Artifact{release.RootfsArtifactKey: art}
+ m.Processes = map[string]release.Process{"web": {Command: []string{"/app"}}}
+ }
+
+ raw, _ = json.Marshal(m)
+ if _, err = fx.rel.Put(ctx, key, raw, etag); err != nil {
+ t.Fatal(err)
+ }
+ if err := release.RootSigner(fx.priv).WritePromotionRecord(ctx, fx.rel, release.PromotionRecord{Account: fx.sqid, App: "shop", Version: "v2", ManifestDigest: release.ManifestDigest(raw), Authorized: true}); err != nil {
+ t.Fatal(err)
+ }
+}
+func copiesBeat(t *testing.T, fx *consoleFixture, box, rel string, at time.Time) {
+ t.Helper()
+ hosts := map[string]status.HostRollout{}
+ host := "a.example.com"
+ if box == "pi-2" {
+ host = "b.example.com"
+ }
+ ver := "v1"
+ if box == "pi-2" {
+ ver = "v2"
+ }
+ hosts[host] = status.HostRollout{Account: fx.sqid, App: "shop", Serving: ver, Installed: ver, Awake: true}
+ b := status.Box{Label: box, GeneratedAt: at, Metrics: &status.BoxMetrics{Release: rel, RootfsReady: true, Rollout: &status.RolloutReport{Hosts: hosts}}}
+ if err := status.WriteBox(context.Background(), release.NewPrefixStore(fx.rel, "fleets/pi/"), b); err != nil {
+ t.Fatal(err)
+ }
+}
+func copiesPut(t *testing.T, fx *consoleFixture, token, body string) (int, string) {
+ t.Helper()
+ code, _, out := rawReq(t, http.MethodPut, fx.ts.URL+"/api/cli/apps/"+fx.sqid+"/shop/copies", token, body)
+ return code, out
+}
+func TestCopiesApplyToEveryInstance(t *testing.T) {
+ fx, token := copiesWorld(t)
+ if code, out := copiesPut(t, fx, token, `{"copies":2}`); code != 200 {
+ t.Fatalf("set: %d %s", code, out)
+ }
+ m, err := appconfig.Get(context.Background(), fx.rel, fx.sqid, "shop")
+ if err != nil {
+ t.Fatal(err)
+ }
+ hostACopies, hostBCopies := appconfig.CopiesOf(m), appconfig.CopiesOf(m)
+ counter := &copiesWriteCounter{Store: fx.rel, key: appconfig.Key(fx.sqid, "shop")}
+ fx.srv.cfg.Releases = counter
+ before, etag, _ := fx.rel.Get(context.Background(), appconfig.Key(fx.sqid, "shop"))
+ copiesManifest(t, fx, false, false, "")
+ if code, _ := copiesPut(t, fx, token, `{"copies":2}`); code != 409 {
+ t.Fatalf("stateful: %d", code)
+ }
+ after, next, _ := fx.rel.Get(context.Background(), appconfig.Key(fx.sqid, "shop"))
+ statefulAdmissionWrites := counter.writes
+ if string(before) != string(after) || etag != next {
+ statefulAdmissionWrites++
+ }
+ if hostACopies != 2 || hostBCopies != 2 || statefulAdmissionWrites != 0 {
+ t.Fatal("app count or admission was not applied to every host")
+ }
+ for _, tc := range []struct {
+ name string
+ hibernate bool
+ swap string
+ }{{"hibernate", true, ""}, {"demand", false, release.DemandHold}} {
+ t.Run(tc.name, func(t *testing.T) {
+ copiesManifest(t, fx, true, tc.hibernate, tc.swap)
+ if code, _ := copiesPut(t, fx, token, `{"copies":2}`); code != 409 {
+ t.Fatalf("accepted: %d", code)
+ }
+ })
+ }
+ copiesManifest(t, fx, true, false, "")
+ if _, err := appconfig.SetSwapPolicy(context.Background(), fx.rel, fx.sqid, "shop", "hold", 0); err != nil {
+ t.Fatal(err)
+ }
+ if code, out := copiesPut(t, fx, token, `{"copies":2}`); code != 409 || !strings.Contains(out, "overlap deploys") {
+ t.Fatalf("policy: %d %s", code, out)
+ }
+}
+func TestCopiesDefaultsAndBounds(t *testing.T) {
+ fx, token := copiesWorld(t)
+ for _, body := range []string{`{}`, `{"copies":-1}`, `{"copies":0}`, `{"copies":1.5}`, `{"copies":999999999999999999999999}`} {
+ if code, _ := copiesPut(t, fx, token, body); code != 400 {
+ t.Fatalf("%s: %d", body, code)
+ }
+ }
+ if code, out := copiesPut(t, fx, token, `{"copies":3}`); code != 409 || !strings.Contains(out, "3 copies need 3 eligible boxes") {
+ t.Fatalf("capacity: %d %s", code, out)
+ }
+ if code, out := copiesPut(t, fx, token, `{"copies":1}`); code != 200 {
+ t.Fatalf("default: %d %s", code, out)
+ }
+}
+func TestCopiesReleaseFloorComplete(t *testing.T) {
+ for _, v := range []string{"v0.34.0", "", "dev", release.StatelessReplicasFloor} {
+ t.Run("box-"+v, func(t *testing.T) {
+ fx, token := copiesWorld(t)
+ at := time.Now()
+ if v == release.StatelessReplicasFloor {
+ at = at.Add(-time.Hour)
+ }
+ copiesBeat(t, fx, "pi-2", v, at)
+ if code, out := copiesPut(t, fx, token, `{"copies":2}`); code != 409 {
+ t.Fatalf("floor: %d %s", code, out)
+ }
+ })
+ }
+ for _, v := range []string{"v0.34.0", "dev", ""} {
+ t.Run("console-"+v, func(t *testing.T) {
+ fx, token := copiesWorld(t)
+ fx.srv.consoleBuild = v
+ if code, out := copiesPut(t, fx, token, `{"copies":2}`); code != 409 {
+ t.Fatalf("floor: %d %s", code, out)
+ }
+ })
+ }
+}
+
+type copiesWriteCounter struct {
+ release.Store
+ key string
+ writes int
+}
+
+func (s *copiesWriteCounter) Put(ctx context.Context, key string, body []byte, etag string) (string, error) {
+ if key == s.key {
+ s.writes++
+ }
+ return s.Store.Put(ctx, key, body, etag)
+}
+
+func TestCopiesRefusesUnsupportedInstances(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ mut func(*provision.Record)
+ want string
+ }{
+ {"shared-region", func(r *provision.Record) { r.Region = "ie" }, copiesManaged},
+ {"ha", func(r *provision.Record) { r.HA = true }, copiesManaged},
+ {"static", func(r *provision.Record) { r.Kind = "static" }, copiesManaged},
+
+ {"service", func(r *provision.Record) { r.Kind = "service" }, copiesManaged},
+ {"addr", func(r *provision.Record) { r.Addr = "127.0.0.1:8080" }, copiesManaged},
+ {"addrs", func(r *provision.Record) { r.Addrs = []string{"127.0.0.1:8080"} }, copiesManaged},
+ {"move", func(r *provision.Record) { r.Move = &provision.MoveState{} }, copiesMoving},
+ {"import", func(r *provision.Record) {
+ r.Seed = &provision.SeedSource{Kind: seeds.KindImport, State: seeds.StateAwaitingUpload}
+ }, copiesMoving},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ fx, token := copiesWorld(t)
+ ctx := context.Background()
+ key := provision.RecordKey(fx.sqid, "shop", "b.example.com")
+ raw, etag, err := fx.rel.Get(ctx, key)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var r provision.Record
+ if err = json.Unmarshal(raw, &r); err != nil {
+ t.Fatal(err)
+ }
+ tc.mut(&r)
+ raw, _ = json.Marshal(r)
+ if _, err = fx.rel.Put(ctx, key, raw, etag); err != nil {
+ t.Fatal(err)
+ }
+ counter := &copiesWriteCounter{Store: fx.rel, key: appconfig.Key(fx.sqid, "shop")}
+ fx.srv.cfg.Releases = counter
+ code, out := copiesPut(t, fx, token, `{"copies":2}`)
+ if code < 400 || !strings.Contains(out, tc.want) || counter.writes != 0 {
+ t.Fatalf("refusal: %d %s, %d writes", code, out, counter.writes)
+ }
+ })
+ }
+}
+
+func TestCopiesMissingUnreadableAndDrainingFloor(t *testing.T) {
+ for _, kind := range []string{"missing", "unreadable", "draining-old", "draining-current"} {
+ t.Run(kind, func(t *testing.T) {
+ fx, token := copiesWorld(t)
+ ctx := context.Background()
+ key := "fleets/pi/status/boxes/pi-2.json"
+ want := copiesUnread
+ switch kind {
+ case "missing":
+ if err := fx.rel.Delete(ctx, key); err != nil {
+ t.Fatal(err)
+ }
+ want = "copies above 1"
+ case "unreadable":
+ _, etag, _ := fx.rel.Get(ctx, key)
+ if _, err := fx.rel.Put(ctx, key, []byte("broken"), etag); err != nil {
+ t.Fatal(err)
+ }
+ default:
+ reg := openTestReg(t, fx)
+ defer reg.Close()
+ if _, err := reg.SetFleetBoxDraining("pi", "pi-2", time.Now().UnixNano()); err != nil {
+ t.Fatal(err)
+ }
+ want = "2 copies need 2 eligible boxes"
+ if kind == "draining-old" {
+ copiesBeat(t, fx, "pi-2", "v0.34.0", time.Now())
+ want = "copies above 1"
+ }
+ }
+ if code, out := copiesPut(t, fx, token, `{"copies":2}`); code < 400 || !strings.Contains(out, want) {
+ t.Fatalf("%d %s", code, out)
+ }
+ })
+ }
+}
+
+func TestCopiesEvidenceAndEligibility(t *testing.T) {
+ t.Run("unreadable release", func(t *testing.T) {
+ fx, token := copiesWorld(t)
+ key := release.ManifestKey(fx.sqid, "shop", "v2")
+ if err := fx.rel.Delete(context.Background(), key); err != nil {
+ t.Fatal(err)
+ }
+ if code, out := copiesPut(t, fx, token, `{"copies":2}`); code != 503 || !strings.Contains(out, copiesUnread) {
+ t.Fatalf("%d %s", code, out)
+ }
+ })
+ t.Run("canonical digest", func(t *testing.T) {
+ fx, token := copiesWorld(t)
+ key := release.ManifestKey(fx.sqid, "shop", "v2")
+ raw, etag, _ := fx.rel.Get(context.Background(), key)
+ raw = append(raw, ' ')
+ if _, err := fx.rel.Put(context.Background(), key, raw, etag); err != nil {
+ t.Fatal(err)
+ }
+ if code, out := copiesPut(t, fx, token, `{"copies":2}`); code != 503 || !strings.Contains(out, copiesUnread) {
+ t.Fatalf("%d %s", code, out)
+ }
+ })
+ v := fleetView{}
+ b := fleetBoxView{Fresh: true, AtLabelFloor: true, AtReplicaFloor: true, AtRootfsFloor: true, RootfsReady: true}
+ if !v.replicaEligible(b, false) || !v.replicaEligible(b, true) {
+ t.Fatal("eligible refused")
+ }
+ b.RootfsReady = false
+ if v.replicaEligible(b, true) || !v.replicaEligible(b, false) {
+ t.Fatal("rootfs readiness ignored")
+ }
+}
+
+func TestCopiesSidecarsAndSharedPlacement(t *testing.T) {
+ for _, kind := range []string{"sidecar", "shared"} {
+ t.Run(kind, func(t *testing.T) {
+ fx, token := copiesWorld(t)
+ if kind == "shared" {
+ if err := fx.st.SetAppPlacement(OpsAccountID, "shop", "ie"); err != nil {
+ t.Fatal(err)
+ }
+ } else {
+ if err := provision.CreateSidecarRecord(context.Background(), fx.rel, provision.SidecarRecord{Schema: 1, Name: "bot", Host: provision.SidecarHost("bot", "shop", fx.sqid), App: "shop", Account: fx.sqid, Region: "fleet/pi", Channel: "edge", CreatedAt: time.Now().UTC()}); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if code, out := copiesPut(t, fx, token, `{"copies":2}`); code != 409 || !strings.Contains(out, copiesManaged) {
+ t.Fatalf("%d %s", code, out)
+ }
+ })
+ }
+}
diff --git a/internal/console/authcli.go b/internal/console/authcli.go
index 6113e23de..cbcf603e2 100644
--- a/internal/console/authcli.go
+++ b/internal/console/authcli.go
@@ -1019,6 +1019,7 @@ func (s *Server) registerCLIRoutes() {
// The swap policy (zero-downtime spec §4.1, apiswap.go). The ZERO Set:
// §11 says only app members change it, and a credential the app holds
// must not choose what its own migrations run beside.
+ s.cliRoute("PUT /api/cli/apps/{account}/{app}/copies", svcrole.Set{}, s.handleAPICopies)
s.cliRoute("PUT /api/cli/apps/{account}/{app}/swap", svcrole.Set{}, s.handleAPISwapPut)
// The interactive sessions setting (rootfs apps spec §5.10,
// apiinteractivesetting.go). The ZERO Set: a session is a live shell
diff --git a/internal/console/claim_invariant_fixtures_test.go b/internal/console/claim_invariant_fixtures_test.go
index 2d8c27668..31caeafd1 100644
--- a/internal/console/claim_invariant_fixtures_test.go
+++ b/internal/console/claim_invariant_fixtures_test.go
@@ -2221,6 +2221,10 @@ var claimFixtures = map[string]claimFixture{
apps: claimRefs("bab/titogo"),
do: claimAPI(http.MethodPut, "/api/cli/apps/bab/titogo/sidecars-manifest", `{}`),
}},
+ "route PUT /api/cli/apps/{account}/{app}/copies": {door: &claimDoor{
+ apps: claimRefs("bab/titogo"),
+ do: claimAPI(http.MethodPut, "/api/cli/apps/bab/titogo/copies", `{"copies":1}`),
+ }},
"route PUT /api/cli/apps/{account}/{app}/swap": {door: &claimDoor{
apps: claimRefs("bab/titogo"),
do: claimAPI(http.MethodPut, "/api/cli/apps/bab/titogo/swap", `{"swap":"hold"}`),
diff --git a/internal/console/fleetbox.go b/internal/console/fleetbox.go
index 540cdc9d4..a443d334f 100644
--- a/internal/console/fleetbox.go
+++ b/internal/console/fleetbox.go
@@ -61,11 +61,11 @@ type fleetView struct {
// mark (Task 6), Labelled whether the console ever named the box on a
// record.
type fleetBoxView struct {
- Label string
- Fresh, Draining, RootfsReady, AtRootfsFloor, AtLabelFloor bool
- Labelled bool
- LastSeen, DrainingSince time.Time
- Release string
+ Label string
+ Fresh, Draining, RootfsReady, AtRootfsFloor, AtLabelFloor, AtReplicaFloor bool
+ Labelled bool
+ LastSeen, DrainingSince time.Time
+ Release string
}
// fleetBoxViewOf is an active registry box before its heartbeat is read.
@@ -97,6 +97,7 @@ func joinBeats(boxes []fleetBoxView, hbs []status.Box, now time.Time) (unheard b
boxes[i].LastSeen = b.GeneratedAt
if b.Metrics != nil {
boxes[i].Release = b.Metrics.Release
+ boxes[i].AtReplicaFloor = atReplicaFloor(b.Metrics.Release)
}
}
return unheard
diff --git a/internal/console/testdata/claim-routes.txt b/internal/console/testdata/claim-routes.txt
index c6ab3e1fd..cb1ce00a9 100644
--- a/internal/console/testdata/claim-routes.txt
+++ b/internal/console/testdata/claim-routes.txt
@@ -344,6 +344,7 @@ route POST /billing/webhook
route POST /fleet/store/{account}/{decision}
route POST /invite/{token}
route PUT /api/cli/apps/{account}/{app}/config
+route PUT /api/cli/apps/{account}/{app}/copies
route PUT /api/cli/apps/{account}/{app}/domains/{host}/paths
route PUT /api/cli/apps/{account}/{app}/domains/{host}/placements
route PUT /api/cli/apps/{account}/{app}/email/events/push
diff --git a/internal/provision/lifetimeindex.go b/internal/provision/lifetimeindex.go
index 2da5c48c0..34c38a1d1 100644
--- a/internal/provision/lifetimeindex.go
+++ b/internal/provision/lifetimeindex.go
@@ -134,6 +134,12 @@ func (x *LifetimeIndex) ReplicaRecord(host string) (Record, bool) {
func replicaRecordSnapshot(rec Record) Record {
snapshot := Record{Account: rec.Account, App: rec.App, Host: rec.Host, CreatedAt: rec.CreatedAt, HA: rec.HA}
+ if rec.ReplicaAssignment != nil {
+ a := *rec.ReplicaAssignment
+ a.Boxes = append([]string(nil), a.Boxes...)
+ a.Retiring = append([]string(nil), a.Retiring...)
+ snapshot.ReplicaAssignment = &a
+ }
if rec.Coordinator != nil {
c := *rec.Coordinator
snapshot.Coordinator = &c
diff --git a/internal/provision/provision.go b/internal/provision/provision.go
index aee65eb33..cef756d05 100644
--- a/internal/provision/provision.go
+++ b/internal/provision/provision.go
@@ -40,8 +40,9 @@ import (
// Account vs the key's segments); GetRecord and ListRecords enforce that, a
// record that lies about identity is never guessed at (design §3.2).
type Record struct {
- Coordinator *replicas.Coordinator `json:"coordinator,omitempty"`
- ReplicaDeploy *replicas.Deploy `json:"replica_deploy,omitempty"`
+ ReplicaAssignment *replicas.Assignment `json:"replica_assignment,omitempty"`
+ Coordinator *replicas.Coordinator `json:"coordinator,omitempty"`
+ ReplicaDeploy *replicas.Deploy `json:"replica_deploy,omitempty"`
// RecordSeq is advanced by every record writer once present; absent is legacy zero.
RecordSeq uint64 `json:"record_seq,omitempty"`
Acquisition string `json:"acq,omitempty"`
diff --git a/internal/provision/replicaassignment_test.go b/internal/provision/replicaassignment_test.go
new file mode 100644
index 000000000..d9d376600
--- /dev/null
+++ b/internal/provision/replicaassignment_test.go
@@ -0,0 +1,48 @@
+package provision
+
+import (
+ "context"
+ "encoding/json"
+ "reflect"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/release"
+ "github.com/carlosframework/platform/internal/replicas"
+)
+
+func TestReplicaAssignmentOrdinaryWritersPreserve(t *testing.T) {
+ ctx := context.Background()
+ s := release.NewDirStore(t.TempDir())
+ rec := Record{Schema: 1, Account: "bab", App: "shop", Host: "shop.example.com", Slug: "shop", Channel: "edge", CreatedAt: time.Now().UTC()}
+ if err := CreateRecord(ctx, s, rec); err != nil {
+ t.Fatal(err)
+ }
+ key := RecordKey(rec.Account, rec.App, rec.Host)
+ raw, etag, _ := s.Get(ctx, key)
+ if err := json.Unmarshal(raw, &rec); err != nil {
+ t.Fatal(err)
+ }
+ want := &replicas.Assignment{Revision: 7, Desired: 2, Boxes: []string{"a", "b"}, Retiring: []string{"c"}}
+ rec.ReplicaAssignment = want
+ raw, _ = json.Marshal(rec)
+ if _, err := s.Put(ctx, key, raw, etag); err != nil {
+ t.Fatal(err)
+ }
+ for _, mut := range []func(*Record) error{
+ func(r *Record) error { r.ReplicaAssignment = nil; return nil },
+ func(r *Record) error { r.ReplicaAssignment.Boxes[0] = "spoofed"; return nil },
+ func(r *Record) error { r.ReplicaAssignment.Retiring = nil; return nil },
+ } {
+ if _, err := updateRecord(ctx, s, rec.Account, rec.App, rec.Host, mut); err == nil {
+ t.Fatal("ordinary writer changed assignment")
+ }
+ }
+ if _, err := updateRecord(ctx, s, rec.Account, rec.App, rec.Host, func(r *Record) error { r.Channel = "stable"; return nil }); err != nil {
+ t.Fatal(err)
+ }
+ got, err := GetRecord(ctx, s, rec.Account, rec.App, rec.Host)
+ if err != nil || !reflect.DeepEqual(got.ReplicaAssignment, want) {
+ t.Fatalf("assignment lost: %+v %v", got, err)
+ }
+}
diff --git a/internal/provision/replicacoordinator.go b/internal/provision/replicacoordinator.go
index f9b53e1c3..cad940f94 100644
--- a/internal/provision/replicacoordinator.go
+++ b/internal/provision/replicacoordinator.go
@@ -55,12 +55,16 @@ func replicaFieldsFixed(ctx context.Context, before, body []byte) error {
return nil
}
var old, next struct {
- Coordinator *replicas.Coordinator `json:"coordinator"`
- ReplicaDeploy *replicas.Deploy `json:"replica_deploy"`
+ ReplicaAssignment *replicas.Assignment `json:"replica_assignment"`
+ Coordinator *replicas.Coordinator `json:"coordinator"`
+ ReplicaDeploy *replicas.Deploy `json:"replica_deploy"`
}
if json.Unmarshal(before, &old) != nil || json.Unmarshal(body, &next) != nil {
return ErrRecordSequence
}
+ if !reflect.DeepEqual(old.ReplicaAssignment, next.ReplicaAssignment) {
+ return replicas.ErrFenced
+ }
field, _ := ctx.Value(replicaWriteKey{}).(string)
if field != "coordinator" && !reflect.DeepEqual(old.Coordinator, next.Coordinator) {
return replicas.ErrFenced
diff --git a/internal/replicas/assignment.go b/internal/replicas/assignment.go
new file mode 100644
index 000000000..21182b8c3
--- /dev/null
+++ b/internal/replicas/assignment.go
@@ -0,0 +1,17 @@
+package replicas
+
+// Assignment is the requested placement of one instance's copies.
+type Assignment struct {
+ Revision uint64 `json:"revision,omitempty"`
+ Desired int `json:"desired,omitempty"`
+ Boxes []string `json:"boxes,omitempty"`
+ Retiring []string `json:"retiring,omitempty"`
+}
+
+// Expect identifies the lifetime and revisions an assignment edit observed.
+type Expect struct {
+ Incarnation string `json:"incarnation,omitempty"`
+ Region string `json:"region,omitempty"`
+ Revision uint64 `json:"revision,omitempty"`
+ RecordSeq uint64 `json:"record_seq,omitempty"`
+}