feat: set app copy counts with fleet release gates
Finish Plan 2 Task 1 by gating publication and instance creation against the app count, canonical release and outstanding replica assignments. Serialize admission with publication and fence app incarnation changes. Apply P7: share one default-config read per mutation and retain copies:1 after a decrease. Return the admitted create record and account for the first rootfs instance when checking destination capacity. Cover pending, browser, channel, rollback, hold and ship paths. Verify targeted and race tests, three mutations, claim/read and performance gates, approved copy and moves, build/vet, and all three cross-builds. Update census inventories with notes and prepare the root proposal; independent review and #280 approval remain controller-owned.
Co-Authored-By: Codex (gpt-6-astra) <noreply@openai.com>
approved_moves_copy_test.go+7 −0approved_stateless_replicas_copy_test.go+1 −1apps_updates_test.go+2 −2docs/superpowers/notes/census-proposal-stateless-replicas-2.md+13 −0internal/appconfig/copies.go+2 −4internal/appconfig/copies_test.go+2 −2internal/appconfig/swap.go+8 −3internal/console/apicli.go+32 −0internal/console/apiinstances.go+37 −1internal/console/apiinstanceseed.go+2 −1internal/console/apiship_rootfs.go+13 −1internal/console/apisidecars.go+11 −1internal/console/apiswap.go+7 −1internal/console/apiupdates.go+11 −0internal/console/appcopies.go+46 −13internal/console/appcopies_test.go+2 −2internal/console/appswap.go+8 −1internal/console/channelmove.go+22 −2internal/console/copiespublication.go+281 −0internal/console/copiespublication_test.go+612 −0internal/console/hostsused.go+16 −8internal/console/lifetimes_create.go+4 −0internal/console/pendinghandlers.go+15 −0internal/console/perfwrites_test.go+8 −4internal/console/record_write_lock_test.go+15 −0internal/console/reqmemo.go+1 −1internal/console/rootfs.go+7 −0internal/console/rootfs_move_test.go+8 −2internal/console/server.go+37 −0internal/console/svcroutes_test.go+1 −0internal/console/updatescore.go+19 −2internal/provision/plan9_b8_census_test.go+1 −1internal/provision/stateless_placement_census_test.go+42 −0internal/provision/testdata/plan14-root-reads-chain.tsv+1 −0internal/provision/testdata/plan14-root-reads-stateless-replicas-2.tsv+6 −0
CI failed — run details
Intent
<task-notification> <task-id>bx5s5wbki</task-id> <tool-use-id>toolu_01Mbga9JBc7npxvjyGRD2a1n</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/7c5a7d70-0e28-42b9-896c-5d73b2d2a05d/tasks/bx5s5wbki.output</output-file> <status>completed</status> <summary>Background command "Wait for Astra 1a to finish or stall" completed (exit code 0)</summary> </task-notification>
<task-notification> <task-id>bai5mnzxu</task-id> <tool-use-id>toolu_01UCCkcw7CnZGFTXHLNpJJpy</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/7c5a7d70-0e28-42b9-896c-5d73b2d2a05d/tasks/bai5mnzxu.output</output-file> <status>completed</status> <summary>Background command "Wait for 1b completion and report CI verdict" completed (exit code 0)</summary> </task-notification>
Attributed to this commit: 38.1 g CO₂e (2,976,171 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/approved_moves_copy_test.go b/approved_moves_copy_test.go| index 3af53c67a..af7993a5d 100644 |
| --- a/approved_moves_copy_test.go |
| +++ b/approved_moves_copy_test.go |
| @@ -1997,6 +1997,13 @@ func TestMovesExemptionHolds(t *testing.T) { |
| func TestMovesLegacyExemptionsAreLegacy(t *testing.T) { |
| base := movesScanBaseRef(t) |
| approvedElsewhere := rootfsBuiltTexts(mustParseRootfsRecord(t)) |
| + // Plan 2 reuses its built, approved SR copy at legacy instance doors. |
| + // This is cross-deck approval, not an exemption claiming main said it. |
| + for _, row := range builtRows(statelessReplicaCopyRows(t), statelessReplicaBuiltCopy) { |
| + if row.Status == "approved" { |
| + approvedElsewhere[rootfsAppliedText(row.Text)] = true |
| + } |
| + } |
| // The instance policy deck's approved texts (Luna pass, 2026-10-26): |
| // IP1-40 answers main's create door in apicli.go. |
| for p := range instancePolicyApprovedPatterns(t) { |
diff --git a/approved_stateless_replicas_copy_test.go b/approved_stateless_replicas_copy_test.go| index c24419dcc..1a95ac988 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-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"} |
| +var statelessReplicaBuiltCopy = []string{"SR-2-C11", "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_updates_test.go b/apps_updates_test.go| index e9614b2ee..d8a9a8b86 100644 |
| --- a/apps_updates_test.go |
| +++ b/apps_updates_test.go |
| @@ -295,8 +295,8 @@ func TestAppsSetInteractiveAloneIsSomethingToSet(t *testing.T) { |
| var none doorLog |
| err := appsSetRun(context.Background(), appsSetConsole(t, &none), apiAcct{Seg: "bah"}, "shop", nil, nil, nil, nil) |
| - if err == nil || err.Error() != "apps set: nothing to set. Pass --swap, --swap-concurrency, --egress-allow, --size or --interactive" { |
| - t.Fatalf("all four nil: %v, want exactly RFS-6-C47", err) |
| + if err == nil || err.Error() != "apps set: nothing to set. pass --copies, --swap, --swap-concurrency, --egress-allow, --size or --interactive" { |
| + t.Fatalf("all four nil: %v, want exactly SR-2-C17 (supersedes RFS-6-C47)", err) |
| } |
| if len(none.got()) != 0 { |
| t.Fatalf("a request went out: %v", none.got()) |
diff --git a/docs/superpowers/notes/census-proposal-stateless-replicas-2.md b/docs/superpowers/notes/census-proposal-stateless-replicas-2.md| new file mode 100644 |
| index 000000000..6ddeae6d7 |
| --- /dev/null |
| +++ b/docs/superpowers/notes/census-proposal-stateless-replicas-2.md |
| @@ -0,0 +1,13 @@ |
| +# Census approval: stateless-replicas-2 |
| + |
| +Status: proposed. Independent review and recording on #280 remain outstanding. |
| + |
| +Ruling `census-ruling-stateless-replicas-2`. 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/appconfig`, `internal/provision`, `internal/replicas`. |
| + |
| +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: `df8bf8056d80b9d78edc957fe7f2adbc75885e15f581e58167768346c4e05771` → `df8bf8056d80b9d78edc957fe7f2adbc75885e15f581e58167768346c4e05771`. |
| + |
| +Overlay: `internal/provision/testdata/plan14-root-reads-stateless-replicas-2.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`. |
diff --git a/internal/appconfig/copies.go b/internal/appconfig/copies.go| index d6885c0df..1b2b1508b 100644 |
| --- a/internal/appconfig/copies.go |
| +++ b/internal/appconfig/copies.go |
| @@ -17,7 +17,8 @@ func CopiesOf(m *Manifest) int { |
| } |
| // SetCopies changes only the default bundle, preserving its other fields. |
| -// Restoring the default omits the key; an unchanged value writes nothing. |
| +// Once enabled, an explicit count survives decreases so publication checks |
| +// can wait for outstanding assignments. 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 { |
| @@ -37,9 +38,6 @@ func SetCopies(ctx context.Context, s release.Store, acct, app string, n int) (i |
| 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 { |
diff --git a/internal/appconfig/copies_test.go b/internal/appconfig/copies_test.go| index 4f4d1a8b1..8f80896e0 100644 |
| --- a/internal/appconfig/copies_test.go |
| +++ b/internal/appconfig/copies_test.go |
| @@ -55,7 +55,7 @@ func TestCopiesDefaultsAndBounds(t *testing.T) { |
| t.Fatal(err) |
| } |
| got, _ = Get(ctx, s, "bab", "shop") |
| - if got.Copies != 0 { |
| - t.Fatal("default was not omitted") |
| + if got.Copies != 1 { |
| + t.Fatal("decrease lost the durable copies marker") |
| } |
| } |
diff --git a/internal/appconfig/swap.go b/internal/appconfig/swap.go| index 25f08166c..c52a8c9e0 100644 |
| --- a/internal/appconfig/swap.go |
| +++ b/internal/appconfig/swap.go |
| @@ -55,9 +55,9 @@ func GetSwapPolicy(ctx context.Context, s release.Store, acct, app string) (Swap |
| // config sync leaves an instance whose config file is absent as it is for |
| // such a bundle (renderExecConfig's keepAbsent), so that first write |
| // restarts nothing (Astra plan 6 R1 #1). |
| -func SetSwapPolicy(ctx context.Context, s release.Store, acct, app, swap string, concurrency int) (claimResult0 SwapPolicy, claimResult1 error) { |
| +func SetSwapPolicy(ctx context.Context, s release.Store, acct, app, swap string, concurrency int, check ...func(*Manifest) error) (claimResult0 SwapPolicy, claimResult1 error) { |
| claimResult1 = release.WithAppMutation(ctx, s, acct, app, "appconfig.SetSwapPolicy", func(claimContext context.Context) error { |
| - claimResult0, claimResult1 = claimRawSetSwapPolicy(claimContext, s, acct, app, swap, concurrency) |
| + claimResult0, claimResult1 = claimRawSetSwapPolicy(claimContext, s, acct, app, swap, concurrency, check...) |
| return claimResult1 |
| }) |
| return |
| @@ -65,7 +65,7 @@ func SetSwapPolicy(ctx context.Context, s release.Store, acct, app, swap string, |
| // claimRawSetSwapPolicy is the unwrapped implementation of SetSwapPolicy, |
| // called from within the WithAppMutation wrapper. |
| -func claimRawSetSwapPolicy(ctx context.Context, s release.Store, acct, app, swap string, concurrency int) (SwapPolicy, error) { |
| +func claimRawSetSwapPolicy(ctx context.Context, s release.Store, acct, app, swap string, concurrency int, check ...func(*Manifest) error) (SwapPolicy, error) { |
| if !release.ValidAccount(acct) { |
| return SwapPolicy{}, fmt.Errorf("config: invalid account %q", acct) |
| } |
| @@ -83,6 +83,11 @@ func claimRawSetSwapPolicy(ctx context.Context, s release.Store, acct, app, swap |
| if err != nil { |
| return SwapPolicy{}, err |
| } |
| + for _, validate := range check { |
| + if err := validate(&m); err != nil { |
| + return SwapPolicy{}, err |
| + } |
| + } |
| next := m |
| switch swap { |
| case SwapOverlap: |
diff --git a/internal/console/apicli.go b/internal/console/apicli.go| index fe081cc3e..67ecb1207 100644 |
| --- a/internal/console/apicli.go |
| +++ b/internal/console/apicli.go |
| @@ -90,6 +90,7 @@ func (s *Server) apiAccountAppSaying(w http.ResponseWriter, r *http.Request, has |
| http.NotFound(w, r) |
| return "", nil, "", false |
| } |
| + s.captureCopiesAdmission(r, acct, app) |
| s.writePlanWarnings(w, r, p, acct) // plans 4a, as apiPrincipalAccount |
| return auditActor(p, acct), acct, app, true |
| } |
| @@ -934,6 +935,13 @@ func (s *Server) handleAPIPromote(w http.ResponseWriter, r *http.Request) { |
| } |
| ctx, cancel := context.WithTimeout(r.Context(), 15*time.Second) |
| defer cancel() |
| + ctx, copiesUnlock, copiesLockRef := s.beginCopiesMutation(ctx, acct, app) |
| + if copiesLockRef != nil { |
| + jsonError(w, copiesLockRef.Status, copiesLockRef.Msg) |
| + return |
| + } |
| + defer copiesUnlock() |
| + |
| // The version's manifest and the app's pipeline are read at once |
| // (console-slow-writes); each answer is judged where it always was, so |
| // an unshipped version is still refused before the pipeline's error. |
| @@ -946,6 +954,9 @@ func (s *Server) handleAPIPromote(w http.ResponseWriter, r *http.Request) { |
| runConcurrently( |
| func() { man, err = release.GetManifest(ctx, s.cfg.Releases, acct.Sqid, app, version) }, |
| func() { pipe, perr = release.GetPipeline(ctx, s.cfg.Releases, s.cfg.ReleasePub, acct.Sqid, app) }, |
| + // P7: preload the one config read under the lock; the gate judges |
| + // its memoized result once the target manifest is known. |
| + func() { _, _ = s.copiesDefault(ctx, acct.Sqid, app) }, |
| ) |
| if err != nil { |
| jsonError(w, http.StatusNotFound, "Version "+version+" is not a shipped release of "+app+".") |
| @@ -982,6 +993,10 @@ func (s *Server) handleAPIPromote(w http.ResponseWriter, r *http.Request) { |
| if s.refuseServiceControlPlane(w, p, acct.ID, app, "promote it") { |
| return |
| } |
| + if ref := s.copiesPublicationRefusal(ctx, acct, app, man, "", false); ref != nil { |
| + jsonError(w, ref.Status, ref.Msg) |
| + return |
| + } |
| if ref := s.statelessRuntimeRefusal(ctx, channel, man, nil, ""); ref != nil { |
| jsonError(w, ref.Status, ref.Msg) |
| return |
| @@ -1271,6 +1286,13 @@ func (s *Server) handleAPIRollback(w http.ResponseWriter, r *http.Request) { |
| } |
| ctx, cancel := context.WithTimeout(r.Context(), 15*time.Second) |
| defer cancel() |
| + ctx, copiesUnlock, copiesLockRef := s.beginCopiesMutation(ctx, acct, app) |
| + if copiesLockRef != nil { |
| + jsonError(w, copiesLockRef.Status, copiesLockRef.Msg) |
| + return |
| + } |
| + defer copiesUnlock() |
| + |
| pipe, perr := release.GetPipeline(ctx, s.cfg.Releases, s.cfg.ReleasePub, acct.Sqid, app) |
| if perr != nil { |
| log.Printf("console: api rollback %s/%s: read pipeline: %v", acct.Sqid, app, perr) |
| @@ -2454,7 +2476,17 @@ func (s *Server) handleAPIShip(w http.ResponseWriter, r *http.Request) { |
| // short strings. |
| ctx, cancel := context.WithTimeout(r.Context(), 2*time.Minute) |
| defer cancel() |
| + ctx, copiesUnlock, copiesLockRef := s.beginCopiesMutation(ctx, acct, app) |
| + if copiesLockRef != nil { |
| + jsonError(w, copiesLockRef.Status, copiesLockRef.Msg) |
| + return |
| + } |
| + defer copiesUnlock() |
| + if ref := s.copiesPublicationRefusal(ctx, acct, app, &m, "", true); ref != nil { |
| + jsonError(w, ref.Status, ref.Msg) |
| + return |
| + } |
| // A version's objects are immutable once shipped, but BOTH callers that |
| // build a manifest like this one (this handler and the direct `carlos |
| // ship` CLI path) stamp BuiltAt with a fresh time.Now() on every |
diff --git a/internal/console/apiinstances.go b/internal/console/apiinstances.go| index 8395d6f02..afe0a4632 100644 |
| --- a/internal/console/apiinstances.go |
| +++ b/internal/console/apiinstances.go |
| @@ -2369,6 +2369,23 @@ func (s *Server) handleAPIInstanceCreate(w http.ResponseWriter, r *http.Request) |
| // room changes nothing. beginClaimCreate keeps this choice. |
| createContext := r.Context() |
| if s.cfg.HostClaim { |
| + var unlock func() |
| + var ref *doorRefusal |
| + createContext, unlock, ref = s.beginCopiesMutation(createContext, acct, app) |
| + if ref != nil { |
| + jsonError(w, ref.Status, ref.Msg) |
| + return |
| + } |
| + defer unlock() |
| + if err := s.copiesCreateCheck(createContext, &rec); err != nil { |
| + var selection *statelessSelectionError |
| + if errors.As(err, &selection) { |
| + jsonError(w, selection.ref.Status, selection.ref.Msg) |
| + return |
| + } |
| + jsonError(w, http.StatusServiceUnavailable, copiesUnread) |
| + return |
| + } |
| var chooseErr error |
| if createContext, chooseErr = s.chooseCreateFirst(createContext, host, buildClaim); chooseErr != nil { |
| writeClaimResponseError(w, chooseErr) |
| @@ -2432,9 +2449,17 @@ func (s *Server) handleAPIInstanceCreate(w http.ResponseWriter, r *http.Request) |
| default: |
| // The hostname history's mark for a data kind, then the |
| // create-only write (hostsused.go). |
| - recordWriteErr = s.createRecordMarked(ctx, rec) |
| + var created *provision.Record |
| + if created, recordWriteErr = s.createRecordMarked(ctx, rec); recordWriteErr == nil { |
| + rec = *created |
| + } |
| } |
| if err := recordWriteErr; err != nil { |
| + var selection *statelessSelectionError |
| + if errors.As(err, &selection) { |
| + jsonError(w, selection.ref.Status, selection.ref.Msg) |
| + return |
| + } |
| if writeOwnedBindingRefusal(w, err) { |
| return |
| } |
| @@ -3371,6 +3396,13 @@ func (s *Server) handleAPIInstanceEnable(w http.ResponseWriter, r *http.Request) |
| } |
| ctx, cancel := context.WithTimeout(r.Context(), instanceStoreTimeout) |
| defer cancel() |
| + ctx, copiesUnlock, copiesLockRef := s.beginCopiesMutation(ctx, acct, app) |
| + if copiesLockRef != nil { |
| + jsonError(w, copiesLockRef.Status, copiesLockRef.Msg) |
| + return |
| + } |
| + defer copiesUnlock() |
| + |
| // Read WITH the etag and write guarded by it below: the domain-conflict |
| // refusal is only honest if nothing can land between this read and the |
| // write. PutManifest's upsert re-reads inside, so an operator's |
| @@ -3426,6 +3458,10 @@ func (s *Server) handleAPIInstanceEnable(w http.ResponseWriter, r *http.Request) |
| if req.PrivateStorage != nil { |
| m.PrivateStorage = *req.PrivateStorage |
| } |
| + if ref := s.copiesChannelRefusal(ctx, acct, app, m.Channel); ref != nil { |
| + jsonError(w, ref.Status, ref.Msg) |
| + return |
| + } |
| if err := provision.PutManifestIfMatch(ctx, s.cfg.Releases, acct.Sqid, app, *m, etag); err != nil { |
| if errors.Is(err, release.ErrCASConflict) { |
| jsonError(w, http.StatusConflict, |
diff --git a/internal/console/apiinstanceseed.go b/internal/console/apiinstanceseed.go| index e3dae747c..01f355098 100644 |
| --- a/internal/console/apiinstanceseed.go |
| +++ b/internal/console/apiinstanceseed.go |
| @@ -86,7 +86,8 @@ func (s *Server) createSeedRecord(ctx context.Context, c seedCreate, rec provisi |
| _, err := s.createRecordWithLifetime(ctx, rec, c.lifetime) |
| return err |
| } |
| - return s.createRecordMarked(ctx, rec) |
| + _, err := s.createRecordMarked(ctx, rec) |
| + return err |
| } |
| // seedCommonRefusal is both seed doors' shape rule: an ordinary instance. |
diff --git a/internal/console/apiship_rootfs.go b/internal/console/apiship_rootfs.go| index fd8868bfa..608916e1a 100644 |
| --- a/internal/console/apiship_rootfs.go |
| +++ b/internal/console/apiship_rootfs.go |
| @@ -259,6 +259,16 @@ func (s *Server) shipRootfsParts(w http.ResponseWriter, r *http.Request, mr *mul |
| } |
| ctx, cancel := context.WithTimeout(r.Context(), apiShipRootfsStoreTimeout) |
| defer cancel() |
| + ctx, copiesUnlock, copiesLockRef := s.beginCopiesMutation(ctx, acct, app) |
| + if copiesLockRef != nil { |
| + jsonError(w, copiesLockRef.Status, copiesLockRef.Msg) |
| + return |
| + } |
| + defer copiesUnlock() |
| + if ref := s.copiesPublicationRefusal(ctx, acct, app, &m, "", true); ref != nil { |
| + jsonError(w, ref.Status, ref.Msg) |
| + return |
| + } |
| // A version already on record: the same release again is a 200 that |
| // writes nothing; anything that differs is a 409, since versions are |
| @@ -367,7 +377,9 @@ func (s *Server) fixFirstRootfsKind(ctx context.Context, acct *Account, m *relea |
| // fixFirstRootfsKindLocked is fixFirstRootfsKind's part under the app |
| // lock: the recheck, the count and the marker, nothing else. |
| func (s *Server) fixFirstRootfsKindLocked(ctx context.Context, acct *Account, m *release.Manifest) (*doorRefusal, error) { |
| - defer s.lockApp(acct.Sqid, m.App)() |
| + if held, ok := ctx.Value(copiesHeldKey{}).(copiesHeld); !ok || held != (copiesHeld{acct.ID, m.App}) { |
| + defer s.lockApp(acct.Sqid, m.App)() |
| + } |
| // Another first ship may have fixed the kind while this one waited. |
| switch info, err := release.EstablishedKind(ctx, s.cfg.Releases, acct.Sqid, m.App); { |
| case err != nil: |
diff --git a/internal/console/apisidecars.go b/internal/console/apisidecars.go| index 427b36c0c..47b92d606 100644 |
| --- a/internal/console/apisidecars.go |
| +++ b/internal/console/apisidecars.go |
| @@ -417,7 +417,17 @@ func (s *Server) handleAPISidecarCreate(w http.ResponseWriter, r *http.Request) |
| defer cancel() |
| var recordWriteErr error |
| if s.cfg.HostClaim { |
| - request, err := s.beginClaimCreate(r.Context(), acct, app, rec.Host, principal, func(now time.Time, acquisition string) (hostops.Record, error) { |
| + claimCtx, unlock, ref := s.beginCopiesMutation(r.Context(), acct, app) |
| + if ref != nil { |
| + jsonError(w, ref.Status, ref.Msg) |
| + return |
| + } |
| + defer unlock() |
| + if ref := s.copiesSidecarRefusal(claimCtx, acct.Sqid, app); ref != nil { |
| + jsonError(w, ref.Status, ref.Msg) |
| + return |
| + } |
| + request, err := s.beginClaimCreate(claimCtx, acct, app, rec.Host, principal, func(now time.Time, acquisition string) (hostops.Record, error) { |
| rec.CreatedAt = time.Time{} |
| rec.Acquisition = acquisition |
| region := s.cfg.claimPlacementRegion(rec.Region) |
diff --git a/internal/console/apiswap.go b/internal/console/apiswap.go| index 6f1b3d7a7..2e73a1db0 100644 |
| --- a/internal/console/apiswap.go |
| +++ b/internal/console/apiswap.go |
| @@ -10,6 +10,7 @@ package console |
| import ( |
| "context" |
| + "errors" |
| "fmt" |
| "net/http" |
| "strings" |
| @@ -72,8 +73,13 @@ func (s *Server) handleAPISwapPut(w http.ResponseWriter, r *http.Request) { |
| } |
| ctx, cancel := context.WithTimeout(r.Context(), configStoreTimeout) |
| defer cancel() |
| - got, err := appconfig.SetSwapPolicy(ctx, s.cfg.Releases, acct.Sqid, app, swap, concurrency) |
| + got, err := s.setCopiesSwapPolicy(ctx, acct, app, swap, concurrency) |
| if err != nil { |
| + var selection *statelessSelectionError |
| + if errors.As(err, &selection) { |
| + jsonError(w, selection.ref.Status, selection.ref.Msg) |
| + return |
| + } |
| s.configStoreError(w, fmt.Sprintf("api swap %s/%s", acct.Sqid, app), err) |
| return |
| } |
diff --git a/internal/console/apiupdates.go b/internal/console/apiupdates.go| index d483067d0..76f621876 100644 |
| --- a/internal/console/apiupdates.go |
| +++ b/internal/console/apiupdates.go |
| @@ -322,6 +322,13 @@ func (s *Server) handleAPIUpdatesPolicy(w http.ResponseWriter, r *http.Request) |
| } |
| ctx, cancel := context.WithTimeout(r.Context(), instanceStoreTimeout) |
| defer cancel() |
| + ctx, copiesUnlock, copiesLockRef := s.beginCopiesMutation(ctx, acct, app) |
| + if copiesLockRef != nil { |
| + jsonError(w, copiesLockRef.Status, copiesLockRef.Msg) |
| + return |
| + } |
| + defer copiesUnlock() |
| + |
| m, etag, err := provision.GetManifestETag(ctx, s.cfg.Releases, acct.Sqid, app) |
| switch { |
| case errors.Is(err, os.ErrNotExist): |
| @@ -401,6 +408,10 @@ func (s *Server) handleAPIUpdatesPolicy(w http.ResponseWriter, r *http.Request) |
| p := next |
| out.Updates = &p |
| } |
| + if ref := s.copiesChannelRefusal(ctx, acct, app, nextChannel); ref != nil { |
| + jsonError(w, ref.Status, ref.Msg) |
| + return |
| + } |
| if err := provision.PutManifestIfMatch(ctx, s.cfg.Releases, acct.Sqid, app, out, etag); err != nil { |
| if errors.Is(err, release.ErrCASConflict) { |
| jsonError(w, http.StatusConflict, updatewords.Text("settings.console.changed")) |
diff --git a/internal/console/appcopies.go b/internal/console/appcopies.go| index f9e95f1d4..c192753cd 100644 |
| --- a/internal/console/appcopies.go |
| +++ b/internal/console/appcopies.go |
| @@ -17,6 +17,7 @@ import ( |
| ) |
| const ( |
| + copiesStopping = "copies are still stopping on other boxes. wait for that to finish before selecting a release with a local database" |
| 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" |
| @@ -82,7 +83,12 @@ func (s *Server) handleAPICopies(w http.ResponseWriter, r *http.Request) { |
| 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)() |
| + ctx, unlock, lockRef := s.beginCopiesMutation(ctx, acct, app) |
| + if lockRef != nil { |
| + jsonError(w, lockRef.Status, lockRef.Msg) |
| + return |
| + } |
| + defer unlock() |
| var ref *doorRefusal |
| var got int |
| err := s.claimAppMutation(ctx, acct, app, "copies", func(ctx context.Context) error { |
| @@ -107,22 +113,48 @@ func (s *Server) handleAPICopies(w http.ResponseWriter, r *http.Request) { |
| 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. |
| +// copiesRefusal runs under the app mutation boundary. A nil target admits |
| +// a count against the complete inventory. A canonical target checks a |
| +// publication for an explicitly configured app, including removal at count 1. |
| 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 target != nil { |
| + if n > 1 { |
| + if !safeCopiesTarget(target) { |
| + return refuse(copiesRelease) |
| + } |
| + if release.NormalizeDemand(target.Swap) == release.DemandHold { |
| + return refuse(copiesOverlap) |
| + } |
| + if target.Kind != "" && target.Kind != "binary" && target.Kind != release.KindRootfs { |
| + return refuse(copiesManaged) |
| + } |
| + } else if !safeCopiesTarget(target) { |
| + recs, err := placeRecords(ctx, s.cfg.Releases, provision.JudgeFrom(ctx), acct.Sqid, app) |
| + if err != nil { |
| + return unread() |
| + } |
| + for _, rec := range recs { |
| + if a := rec.ReplicaAssignment; a != nil && (len(a.Boxes) > 1 || len(a.Retiring) != 0) { |
| + return refuse(copiesStopping) |
| + } |
| + } |
| + } |
| + return nil |
| + } |
| if n == 1 { |
| return nil |
| } |
| if s.cfg.Releases == nil { |
| return unread() |
| } |
| - ctx = withWriteMemo(ctx) |
| + if memoOf(ctx, "copies-config:"+acct.Sqid+"/"+app) == nil { |
| + ctx = withWriteMemo(ctx) |
| + } |
| placed, err := s.store.AppPlacement(acct.ID, app) |
| if err != nil { |
| return unread() |
| @@ -146,6 +178,12 @@ func (s *Server) copiesRefusal(ctx context.Context, acct *Account, app string, n |
| if err != nil { |
| return unread() |
| } |
| + // A durable create allocation may publish its body during recovery. |
| + // Do not admit a larger count while that record is still pending. |
| + allocations, err := s.store.PendingLifetimesForApp(acct.Sqid, app) |
| + if err != nil || len(allocations) != 0 { |
| + return unread() |
| + } |
| sidecars, err := provision.ListSidecarRecordsStrict(ctx, s.cfg.Releases, acct.Sqid, app) |
| if err != nil { |
| return unread() |
| @@ -153,11 +191,11 @@ func (s *Server) copiesRefusal(ctx context.Context, acct *Account, app string, n |
| if len(sidecars) > 0 { |
| return refuse(copiesManaged) |
| } |
| - m, err := appconfig.Get(ctx, s.cfg.Releases, acct.Sqid, app) |
| + cfg, err := s.copiesDefault(ctx, acct.Sqid, app) |
| if err != nil { |
| return unread() |
| } |
| - if appconfig.PolicyOf(m).Swap != appconfig.SwapOverlap { |
| + if appconfig.PolicyOf(&cfg.manifest).Swap != appconfig.SwapOverlap { |
| return refuse(copiesOverlap) |
| } |
| check := func(m *release.Manifest) *doorRefusal { |
| @@ -175,12 +213,7 @@ func (s *Server) copiesRefusal(ctx context.Context, acct *Account, app string, n |
| } |
| return nil |
| } |
| - if target != nil { |
| - if ref := check(target); ref != nil { |
| - return ref |
| - } |
| - } |
| - rootfs := target != nil && target.Kind == release.KindRootfs |
| + rootfs, _ := ctx.Value(copiesRootfsCreateKey{}).(bool) |
| for _, rec := range recs { |
| if rec.Retired { |
| continue |
diff --git a/internal/console/appcopies_test.go b/internal/console/appcopies_test.go| index 3c203de7c..d28e2605a 100644 |
| --- a/internal/console/appcopies_test.go |
| +++ b/internal/console/appcopies_test.go |
| @@ -162,7 +162,7 @@ func TestCopiesReleaseFloorComplete(t *testing.T) { |
| at = at.Add(-time.Hour) |
| } |
| copiesBeat(t, fx, "pi-2", v, at) |
| - if code, out := copiesPut(t, fx, token, `{"copies":2}`); code != 409 { |
| + if code, out := copiesPut(t, fx, token, `{"copies":2}`); code != 409 || !strings.Contains(out, "copies above 1") { |
| t.Fatalf("floor: %d %s", code, out) |
| } |
| }) |
| @@ -171,7 +171,7 @@ func TestCopiesReleaseFloorComplete(t *testing.T) { |
| 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 { |
| + if code, out := copiesPut(t, fx, token, `{"copies":2}`); code != 409 || !strings.Contains(out, "copies above 1") { |
| t.Fatalf("floor: %d %s", code, out) |
| } |
| }) |
diff --git a/internal/console/appswap.go b/internal/console/appswap.go| index c215111b5..fbd7a90e6 100644 |
| --- a/internal/console/appswap.go |
| +++ b/internal/console/appswap.go |
| @@ -3,6 +3,7 @@ package console |
| import ( |
| "context" |
| "crypto/subtle" |
| + "errors" |
| "fmt" |
| "log" |
| "net/http" |
| @@ -35,6 +36,7 @@ func (s *Server) handleAppSwap(w http.ResponseWriter, r *http.Request) { |
| http.NotFound(w, r) |
| return |
| } |
| + s.captureCopiesAdmission(r, acct, app) |
| back := func(kind, msg string) { |
| s.setFlash(w, kind, msg) |
| http.Redirect(w, r, appSettingsURL(acct.Sqid, app, "general"), http.StatusSeeOther) |
| @@ -55,8 +57,13 @@ func (s *Server) handleAppSwap(w http.ResponseWriter, r *http.Request) { |
| } |
| ctx, cancel := context.WithTimeout(r.Context(), configStoreTimeout) |
| defer cancel() |
| - got, err := appconfig.SetSwapPolicy(ctx, s.cfg.Releases, acct.Sqid, app, swap, n) |
| + got, err := s.setCopiesSwapPolicy(ctx, acct, app, swap, n) |
| if err != nil { |
| + var selection *statelessSelectionError |
| + if errors.As(err, &selection) { |
| + back("err", selection.ref.Msg) |
| + return |
| + } |
| log.Printf("console: swap policy %s/%s: %v", acct.Sqid, app, err) |
| back("err", swapCopy.StoreFailed) |
| return |
diff --git a/internal/console/channelmove.go b/internal/console/channelmove.go| index f3c73ef70..ea6185dce 100644 |
| --- a/internal/console/channelmove.go |
| +++ b/internal/console/channelmove.go |
| @@ -123,6 +123,13 @@ func (s *Server) handleAPIInstanceChannel(w http.ResponseWriter, r *http.Request |
| } |
| ctx, cancel := context.WithTimeout(r.Context(), instanceStoreTimeout) |
| defer cancel() |
| + ctx, copiesUnlock, copiesLockRef := s.beginCopiesMutation(ctx, acct, app) |
| + if copiesLockRef != nil { |
| + jsonError(w, copiesLockRef.Status, copiesLockRef.Msg) |
| + return |
| + } |
| + defer copiesUnlock() |
| + |
| rec, etag, err := s.readRecord(ctx, acct.Sqid, app, host) |
| switch { |
| case errors.Is(err, os.ErrNotExist): |
| @@ -175,7 +182,11 @@ func (s *Server) handleAPIInstanceChannel(w http.ResponseWriter, r *http.Request |
| return |
| } |
| rec.Channel = to |
| - if err := s.withRecordLock(rec.Account, rec.App, func() error { return provision.UpdateRecord(ctx, s.cfg.Releases, *rec, etag) }); err != nil { |
| + if ref := s.copiesRecordRefusal(ctx, acct, *rec, false); ref != nil { |
| + jsonError(w, ref.Status, ref.Msg) |
| + return |
| + } |
| + if err := provision.UpdateRecord(ctx, s.cfg.Releases, *rec, etag); err != nil { |
| if errors.Is(err, release.ErrCASConflict) { |
| jsonError(w, http.StatusConflict, "this instance changed while the request was in flight — try again") |
| return |
| @@ -204,6 +215,12 @@ func isCanaryChannel(channel string) bool { |
| // the proposal is a decision made about bytes that no longer exist, which is |
| // exactly what staleProposal says. |
| func (s *Server) executePendingRouteChannel(ctx context.Context, acct *Account, app, actor string, pc *PendingChange) (string, error) { |
| + |
| + ctx, copiesUnlock, copiesLockRef := s.beginCopiesMutation(ctx, acct, app) |
| + if copiesLockRef != nil { |
| + return "", &statelessSelectionError{copiesLockRef} |
| + } |
| + defer copiesUnlock() |
| var p channelMovePayload |
| if err := json.Unmarshal(pc.Payload, &p); err != nil { |
| return "", errors.New("this proposal's payload cannot be read — reject it and propose again") |
| @@ -217,7 +234,10 @@ func (s *Server) executePendingRouteChannel(ctx context.Context, acct *Account, |
| return "", staleProposal("the instance is on " + rec.Channel + " now") |
| } |
| rec.Channel = p.To |
| - if err := s.withRecordLock(rec.Account, rec.App, func() error { return provision.UpdateRecord(ctx, s.cfg.Releases, *rec, etag) }); err != nil { |
| + if ref := s.copiesRecordRefusal(ctx, acct, *rec, false); ref != nil { |
| + return "", &statelessSelectionError{ref} |
| + } |
| + if err := provision.UpdateRecord(ctx, s.cfg.Releases, *rec, etag); err != nil { |
| log.Printf("console: execute route-channel %s/%s/%s: %v", acct.Sqid, app, p.Host, err) |
| return "", errors.New("could not change the channel — try again") |
| } |
diff --git a/internal/console/copiespublication.go b/internal/console/copiespublication.go| new file mode 100644 |
| index 000000000..7dacc27fc |
| --- /dev/null |
| +++ b/internal/console/copiespublication.go |
| @@ -0,0 +1,281 @@ |
| +package console |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "errors" |
| + "net/http" |
| + "os" |
| + |
| + "github.com/carlosframework/platform/internal/appconfig" |
| + "github.com/carlosframework/platform/internal/provision" |
| + "github.com/carlosframework/platform/internal/release" |
| +) |
| + |
| +// Admission is bound to the app found by the authenticated request, before |
| +// uploads or lock waits. An app recreated under the same name is different. |
| +type copiesAdmissionKey struct{} |
| +type copiesAdmission struct { |
| + account int64 |
| + app string |
| + incarnation AppIncarnation |
| + valid bool |
| +} |
| + |
| +type copiesHeldKey struct{} |
| + |
| +// The prospective release participates in destination readiness before its |
| +// first record exists in the app inventory. |
| +type copiesRootfsCreateKey struct{} |
| +type copiesHeld struct { |
| + account int64 |
| + app string |
| +} |
| + |
| +func (s *Server) captureCopiesAdmission(r *http.Request, acct *Account, app string) { |
| + if readOnlyMethod(r.Method) { |
| + return |
| + } |
| + inc, ok, err := s.store.AppIncarnationContext(r.Context(), acct.ID, app) |
| + *r = *r.WithContext(context.WithValue(r.Context(), copiesAdmissionKey{}, copiesAdmission{acct.ID, app, inc, ok && err == nil})) |
| +} |
| + |
| +func copiesUnavailable() *doorRefusal { |
| + return &doorRefusal{http.StatusServiceUnavailable, copiesUnread} |
| +} |
| + |
| +func (s *Server) copiesStillApp(ctx context.Context, acct *Account, app string) *doorRefusal { |
| + admitted, present := ctx.Value(copiesAdmissionKey{}).(copiesAdmission) |
| + if !present { |
| + return nil |
| + } // Internal callers capture at their mutation boundary. |
| + inc, ok, err := s.store.AppIncarnationContext(ctx, acct.ID, app) |
| + if err != nil { |
| + return copiesUnavailable() |
| + } |
| + if !admitted.valid || admitted.account != acct.ID || admitted.app != app || !ok || inc != admitted.incarnation { |
| + return &doorRefusal{http.StatusConflict, copiesUnread} |
| + } |
| + return nil |
| +} |
| + |
| +// beginCopiesMutation takes the existing app lock. A nested publication may |
| +// join only through this context, whose lifetime ends before unlock. |
| +func (s *Server) beginCopiesMutation(ctx context.Context, acct *Account, app string) (context.Context, func(), *doorRefusal) { |
| + if held, ok := ctx.Value(copiesHeldKey{}).(copiesHeld); ok && held == (copiesHeld{acct.ID, app}) { |
| + return ctx, func() {}, s.copiesStillApp(ctx, acct, app) |
| + } |
| + if _, ok := ctx.Value(copiesAdmissionKey{}).(copiesAdmission); !ok { |
| + inc, live, err := s.store.AppIncarnationContext(ctx, acct.ID, app) |
| + ctx = context.WithValue(ctx, copiesAdmissionKey{}, copiesAdmission{acct.ID, app, inc, live && err == nil}) |
| + } |
| + unlockApp := s.lockApp(acct.Sqid, app) |
| + unlockName := s.store.lockAppNames(appNameKey{acct.ID, app}) |
| + unlock := func() { unlockName(); unlockApp() } |
| + if ref := s.copiesStillApp(ctx, acct, app); ref != nil { |
| + unlock() |
| + return ctx, func() {}, ref |
| + } |
| + if memoOf(ctx, "copies-config:"+acct.Sqid+"/"+app) == nil { |
| + ctx = withWriteMemo(ctx) |
| + } |
| + return context.WithValue(ctx, copiesHeldKey{}, copiesHeld{acct.ID, app}), unlock, nil |
| +} |
| + |
| +type copiesConfig struct { |
| + manifest appconfig.Manifest |
| + explicit bool |
| +} |
| + |
| +// P7: one default-bundle GET, under the app lock, shared by all checks in |
| +// this mutation. Explicit copies:1 preserves the retirement obligation. |
| +func (s *Server) copiesDefault(ctx context.Context, acct, app string) (copiesConfig, error) { |
| + return memoize(ctx, "copies-config:"+acct+"/"+app, func() (copiesConfig, error) { |
| + var out copiesConfig |
| + if s.cfg.Releases == nil { |
| + return out, os.ErrNotExist |
| + } |
| + raw, _, err := s.cfg.Releases.Get(ctx, appconfig.Key(acct, app)) |
| + if errors.Is(err, os.ErrNotExist) { |
| + return out, nil |
| + } |
| + if err != nil { |
| + return out, err |
| + } |
| + if err = json.Unmarshal(raw, &out.manifest); err != nil { |
| + return out, err |
| + } |
| + var fields map[string]json.RawMessage |
| + if err = json.Unmarshal(raw, &fields); err != nil { |
| + return out, err |
| + } |
| + _, out.explicit = fields["copies"] |
| + if out.manifest.Schema > appconfig.MaxSchema { |
| + return out, errors.New(copiesUnread) |
| + } |
| + return out, nil |
| + }) |
| +} |
| + |
| +func safeCopiesTarget(m *release.Manifest) bool { return m != nil && m.Stateless && !m.Hibernate } |
| + |
| +// target is a canonical manifest already read by the door; otherwise load |
| +// the named version only for opted-in apps. Ship retains stateful artifacts. |
| +func (s *Server) copiesPublicationRefusal(ctx context.Context, acct *Account, app string, target *release.Manifest, ver string, ship bool) *doorRefusal { |
| + cfg, err := s.copiesDefault(ctx, acct.Sqid, app) |
| + if ship && target != nil && !target.Hibernate { |
| + return nil |
| + } |
| + if err == nil && !cfg.explicit { |
| + return nil |
| + } |
| + if target == nil && ver != "" { |
| + target, _ = memoize(ctx, "stateless-manifest:"+release.ManifestKey(acct.Sqid, app, ver), func() (*release.Manifest, error) { |
| + return release.GetManifest(ctx, s.cfg.Releases, acct.Sqid, app, ver) |
| + }) |
| + } |
| + if err != nil { |
| + if safeCopiesTarget(target) { |
| + return nil |
| + } |
| + return copiesUnavailable() |
| + } |
| + if target == nil { |
| + return copiesUnavailable() |
| + } |
| + return s.copiesRefusal(ctx, acct, app, appconfig.CopiesOf(&cfg.manifest), target) |
| +} |
| + |
| +// The caller already holds the record writer's app lock. The proposed |
| +// record is checked before a create allocation or any record write. |
| +func (s *Server) copiesRecordRefusal(ctx context.Context, acct *Account, rec provision.Record, create bool) *doorRefusal { |
| + if ref := s.copiesStillApp(ctx, acct, rec.App); ref != nil { |
| + return ref |
| + } |
| + cfg, err := s.copiesDefault(ctx, rec.Account, rec.App) |
| + if err == nil && !cfg.explicit { |
| + return nil |
| + } |
| + configErr := err |
| + n := appconfig.CopiesOf(&cfg.manifest) |
| + if n > 1 { |
| + if !rec.DerivesPaths() || rec.HA || rec.Role != "" || rec.Pool != "" || len(rec.Replicas) != 0 { |
| + return &doorRefusal{http.StatusConflict, copiesManaged} |
| + } |
| + if rec.Move != nil || rec.Seed.BlocksRun() { |
| + return &doorRefusal{http.StatusConflict, copiesMoving} |
| + } |
| + } |
| + ver := rec.Pin |
| + if ver == "" { |
| + head, err := release.Channel(ctx, s.cfg.Releases, s.cfg.ReleasePub, rec.Account, rec.App, rec.Channel) |
| + if err != nil || head == nil { |
| + return copiesUnavailable() |
| + } |
| + ver = head.Version |
| + } |
| + target, err := release.AuthorizedManifest(ctx, s.cfg.Releases, s.cfg.ReleasePub, rec.Account, rec.App, ver) |
| + if err != nil { |
| + return copiesUnavailable() |
| + } |
| + if rec.Runtime != provision.RuntimeRootfsV1 && (rec.Hibernate == nil || *rec.Hibernate) { |
| + cp := *target |
| + cp.Hibernate = true |
| + target = &cp |
| + } |
| + if configErr != nil { |
| + if safeCopiesTarget(target) { |
| + return nil |
| + } |
| + return copiesUnavailable() |
| + } |
| + if ref := s.copiesRefusal(ctx, acct, rec.App, n, target); ref != nil { |
| + return ref |
| + } |
| + if create && n > 1 { |
| + ctx = context.WithValue(ctx, copiesRootfsCreateKey{}, target.Kind == release.KindRootfs) |
| + return s.copiesRefusal(ctx, acct, rec.App, n, nil) |
| + } |
| + return nil |
| +} |
| + |
| +func (s *Server) copiesCreateCheck(ctx context.Context, rec *provision.Record) error { |
| + // Only authenticated create contexts participate; internal recovery keeps |
| + // the admission attached to its durable allocation. |
| + if _, ok := ctx.Value(copiesAdmissionKey{}).(copiesAdmission); !ok { |
| + return nil |
| + } |
| + acct, err := s.store.AccountBySqid(rec.Account) |
| + if err != nil || acct == nil { |
| + return &statelessSelectionError{copiesUnavailable()} |
| + } |
| + cfg, err := s.copiesDefault(ctx, rec.Account, rec.App) |
| + if err == nil && appconfig.CopiesOf(&cfg.manifest) > 1 && rec.Runtime == "" && rec.Hibernate == nil && rec.DerivesPaths() { |
| + rec.Hibernate = new(bool) |
| + } |
| + if ref := s.copiesRecordRefusal(ctx, acct, *rec, true); ref != nil { |
| + return &statelessSelectionError{ref} |
| + } |
| + return nil |
| +} |
| + |
| +// Swap's existing CAS read supplies the count; no second config GET is needed. |
| +func (s *Server) setCopiesSwapPolicy(ctx context.Context, acct *Account, app, swap string, concurrency int) (appconfig.SwapPolicy, error) { |
| + ctx, unlock, ref := s.beginCopiesMutation(ctx, acct, app) |
| + if ref != nil { |
| + return appconfig.SwapPolicy{}, &statelessSelectionError{ref} |
| + } |
| + defer unlock() |
| + return appconfig.SetSwapPolicy(ctx, s.cfg.Releases, acct.Sqid, app, swap, concurrency, func(m *appconfig.Manifest) error { |
| + if swap == appconfig.SwapHold { |
| + if ref := s.copiesRefusal(ctx, acct, app, appconfig.CopiesOf(m), &release.Manifest{Stateless: true, Swap: release.DemandHold}); ref != nil { |
| + return &statelessSelectionError{ref} |
| + } |
| + } |
| + return nil |
| + }) |
| +} |
| + |
| +// A create already holds its app lock. Keep the name pinned through the |
| +// record write too, in the same app-then-name order as publication. |
| +func (s *Server) copiesCreateNameLock(ctx context.Context) func() { |
| + a, ok := ctx.Value(copiesAdmissionKey{}).(copiesAdmission) |
| + if !ok { |
| + return func() {} |
| + } |
| + return s.store.lockAppNames(appNameKey{a.account, a.app}) |
| +} |
| + |
| +func (s *Server) copiesChannelRefusal(ctx context.Context, acct *Account, app, channel string) *doorRefusal { |
| + cfg, err := s.copiesDefault(ctx, acct.Sqid, app) |
| + if err == nil && !cfg.explicit { |
| + return nil |
| + } |
| + head, err := release.Channel(ctx, s.cfg.Releases, s.cfg.ReleasePub, acct.Sqid, app, channel) |
| + if err != nil || head == nil { |
| + return copiesUnavailable() |
| + } |
| + return s.copiesPublicationRefusal(ctx, acct, app, nil, head.Version, false) |
| +} |
| + |
| +// A sidecar cannot be introduced after the app passed the no-sidecars gate. |
| +func (s *Server) copiesSidecarRefusal(ctx context.Context, account, app string) *doorRefusal { |
| + if _, ok := ctx.Value(copiesAdmissionKey{}).(copiesAdmission); !ok { |
| + return nil |
| + } |
| + acct, err := s.store.AccountBySqid(account) |
| + if err != nil || acct == nil { |
| + return copiesUnavailable() |
| + } |
| + if ref := s.copiesStillApp(ctx, acct, app); ref != nil { |
| + return ref |
| + } |
| + cfg, err := s.copiesDefault(ctx, account, app) |
| + if err != nil { |
| + return copiesUnavailable() |
| + } |
| + if !cfg.explicit { |
| + return nil |
| + } |
| + return s.copiesRefusal(ctx, acct, app, appconfig.CopiesOf(&cfg.manifest), &release.Manifest{Stateless: true, Kind: "sidecar"}) |
| +} |
diff --git a/internal/console/copiespublication_test.go b/internal/console/copiespublication_test.go| new file mode 100644 |
| index 000000000..309ae1723 |
| --- /dev/null |
| +++ b/internal/console/copiespublication_test.go |
| @@ -0,0 +1,612 @@ |
| +package console |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "errors" |
| + "net/http" |
| + "net/http/httptest" |
| + "net/url" |
| + "os" |
| + "path/filepath" |
| + "strings" |
| + "sync" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/appconfig" |
| + "github.com/carlosframework/platform/internal/provision" |
| + "github.com/carlosframework/platform/internal/release" |
| + "github.com/carlosframework/platform/internal/replicas" |
| +) |
| + |
| +func copiesUnsafeRelease(t *testing.T, fx *consoleFixture) { |
| + t.Helper() |
| + shipVersion(t, fx, "shop", "unsafe") |
| + for _, v := range []string{"unsafe", "v1"} { |
| + if err := release.Promote(context.Background(), fx.rel, fx.priv, fx.sqid, "shop", "edge", v); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + if err := release.Promote(context.Background(), fx.rel, fx.priv, fx.sqid, "shop", "canary/unsafe", "unsafe"); err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
| + |
| +type copiesDoor struct{ name, method, path, body string } |
| + |
| +var copiesUnsafeDoors = []copiesDoor{ |
| + {"promote", "POST", "/promote", `{"channel":"canary/new","version":"unsafe"}`}, |
| + {"rollback", "POST", "/rollback", `{"channel":"edge"}`}, |
| + {"channel", "POST", "/instances/a.example.com/channel", `{"channel":"canary/unsafe"}`}, |
| + {"pin", "PUT", "/instances/a.example.com/updates", `{"pin":"unsafe"}`}, |
| + {"hold", "PUT", "/swap", `{"swap":"hold"}`}, |
| + {"create", "POST", "/instances", `{"host":"new.example.com","channel":"canary/unsafe"}`}, |
| +} |
| + |
| +func copiesCall(t *testing.T, fx *consoleFixture, token string, door copiesDoor) (int, string) { |
| + t.Helper() |
| + code, _, out := rawReq(t, door.method, fx.ts.URL+"/api/cli/apps/"+fx.sqid+"/shop"+door.path, token, door.body) |
| + return code, out |
| +} |
| + |
| +func TestCopiesPublicationDoors(t *testing.T) { |
| + for _, door := range copiesUnsafeDoors { |
| + t.Run(door.name, func(t *testing.T) { |
| + fx, token := copiesWorld(t) |
| + copiesUnsafeRelease(t, fx) |
| + if code, out := copiesPut(t, fx, token, `{"copies":2}`); code != 200 { |
| + t.Fatalf("count: %d %s", code, out) |
| + } |
| + code, out := copiesCall(t, fx, token, door) |
| + want := copiesRelease |
| + if door.name == "hold" { |
| + want = copiesOverlap |
| + } |
| + if code != 409 || !strings.Contains(out, want) { |
| + t.Fatalf("publication: %d %s, want %s", code, out, want) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func copiesAssignment(t *testing.T, fx *consoleFixture, a *replicas.Assignment, retired bool) { |
| + t.Helper() |
| + ctx := context.Background() |
| + key := provision.RecordKey(fx.sqid, "shop", "a.example.com") |
| + 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) |
| + } |
| + rec.ReplicaAssignment = a |
| + rec.Retired = retired |
| + raw, _ = json.Marshal(rec) |
| + if _, err := fx.rel.Put(ctx, key, raw, etag); err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
| + |
| +func TestCopiesStoredAssignmentAndDecrease(t *testing.T) { |
| + for _, tc := range []struct { |
| + name string |
| + a *replicas.Assignment |
| + retired bool |
| + refuse bool |
| + }{ |
| + {"two boxes", &replicas.Assignment{Boxes: []string{"pi-1", "pi-2"}}, false, true}, |
| + {"retiring", &replicas.Assignment{Boxes: []string{"pi-1"}, Retiring: []string{"pi-2"}}, false, true}, |
| + {"retired record", &replicas.Assignment{Boxes: []string{"pi-1"}, Retiring: []string{"pi-2"}}, true, true}, |
| + {"one box", &replicas.Assignment{Boxes: []string{"pi-1"}}, false, false}, |
| + {"none", nil, false, false}, |
| + } { |
| + t.Run(tc.name, func(t *testing.T) { |
| + fx, token := copiesWorld(t) |
| + copiesUnsafeRelease(t, fx) |
| + if code, out := copiesPut(t, fx, token, `{"copies":2}`); code != 200 { |
| + t.Fatalf("count: %d %s", code, out) |
| + } |
| + copiesAssignment(t, fx, tc.a, tc.retired) |
| + before, _, _ := fx.rel.Get(context.Background(), provision.RecordKey(fx.sqid, "shop", "a.example.com")) |
| + if code, out := copiesPut(t, fx, token, `{"copies":1}`); code != 200 || !strings.Contains(out, `"copies":1`) { |
| + t.Fatalf("decrease: %d %s", code, out) |
| + } |
| + after, _, _ := fx.rel.Get(context.Background(), provision.RecordKey(fx.sqid, "shop", "a.example.com")) |
| + if string(before) != string(after) { |
| + t.Fatal("decrease changed assignments") |
| + } |
| + m, _ := appconfig.Get(context.Background(), fx.rel, fx.sqid, "shop") |
| + if m == nil || m.Copies != 1 { |
| + t.Fatal("decrease lost explicit count") |
| + } |
| + code, out := copiesCall(t, fx, token, copiesUnsafeDoors[0]) |
| + if tc.refuse { |
| + if code != 409 || !strings.Contains(out, copiesStopping) { |
| + t.Fatalf("publication: %d %s", code, out) |
| + } |
| + } else if code != 200 { |
| + t.Fatalf("completed: %d %s", code, out) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +type copiesEvidenceStore struct { |
| + release.Store |
| + mu sync.Mutex |
| + gets map[string]int |
| + fail string |
| + lists int |
| +} |
| + |
| +func (s *copiesEvidenceStore) Get(ctx context.Context, key string) ([]byte, string, error) { |
| + s.mu.Lock() |
| + s.gets[key]++ |
| + s.mu.Unlock() |
| + if key == s.fail { |
| + return nil, "", errors.New("test evidence unavailable") |
| + } |
| + return s.Store.Get(ctx, key) |
| +} |
| +func (s *copiesEvidenceStore) List(ctx context.Context, prefix string) ([]string, error) { |
| + s.mu.Lock() |
| + s.lists++ |
| + s.mu.Unlock() |
| + return s.Store.List(ctx, prefix) |
| +} |
| + |
| +func TestCopiesPublicationEvidence(t *testing.T) { |
| + for _, tc := range []struct { |
| + name string |
| + explicit, safe bool |
| + failure string |
| + status int |
| + }{ |
| + {"legacy", false, false, "", 200}, |
| + {"explicit one", true, false, "", 200}, |
| + {"unread config unsafe", false, false, "config", 503}, |
| + {"unread config safe", false, true, "config", 200}, |
| + {"unread inventory unsafe", true, false, "record", 503}, |
| + {"unread inventory safe", true, true, "record", 200}, |
| + } { |
| + t.Run(tc.name, func(t *testing.T) { |
| + fx, token := copiesWorld(t) |
| + copiesUnsafeRelease(t, fx) |
| + if tc.explicit { |
| + for _, n := range []int{2, 1} { |
| + if _, err := appconfig.SetCopies(context.Background(), fx.rel, fx.sqid, "shop", n); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + } |
| + counter := &copiesEvidenceStore{Store: fx.rel, gets: map[string]int{}} |
| + cfgKey := appconfig.Key(fx.sqid, "shop") |
| + if tc.failure == "config" { |
| + counter.fail = cfgKey |
| + } |
| + recKey := provision.RecordKey(fx.sqid, "shop", "a.example.com") |
| + if tc.failure == "record" { |
| + counter.fail = recKey |
| + } |
| + fx.srv.cfg.Releases = counter |
| + door := copiesUnsafeDoors[0] |
| + if tc.safe { |
| + door.body = `{"channel":"canary/new","version":"v1"}` |
| + } |
| + code, out := copiesCall(t, fx, token, door) |
| + if code != tc.status { |
| + t.Fatalf("%d %s, want %d", code, out, tc.status) |
| + } |
| + counter.mu.Lock() |
| + defer counter.mu.Unlock() |
| + if counter.gets[cfgKey] != 1 { |
| + t.Fatalf("config GETs=%d, want exactly one", counter.gets[cfgKey]) |
| + } |
| + if (!tc.explicit || tc.safe) && counter.gets[recKey] != 0 { |
| + t.Fatal("legacy/safe target read assignments") |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestCopiesFreshInstanceInheritsCount(t *testing.T) { |
| + fx, token := copiesWorld(t) |
| + if code, out := copiesPut(t, fx, token, `{"copies":2}`); code != 200 { |
| + t.Fatalf("count: %d %s", code, out) |
| + } |
| + code, out := createShop(t, fx, token, `{"host":"new.example.com","channel":"edge"}`) |
| + if code != 201 { |
| + t.Fatalf("create: %d %s", code, out) |
| + } |
| + var reply provision.Record |
| + if err := json.Unmarshal([]byte(out), &reply); err != nil || reply.Hibernate == nil || *reply.Hibernate { |
| + t.Fatalf("create reply lost inherited always-on setting: %s (%v)", out, err) |
| + } |
| + rec, _ := storedShop(t, fx, "new.example.com") |
| + if rec.Hibernate == nil || *rec.Hibernate { |
| + t.Fatal("new replicated instance did not inherit always-on") |
| + } |
| + m, _ := appconfig.Get(context.Background(), fx.rel, fx.sqid, "shop") |
| + if appconfig.CopiesOf(m) != 2 { |
| + t.Fatal("new instance lost app count") |
| + } |
| +} |
| + |
| +func TestCopiesHibernatingShipAndArtifactRetention(t *testing.T) { |
| + for _, n := range []int{1, 2} { |
| + t.Run(string(rune('0'+n)), func(t *testing.T) { |
| + f := rootfsShipFixture(t) |
| + if _, err := appconfig.SetCopies(context.Background(), f.fx.rel, f.fx.sqid, "shop", 2); err != nil { |
| + t.Fatal(err) |
| + } |
| + if n == 1 { |
| + if _, err := appconfig.SetCopies(context.Background(), f.fx.rel, f.fx.sqid, "shop", 1); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + img := []byte("rootfs test image") |
| + fields := rootfsFields("v1", len(img), true) |
| + fields["stateless"] = true |
| + code, out := postShip(t, f.url("shop"), f.token, []shipPart{metaOf(t, fields), {name: "rootfs-linux-arm64", body: img}}) |
| + if n == 2 { |
| + wantRefusal(t, "hibernate", code, out, 409, copiesRelease) |
| + } else if code != 201 { |
| + t.Fatalf("one copy: %d %v", code, out) |
| + } |
| + f.assertScratchEmpty(t) |
| + }) |
| + } |
| + fx, token := copiesWorld(t) |
| + if code, out := copiesPut(t, fx, token, `{"copies":2}`); code != 200 { |
| + t.Fatalf("count: %d %s", code, out) |
| + } |
| + // A shipped stateful artifact is permitted but still cannot be selected. |
| + code, out := postShip(t, fx.ts.URL+"/api/cli/apps/"+fx.sqid+"/shop/releases", token, []shipPart{metaPart(t, "unsafe", "binary"), {name: "linux-amd64", body: tinyProgramForConsole(t, "example.com/shop")}}) |
| + if code != 201 { |
| + t.Fatalf("stateful artifact: %d %v", code, out) |
| + } |
| + code, body := copiesCall(t, fx, token, copiesUnsafeDoors[0]) |
| + if code != 409 || !strings.Contains(body, copiesRelease) { |
| + t.Fatalf("selected artifact: %d %s", code, body) |
| + } |
| +} |
| + |
| +// The count writer parks after all evidence has been checked and before CAS. |
| +// A selection must wait, then read the committed count under the same lock. |
| +type copiesCommitBarrier struct { |
| + release.Store |
| + key string |
| + entered, resume chan struct{} |
| + once sync.Once |
| +} |
| + |
| +func (s *copiesCommitBarrier) Put(ctx context.Context, key string, b []byte, etag string) (string, error) { |
| + if key == s.key { |
| + s.once.Do(func() { |
| + close(s.entered) |
| + select { |
| + case <-s.resume: |
| + case <-ctx.Done(): |
| + } |
| + }) |
| + } |
| + return s.Store.Put(ctx, key, b, etag) |
| +} |
| +func TestCopiesAdmissionSerializesAppMutations(t *testing.T) { |
| + for _, door := range copiesUnsafeDoors { |
| + t.Run(door.name, func(t *testing.T) { |
| + fx, token := copiesWorld(t) |
| + copiesUnsafeRelease(t, fx) |
| + barrier := &copiesCommitBarrier{Store: fx.rel, key: appconfig.Key(fx.sqid, "shop"), entered: make(chan struct{}), resume: make(chan struct{})} |
| + fx.srv.cfg.Releases = barrier |
| + var resume sync.Once |
| + defer resume.Do(func() { close(barrier.resume) }) |
| + type result struct { |
| + code int |
| + out string |
| + } |
| + counted := make(chan result, 1) |
| + go func() { c, b := copiesPut(t, fx, token, `{"copies":2}`); counted <- result{c, b} }() |
| + select { |
| + case <-barrier.entered: |
| + case <-time.After(10 * time.Second): |
| + t.Fatal("count did not reach CAS") |
| + } |
| + if !witnessLockHeld(fx.rel.(*deletableStore), fx.sqid+"/shop") { |
| + t.Fatal("count CAS is not protected by the app lock") |
| + } |
| + waiting := make(chan struct{}) |
| + appLockWaits(t, fx.sqid, waiting) |
| + selected := make(chan result, 1) |
| + go func() { c, b := copiesCall(t, fx, token, door); selected <- result{c, b} }() |
| + var early *result |
| + select { |
| + case <-waiting: |
| + case r := <-selected: |
| + early = &r |
| + case <-time.After(10 * time.Second): |
| + t.Error("selection neither waited nor completed") |
| + } |
| + resume.Do(func() { close(barrier.resume) }) |
| + if r := <-counted; r.code != 200 { |
| + t.Fatalf("count: %d %s", r.code, r.out) |
| + } |
| + var r result |
| + if early != nil { |
| + r = *early |
| + } else { |
| + r = <-selected |
| + } |
| + if r.code != 409 { |
| + t.Fatalf("count>1 committed with unsafe %s: %d %s", door.name, r.code, r.out) |
| + } |
| + }) |
| + } |
| + t.Run("trash recreate rejects old admission", func(t *testing.T) { |
| + fx, token := copiesWorld(t) |
| + unlock := fx.srv.lockApp(fx.sqid, "shop") |
| + waiting := make(chan struct{}) |
| + appLockWaits(t, fx.sqid, waiting) |
| + done := make(chan int, 1) |
| + go func() { c, _ := copiesPut(t, fx, token, `{"copies":2}`); done <- c }() |
| + select { |
| + case <-waiting: |
| + case <-time.After(10 * time.Second): |
| + unlock() |
| + t.Fatal("admission did not wait") |
| + } |
| + if err := fx.st.TrashAppRow(OpsAccountID, "shop", time.Now()); err != nil { |
| + unlock() |
| + t.Fatal(err) |
| + } |
| + if err := fx.st.PurgeAppRow(OpsAccountID, "shop"); err != nil { |
| + unlock() |
| + t.Fatal(err) |
| + } |
| + if _, err := fx.st.CreateAppIn(OpsAccountID, "shop", "paul@keymail.dev", time.Now()); err != nil { |
| + unlock() |
| + t.Fatal(err) |
| + } |
| + unlock() |
| + if code := <-done; code != 409 { |
| + t.Fatalf("old admission: %d", code) |
| + } |
| + if _, _, err := fx.rel.Get(context.Background(), appconfig.Key(fx.sqid, "shop")); !errors.Is(err, os.ErrNotExist) { |
| + t.Fatalf("old admission wrote: %v", err) |
| + } |
| + }) |
| +} |
| + |
| +func TestCopiesPendingAndExactTargetGuard(t *testing.T) { |
| + fx, token := copiesWorld(t) |
| + copiesUnsafeRelease(t, fx) |
| + if code, out := copiesPut(t, fx, token, `{"copies":2}`); code != 200 { |
| + t.Fatalf("count: %d %s", code, out) |
| + } |
| + acct, _ := fx.st.AccountBySqid(fx.sqid) |
| + ctx, unlock, ref := fx.srv.beginCopiesMutation(context.Background(), acct, "shop") |
| + if ref != nil { |
| + t.Fatal(ref) |
| + } |
| + defer unlock() |
| + if err := fx.srv.statelessSelectionGuard(ctx, fx.sqid, "shop", "edge")("unsafe"); err == nil || err.Error() != copiesRelease { |
| + t.Fatalf("actual CAS target: %v", err) |
| + } |
| + // Execution is a separate mutation from proposal creation. |
| + pc := &PendingChange{} |
| + pc.Payload, _ = json.Marshal(fastTrackPayload{Channel: "canary/unsafe", Version: "unsafe"}) |
| + if _, err := fx.srv.executePendingFastTrack(ctx, acct, "shop", "paul@keymail.dev", pc); err == nil || !strings.Contains(err.Error(), copiesRelease) { |
| + t.Fatalf("pending fast-track: %v", err) |
| + } |
| +} |
| + |
| +// A request's captured incarnation also survives an upload before the lock. |
| +func TestCopiesIncarnationFence(t *testing.T) { |
| + fx, _ := copiesWorld(t) |
| + acct, _ := fx.st.AccountBySqid(fx.sqid) |
| + r := httptest.NewRequest("POST", "/", nil) |
| + fx.srv.captureCopiesAdmission(r, acct, "shop") |
| + if err := fx.st.TrashAppRow(OpsAccountID, "shop", time.Now()); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := fx.st.PurgeAppRow(OpsAccountID, "shop"); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := fx.st.CreateAppIn(OpsAccountID, "shop", "paul@keymail.dev", time.Now()); err != nil { |
| + t.Fatal(err) |
| + } |
| + _, unlock, ref := fx.srv.beginCopiesMutation(r.Context(), acct, "shop") |
| + defer unlock() |
| + if ref == nil || ref.Status != http.StatusConflict { |
| + t.Fatalf("stale publication admitted: %v", ref) |
| + } |
| +} |
| + |
| +func TestCopiesPendingPromoteAndChannel(t *testing.T) { |
| + fx, token := copiesWorld(t) |
| + copiesUnsafeRelease(t, fx) |
| + setPipeline(t, fx, "shop", release.PipelineChannel{Name: "edge"}, release.PipelineChannel{Name: "stable"}) |
| + // These payloads are prepared at count 1 and executed after count 2 lands. |
| + promote := &PendingChange{} |
| + promote.Payload, _ = json.Marshal(promotePayload{Channel: "edge", Version: "unsafe", Hotfix: true}) |
| + rec, etag, err := provision.GetRecordETag(context.Background(), fx.rel, fx.sqid, "shop", "a.example.com") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + channel := &PendingChange{} |
| + channel.Payload, _ = json.Marshal(channelMovePayload{Host: rec.Host, From: rec.Channel, To: "canary/unsafe", ETag: etag}) |
| + if code, out := copiesPut(t, fx, token, `{"copies":2}`); code != 200 { |
| + t.Fatalf("count: %d %s", code, out) |
| + } |
| + acct, _ := fx.st.AccountBySqid(fx.sqid) |
| + if _, err := fx.srv.executePendingPromote(context.Background(), acct, "shop", "paul@keymail.dev", promote); err == nil || err.Error() != copiesRelease { |
| + t.Fatalf("pending promote: %v", err) |
| + } |
| + if _, err := fx.srv.executePendingRouteChannel(context.Background(), acct, "shop", "paul@keymail.dev", channel); err == nil || err.Error() != copiesRelease { |
| + t.Fatalf("pending channel: %v", err) |
| + } |
| +} |
| + |
| +func TestCopiesBrowserPublication(t *testing.T) { |
| + for _, tc := range []struct { |
| + path string |
| + form url.Values |
| + }{ |
| + {"promote", url.Values{"channel": {"canary/new"}, "version": {"unsafe"}}}, |
| + {"rollback", url.Values{"channel": {"edge"}}}, |
| + {"canary", url.Values{"name": {"new"}, "version": {"unsafe"}}}, |
| + } { |
| + t.Run(tc.path, func(t *testing.T) { |
| + fx, token := copiesWorld(t) |
| + copiesUnsafeRelease(t, fx) |
| + if code, out := copiesPut(t, fx, token, `{"copies":2}`); code != 200 { |
| + t.Fatalf("count: %d %s", code, out) |
| + } |
| + c := signInPaul(t, fx) |
| + tc.form.Set("csrf", sessionToken(t, fx, c)) |
| + tc.form.Set("confirmed", "1") |
| + code, _, out := postForm(t, c, fx.u("/apps/shop/"+tc.path), tc.form) |
| + if code != http.StatusSeeOther { |
| + t.Fatalf("browser: %d %s", code, out) |
| + } |
| + if fx.channelVersion(t, "shop", "edge").Version != "v1" { |
| + t.Fatal("browser rollback selected unsafe release") |
| + } |
| + if _, _, err := fx.rel.Get(context.Background(), release.ChannelKey(fx.sqid, "shop", "canary/new")); !errors.Is(err, os.ErrNotExist) { |
| + t.Fatal("browser selected unsafe release") |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestCopiesAdmissionSerializesShip(t *testing.T) { |
| + fx, token, _ := fleetBoxWorld(t, "copies-rootfs-race", "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] |
| + ver := []string{"v1", "v2"}[i] |
| + putFleetRecord(t, fx, "shop", host, func(r *provision.Record) { |
| + r.Channel = channel |
| + r.Runtime = provision.RuntimeRootfsV1 |
| + r.Hibernate = new(bool) |
| + r.FleetBox = []string{"pi-1", "pi-2"}[i] |
| + }) |
| + m := release.Manifest{Schema: 1, App: "shop", Version: ver, Kind: release.KindRootfs, Stateless: true, Processes: map[string]release.Process{"web": {Command: []string{"bin/web"}}}, Artifacts: map[string]release.Artifact{release.RootfsArtifactKey: {File: release.RootfsArtifactFile}}} |
| + if err := release.Ship(context.Background(), fx.rel, fx.sqid, m, map[string][]byte{release.RootfsArtifactKey: []byte("rootfs image")}); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := release.Promote(context.Background(), fx.rel, fx.priv, fx.sqid, "shop", channel, ver); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + for _, box := range []string{"pi-1", "pi-2"} { |
| + copiesBeat(t, fx, box, release.StatelessReplicasFloor, time.Now()) |
| + } |
| + scratch := filepath.Join(t.TempDir(), "seeds") |
| + if err := clearSeedScratch(scratch); err != nil { |
| + t.Fatal(err) |
| + } |
| + fx.srv.seedScratch = newSeedScratch(scratch, func(string) (int64, error) { return 64 << 30, nil }) |
| + liftShipBudget(fx) |
| + barrier := &copiesCommitBarrier{Store: fx.rel, key: appconfig.Key(fx.sqid, "shop"), entered: make(chan struct{}), resume: make(chan struct{})} |
| + fx.srv.cfg.Releases = barrier |
| + var resume sync.Once |
| + defer resume.Do(func() { close(barrier.resume) }) |
| + counted := make(chan int, 1) |
| + go func() { c, _ := copiesPut(t, fx, token, `{"copies":2}`); counted <- c }() |
| + select { |
| + case <-barrier.entered: |
| + case <-time.After(10 * time.Second): |
| + t.Fatal("count did not reach CAS") |
| + } |
| + waiting := make(chan struct{}) |
| + appLockWaits(t, fx.sqid, waiting) |
| + shipped := make(chan int, 1) |
| + go func() { |
| + img := []byte("hibernate image") |
| + fields := rootfsFields("v3", len(img), true) |
| + fields["stateless"] = true |
| + c, _ := postShip(t, fx.ts.URL+"/api/cli/apps/"+fx.sqid+"/shop/releases", token, []shipPart{metaOf(t, fields), {name: "rootfs-linux-arm64", body: img}}) |
| + shipped <- c |
| + }() |
| + early := 0 |
| + select { |
| + case <-waiting: |
| + case early = <-shipped: |
| + case <-time.After(10 * time.Second): |
| + t.Error("ship did not wait") |
| + } |
| + resume.Do(func() { close(barrier.resume) }) |
| + if code := <-counted; code != 200 { |
| + t.Fatalf("count: %d", code) |
| + } |
| + code := early |
| + if code == 0 { |
| + code = <-shipped |
| + } |
| + if code != 409 { |
| + t.Fatalf("hibernating ship committed across count admission: %d", code) |
| + } |
| + if _, _, err := fx.rel.Get(context.Background(), release.ManifestKey(fx.sqid, "shop", "v3")); !errors.Is(err, os.ErrNotExist) { |
| + t.Fatal("refused ship wrote manifest") |
| + } |
| +} |
| + |
| +// Two eligible destinations do not excuse an old draining member of the roster. |
| +func TestCopiesFloorIncludesNonDestinations(t *testing.T) { |
| + fx, token := copiesWorld(t) |
| + reg := openTestReg(t, fx) |
| + defer reg.Close() |
| + registerFleetBox(t, reg, "pi", "pi-3") |
| + copiesBeat(t, fx, "pi-3", "v0.34.0", time.Now()) |
| + if _, err := reg.SetFleetBoxDraining("pi", "pi-3", time.Now().UnixNano()); err != nil { |
| + t.Fatal(err) |
| + } |
| + if code, out := copiesPut(t, fx, token, `{"copies":2}`); code != 409 || !strings.Contains(out, "copies above 1") { |
| + t.Fatalf("old draining box bypassed fleet floor: %d %s", code, out) |
| + } |
| +} |
| + |
| +func TestCopiesCannotAddSidecarAfterAdmission(t *testing.T) { |
| + fx, token := copiesWorld(t) |
| + if code, out := copiesPut(t, fx, token, `{"copies":2}`); code != 200 { |
| + t.Fatalf("count: %d %s", code, out) |
| + } |
| + reg := openTestReg(t, fx) |
| + defer reg.Close() |
| + if err := reg.SetFleetBoxStatus("pi", "pi-2", "detached"); err != nil { |
| + t.Fatal(err) |
| + } |
| + enableSidecars(t, fx, "shop", provision.SidecarManifest{Schema: 1, App: "shop", Channel: "edge", Args: []string{"sidecar", "run"}}) |
| + code, _, out := rawReq(t, "POST", sidecarsURL(fx, fx.sqid, "shop"), token, `{"name":"bot"}`) |
| + if code != 409 || !strings.Contains(out, copiesManaged) { |
| + t.Fatalf("sidecar: %d %s", code, out) |
| + } |
| +} |
| + |
| +func TestCopiesFreshRootfsChecksEveryDestination(t *testing.T) { |
| + fx, token, _ := fleetBoxWorld(t, "copies-first-rootfs", "pi-1", "pi-2") |
| + fx.srv.consoleBuild = release.StatelessReplicasFloor |
| + piBeat(t, fx, "pi-1", true, time.Now(), release.StatelessReplicasFloor) |
| + piBeat(t, fx, "pi-2", false, time.Now(), release.StatelessReplicasFloor) |
| + m := release.Manifest{Schema: 1, App: "shop", Version: "v1", Kind: release.KindRootfs, Stateless: true, Processes: map[string]release.Process{"web": {Command: []string{"bin/web"}}}, Artifacts: map[string]release.Artifact{release.RootfsArtifactKey: {File: release.RootfsArtifactFile}}} |
| + if err := release.Ship(context.Background(), fx.rel, fx.sqid, m, map[string][]byte{release.RootfsArtifactKey: []byte("rootfs image")}); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := release.Promote(context.Background(), fx.rel, fx.priv, fx.sqid, "shop", "edge", "v1"); err != nil { |
| + t.Fatal(err) |
| + } |
| + if code, out := copiesPut(t, fx, token, `{"copies":2}`); code != 200 { |
| + t.Fatalf("count: %d %s", code, out) |
| + } |
| + code, out := createShop(t, fx, token, `{"host":"first.example.com","channel":"edge"}`) |
| + if code != 409 || !strings.Contains(out, "2 copies need 2 eligible boxes") { |
| + t.Fatalf("rootfs copies admitted without two ready boxes: %d %s", code, out) |
| + } |
| + if _, _, err := fx.rel.Get(context.Background(), provision.RecordKey(fx.sqid, "shop", "first.example.com")); !errors.Is(err, os.ErrNotExist) { |
| + t.Fatalf("refused create wrote a record: %v", err) |
| + } |
| +} |
diff --git a/internal/console/hostsused.go b/internal/console/hostsused.go| index e38c0160d..d4be2a94a 100644 |
| --- a/internal/console/hostsused.go |
| +++ b/internal/console/hostsused.go |
| @@ -559,36 +559,40 @@ func recordUse(rec provision.Record) provision.HostUse { |
| // (placeAppTarget), and then the hostname exclusion (the lock table's order, |
| // lifetimes.go), so the regional recheck (#447) and the write are one hold |
| // against a placements PUT. |
| -func (s *Server) createRecordMarked(ctx context.Context, rec provision.Record) error { |
| +func (s *Server) createRecordMarked(ctx context.Context, rec provision.Record) (*provision.Record, error) { |
| defer s.lockApp(rec.Account, rec.App)() // record writes hold the app lock (recordlock.go) |
| defer s.lockHostname(rec.Host)() |
| + defer s.copiesCreateNameLock(ctx)() |
| + if err := s.copiesCreateCheck(ctx, &rec); err != nil { |
| + return nil, err |
| + } |
| // The regional recheck (spec §6.3): a regional claim written since the |
| // door's first check refuses the create before anything is marked. |
| if err := s.regionalRecheck(ctx, rec); err != nil { |
| - return err |
| + return nil, err |
| } |
| // The first-kind boundary (rootfs.go): under the lock, before the mark. |
| if err := s.firstKindRecheck(ctx, rec); err != nil { |
| - return err |
| + return nil, err |
| } |
| // The owned-environment boundary (teamenv.go): under the lock, the |
| // environment the record binds is still one the door's scope may. |
| if err := s.ownedBindingRecheck(ctx, rec); err != nil { |
| - return err |
| + return nil, err |
| } |
| if rec.DataKind() { |
| if ref := s.gateDataCreate(ctx, rec.Host, rec.Region); ref != nil { |
| - return &hostsUsedError{*ref} |
| + return nil, &hostsUsedError{*ref} |
| } |
| if err := s.markBeforeCreate(ctx, recordUse(rec), provision.RecordKey(rec.Account, rec.App, rec.Host)); err != nil { |
| - return err |
| + return nil, err |
| } |
| } |
| if err := provision.CreateRecord(ctx, s.cfg.Releases, rec); err != nil { |
| - return err |
| + return nil, err |
| } |
| instanceCreateStage(instanceCreateAfterRecordWrite, rec.Host) // still under both locks |
| - return nil |
| + return &rec, nil |
| } |
| // createSidecarMarked is the sidecar door's create: a sidecar is always a |
| @@ -596,6 +600,10 @@ func (s *Server) createRecordMarked(ctx context.Context, rec provision.Record) e |
| // provision.CreateSidecarRecord. |
| func (s *Server) createSidecarMarked(ctx context.Context, rec provision.SidecarRecord) error { |
| defer s.lockApp(rec.Account, rec.App)() // record writes hold the app lock (recordlock.go) |
| + defer s.copiesCreateNameLock(ctx)() |
| + if ref := s.copiesSidecarRefusal(ctx, rec.Account, rec.App); ref != nil { |
| + return &hostsUsedError{*ref} |
| + } |
| if ref := s.gateDataCreate(ctx, rec.Host, rec.Region); ref != nil { |
| return &hostsUsedError{*ref} |
| } |
diff --git a/internal/console/lifetimes_create.go b/internal/console/lifetimes_create.go| index 5fadcf249..8d8340457 100644 |
| --- a/internal/console/lifetimes_create.go |
| +++ b/internal/console/lifetimes_create.go |
| @@ -61,6 +61,10 @@ func (s *Server) createRecordWithLifetime(ctx context.Context, rec provision.Rec |
| // errLifetimeSettling, errLifetimePending, or a read error with nothing |
| // persisted. |
| func (s *Server) createRecordWithLifetimeLocked(ctx context.Context, rec provision.Record, lifetime string) (*provision.Record, error) { |
| + defer s.copiesCreateNameLock(ctx)() |
| + if err := s.copiesCreateCheck(ctx, &rec); err != nil { |
| + return nil, err |
| + } |
| if len(rec.Maintenance) != 0 { |
| return nil, provision.ErrMaintenanceProjection |
| } |
diff --git a/internal/console/pendinghandlers.go b/internal/console/pendinghandlers.go| index 20175872b..9e659a49c 100644 |
| --- a/internal/console/pendinghandlers.go |
| +++ b/internal/console/pendinghandlers.go |
| @@ -489,6 +489,12 @@ func staleProposal(detail string) error { |
| } |
| func (s *Server) executePendingPromote(ctx context.Context, acct *Account, app, actor string, pc *PendingChange) (string, error) { |
| + |
| + ctx, copiesUnlock, copiesLockRef := s.beginCopiesMutation(ctx, acct, app) |
| + if copiesLockRef != nil { |
| + return "", &statelessSelectionError{copiesLockRef} |
| + } |
| + defer copiesUnlock() |
| var p promotePayload |
| if err := json.Unmarshal(pc.Payload, &p); err != nil { |
| return "", errors.New("this proposal's payload cannot be read — reject it and propose again") |
| @@ -561,6 +567,9 @@ func (s *Server) executePendingPromote(ctx context.Context, acct *Account, app, |
| return "", &statelessSelectionError{ref} |
| } |
| + if ref := s.copiesPublicationRefusal(ctx, acct, app, nil, p.Version, false); ref != nil { |
| + return "", &statelessSelectionError{ref} |
| + } |
| 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 { |
| @@ -624,6 +633,12 @@ func (s *Server) executePendingPolicy(ctx context.Context, acct *Account, app, a |
| } |
| func (s *Server) executePendingFastTrack(ctx context.Context, acct *Account, app, actor string, pc *PendingChange) (string, error) { |
| + |
| + ctx, copiesUnlock, copiesLockRef := s.beginCopiesMutation(ctx, acct, app) |
| + if copiesLockRef != nil { |
| + return "", &statelessSelectionError{copiesLockRef} |
| + } |
| + defer copiesUnlock() |
| var p fastTrackPayload |
| if err := json.Unmarshal(pc.Payload, &p); err != nil { |
| return "", errors.New("this proposal's payload cannot be read — reject it and propose again") |
diff --git a/internal/console/perfwrites_test.go b/internal/console/perfwrites_test.go| index 2f188699b..e3e136cf3 100644 |
| --- a/internal/console/perfwrites_test.go |
| +++ b/internal/console/perfwrites_test.go |
| @@ -325,14 +325,18 @@ type perfWriteLimit struct { |
| // once more under the record lock and the hostname exclusion, so a regional |
| // domain written since the door's first check refuses the create. About |
| // 580 ms, inside the door's budget. |
| +// P7 (stateless replicas, 2026-11-02) allows one default-config GET under |
| +// the app lock at publication/create doors. The measured deltas are exactly |
| +// one for ship, instance create, promote and instances-manifest put; other |
| +// request caps and every timing budget remain unchanged. |
| func perfWriteLimits() map[string]perfWriteLimit { |
| return map[string]perfWriteLimit{ |
| - "ship": {Calls: 32, Budget: perfWriteBudget}, |
| - "instance create": {Calls: 52, Budget: 700 * time.Millisecond, Over: "24 requests one after another: the manifest, the host holder (record then slot), the channel head (pointer then manifest), the plan cap's listings, then under the record lock the regional recheck's claim read (#447), the app's tombstone, this key's record and slot, every other app's, three writes in the lifetime protocol's order, the change index and the serial"}, |
| + "ship": {Calls: 33, Budget: perfWriteBudget}, |
| + "instance create": {Calls: 53, Budget: 700 * time.Millisecond, Over: "24 requests one after another: the manifest, the host holder (record then slot), the channel head (pointer then manifest), the plan cap's listings, then under the record lock the regional recheck's claim read (#447), the app's tombstone, this key's record and slot, every other app's, three writes in the lifetime protocol's order, the change index and the serial"}, |
| "app create": {Calls: 50, Budget: perfWriteBudget}, |
| - "promote": {Calls: 18, Budget: 600 * time.Millisecond, Over: "the signed promote's own reads and writes, one after another, inside release.PromoteOnLadder: on flagship 470 ms before this branch, one read fewer after it"}, |
| + "promote": {Calls: 19, Budget: 600 * time.Millisecond, Over: "the signed promote's own reads and writes, one after another, inside release.PromoteOnLadder: on flagship 470 ms before this branch, one read fewer after it"}, |
| "config put": {Calls: 10, Budget: perfWriteBudget}, |
| - "instances-manifest put": {Calls: 6, Budget: perfWriteBudget}, |
| + "instances-manifest put": {Calls: 7, Budget: perfWriteBudget}, |
| } |
| } |
diff --git a/internal/console/record_write_lock_test.go b/internal/console/record_write_lock_test.go| index d01c5190c..098561f65 100644 |
| --- a/internal/console/record_write_lock_test.go |
| +++ b/internal/console/record_write_lock_test.go |
| @@ -134,7 +134,22 @@ func appLockHolders(t *testing.T) map[string]bool { |
| if !ok || fd.Body == nil { |
| continue |
| } |
| + lockHandles := map[string]bool{} |
| for _, st := range fd.Body.List { |
| + if assign, ok := st.(*ast.AssignStmt); ok && len(assign.Rhs) == 1 && len(assign.Lhs) == 3 { |
| + if call, ok := assign.Rhs[0].(*ast.CallExpr); ok { |
| + if sel, ok := call.Fun.(*ast.SelectorExpr); ok && sel.Sel.Name == "beginCopiesMutation" { |
| + if id, ok := assign.Lhs[1].(*ast.Ident); ok { |
| + lockHandles[id.Name] = true |
| + } |
| + } |
| + } |
| + } |
| + if ds, ok := st.(*ast.DeferStmt); ok { |
| + if id, ok := ds.Call.Fun.(*ast.Ident); ok && lockHandles[id.Name] { |
| + set[fd.Name.Name] = true |
| + } |
| + } |
| ds, ok := st.(*ast.DeferStmt) |
| if !ok { |
| continue |
diff --git a/internal/console/reqmemo.go b/internal/console/reqmemo.go| index cdb2f9091..124494b63 100644 |
| --- a/internal/console/reqmemo.go |
| +++ b/internal/console/reqmemo.go |
| @@ -75,7 +75,7 @@ func withWriteMemo(ctx context.Context) context.Context { |
| // writeMemoKey includes the stateless platform-floor snapshot so a preflight |
| // and the guarded selection share one read, including a failed read. |
| func writeMemoKey(key string) bool { |
| - return key == "edges" || strings.HasPrefix(key, "boxes:") || strings.HasPrefix(key, "stateless-system-pointer:") || strings.HasPrefix(key, "stateless-manifest:") |
| + return strings.HasPrefix(key, "copies-config:") || key == "edges" || strings.HasPrefix(key, "boxes:") || strings.HasPrefix(key, "stateless-system-pointer:") || strings.HasPrefix(key, "stateless-manifest:") |
| } |
| // memoOf is ctx's memo when it holds key, nil otherwise. |
diff --git a/internal/console/rootfs.go b/internal/console/rootfs.go| index d48cea423..00321efb3 100644 |
| --- a/internal/console/rootfs.go |
| +++ b/internal/console/rootfs.go |
| @@ -90,6 +90,13 @@ func (e *statelessSelectionError) Error() string { return e.ref.Msg } |
| // write, so a rollback or bake waiver cannot select an unchecked successor. |
| func (s *Server) statelessSelectionGuard(ctx context.Context, acct, app, channel string) func(string) error { |
| return func(version string) error { |
| + account, err := s.store.AccountBySqid(acct) |
| + if err != nil || account == nil { |
| + return &statelessSelectionError{copiesUnavailable()} |
| + } |
| + if ref := s.copiesPublicationRefusal(ctx, account, app, nil, version, false); ref != nil { |
| + return &statelessSelectionError{ref} |
| + } |
| if ref := s.statelessVersionRefusal(ctx, acct, app, channel, version); ref != nil { |
| return &statelessSelectionError{ref} |
| } |
diff --git a/internal/console/rootfs_move_test.go b/internal/console/rootfs_move_test.go| index fcd246a3d..9c5ed04d7 100644 |
| --- a/internal/console/rootfs_move_test.go |
| +++ b/internal/console/rootfs_move_test.go |
| @@ -239,7 +239,10 @@ func TestPlaceWaitsForACreateInFlight(t *testing.T) { |
| entered: make(chan struct{}), release: make(chan struct{})} |
| fx.srv.cfg.Releases = gate |
| created := make(chan error, 1) |
| - go func() { created <- fx.srv.createRecordMarked(context.Background(), rootfsCreateRecord(fx.sqid)) }() |
| + go func() { |
| + _, err := fx.srv.createRecordMarked(context.Background(), rootfsCreateRecord(fx.sqid)) |
| + created <- err |
| + }() |
| waitForSignal(t, gate.entered, "the rootfs record's create") |
| placeWaiting := make(chan struct{}) |
| appLockWaits(t, fx.sqid, placeWaiting) |
| @@ -286,7 +289,10 @@ func TestACreateWaitsForAPlaceInFlight(t *testing.T) { |
| switch n { |
| case 1: // the place's check, under its lock |
| appLockWaits(t, fx.sqid, createWaiting) |
| - go func() { created <- fx.srv.createRecordMarked(context.Background(), rootfsCreateRecord(fx.sqid)) }() |
| + go func() { |
| + _, err := fx.srv.createRecordMarked(context.Background(), rootfsCreateRecord(fx.sqid)) |
| + created <- err |
| + }() |
| case 2: // the place's walk: the create is waiting, or (without the lock) done |
| select { |
| case <-createWaiting: |
diff --git a/internal/console/server.go b/internal/console/server.go| index ea7eb5a28..aeb4704cf 100644 |
| --- a/internal/console/server.go |
| +++ b/internal/console/server.go |
| @@ -4229,6 +4229,7 @@ func (s *Server) accountApp(w http.ResponseWriter, r *http.Request) (addr, raw s |
| s.renderMessage(w, r, http.StatusNotFound, "Not found", "No such app here.") |
| return "", "", nil, "", "", false |
| } |
| + s.captureCopiesAdmission(r, acct, app) |
| return addr, raw, acct, role, app, true |
| } |
| @@ -5672,6 +5673,13 @@ func (s *Server) handlePromote(w http.ResponseWriter, r *http.Request) { |
| version := strings.TrimSpace(r.FormValue("version")) |
| ctx, cancel := context.WithTimeout(r.Context(), 15*time.Second) |
| defer cancel() |
| + ctx, copiesUnlock, copiesLockRef := s.beginCopiesMutation(ctx, acct, app) |
| + if copiesLockRef != nil { |
| + back("err", copiesLockRef.Msg) |
| + return |
| + } |
| + defer copiesUnlock() |
| + |
| if !release.ValidVersion(version) { |
| back("err", "Invalid version.") |
| return |
| @@ -5718,6 +5726,10 @@ func (s *Server) handlePromote(w http.ResponseWriter, r *http.Request) { |
| http.NotFound(w, r) |
| return |
| } |
| + if ref := s.copiesPublicationRefusal(ctx, acct, app, man, "", false); ref != nil { |
| + back("err", ref.Msg) |
| + return |
| + } |
| if ref := s.statelessRuntimeRefusal(ctx, channel, man, nil, ""); ref != nil { |
| back("err", ref.Msg) |
| return |
| @@ -5927,6 +5939,13 @@ func (s *Server) handleRollback(w http.ResponseWriter, r *http.Request) { |
| } |
| ctx, cancel := context.WithTimeout(r.Context(), 15*time.Second) |
| defer cancel() |
| + ctx, copiesUnlock, copiesLockRef := s.beginCopiesMutation(ctx, acct, app) |
| + if copiesLockRef != nil { |
| + back("err", copiesLockRef.Msg) |
| + return |
| + } |
| + defer copiesUnlock() |
| + |
| // Which gate this rollback meets is the pipeline's answer, so it is read |
| // before the confirm card — the same reasoning, and the same order, as |
| // handlePromote. |
| @@ -6193,6 +6212,13 @@ func (s *Server) handleFastTrack(w http.ResponseWriter, r *http.Request) { |
| // refusal; the alternative is an oracle. |
| ctx, cancel := context.WithTimeout(r.Context(), 15*time.Second) |
| defer cancel() |
| + ctx, copiesUnlock, copiesLockRef := s.beginCopiesMutation(ctx, acct, app) |
| + if copiesLockRef != nil { |
| + back("err", copiesLockRef.Msg) |
| + return |
| + } |
| + defer copiesUnlock() |
| + |
| // holdWindow, not HoldFor: a pipelined channel's window is its own, for a |
| // name the legacy table may never have heard of — and an app that |
| // declared a 0s bake on a channel has nothing to waive there either. |
| @@ -6410,11 +6436,22 @@ func (s *Server) handleNewCanary(w http.ResponseWriter, r *http.Request) { |
| } |
| ctx, cancel := context.WithTimeout(r.Context(), 15*time.Second) |
| defer cancel() |
| + ctx, copiesUnlock, copiesLockRef := s.beginCopiesMutation(ctx, acct, app) |
| + if copiesLockRef != nil { |
| + back("err", copiesLockRef.Msg) |
| + return |
| + } |
| + defer copiesUnlock() |
| + |
| man, err := release.GetManifest(ctx, s.cfg.Releases, acct.Sqid, app, version) |
| if err != nil { |
| back("err", "Version "+version+" is not a shipped release of "+app+".") |
| return |
| } |
| + if ref := s.copiesPublicationRefusal(ctx, acct, app, man, "", false); ref != nil { |
| + back("err", ref.Msg) |
| + return |
| + } |
| if ref := s.statelessRuntimeRefusal(ctx, channel, man, nil, ""); ref != nil { |
| back("err", ref.Msg) |
| return |
diff --git a/internal/console/svcroutes_test.go b/internal/console/svcroutes_test.go| index 0b5375ff3..83d30c883 100644 |
| --- a/internal/console/svcroutes_test.go |
| +++ b/internal/console/svcroutes_test.go |
| @@ -259,6 +259,7 @@ var closedDoors = []string{ |
| // app members": a credential the app holds must not choose what its own |
| // migrations run beside. |
| "PUT /api/cli/apps/{account}/{app}/swap", |
| + "PUT /api/cli/apps/{account}/{app}/copies", |
| // The interactive sessions setting (rootfs apps spec §5.10): whether |
| // members may open a live shell into production data on the app's |
| // instances. A credential the app holds must not open that for itself; |
diff --git a/internal/console/updatescore.go b/internal/console/updatescore.go| index 776884383..491fc0f76 100644 |
| --- a/internal/console/updatescore.go |
| +++ b/internal/console/updatescore.go |
| @@ -94,6 +94,11 @@ func (s *Server) enableRefusal(ctx context.Context, what string) (int, string) { |
| // or a status and the reviewed refusal. An empty req writes nothing. It |
| // writes preferences only: the console never chooses a build (spec §4). |
| func (s *Server) applyUpdates(ctx context.Context, acct *Account, app, principal string, rec *provision.Record, etag string, policy *provision.UpdatePolicy, req map[string]any) (updatesView, int, string) { |
| + ctx, unlock, ref := s.beginCopiesMutation(ctx, acct, app) |
| + if ref != nil { |
| + return updatesView{}, ref.Status, ref.Msg |
| + } |
| + defer unlock() |
| if st, msg := shapeRefusal(rec); st != 0 { |
| return updatesView{}, st, msg |
| } |
| @@ -169,6 +174,10 @@ func (s *Server) applyUpdates(ctx context.Context, acct *Account, app, principal |
| } |
| } |
| + if ref := s.copiesRecordRefusal(ctx, acct, next, false); ref != nil { |
| + return updatesView{}, ref.Status, ref.Msg |
| + } |
| + |
| // Only a change that turns a setting ON waits for the fleet: manual newly |
| // set, a different pin, or a new major. A value re-sent unchanged beside |
| // a clear (a form that sends its full state) is not an enable, so the |
| @@ -181,7 +190,7 @@ func (s *Server) applyUpdates(ctx context.Context, acct *Account, app, principal |
| return updatesView{}, st, msg |
| } |
| } |
| - if err := s.withRecordLock(next.Account, next.App, func() error { return provision.UpdateRecord(ctx, s.cfg.Releases, next, etag) }); err != nil { |
| + if err := provision.UpdateRecord(ctx, s.cfg.Releases, next, etag); err != nil { |
| if errors.Is(err, release.ErrCASConflict) { |
| return updatesView{}, http.StatusConflict, updatewords.Text("settings.console.changed") |
| } |
| @@ -204,6 +213,11 @@ func (s *Server) applyUpdates(ctx context.Context, acct *Account, app, principal |
| // message for a host with no record). Root resolves the request to a build; |
| // the console never names one. |
| func (s *Server) requestInstall(ctx context.Context, acct *Account, app, principal, host string, fast bool) (uint64, int, string) { |
| + ctx, unlock, ref := s.beginCopiesMutation(ctx, acct, app) |
| + if ref != nil { |
| + return 0, ref.Status, ref.Msg |
| + } |
| + defer unlock() |
| for attempt := 0; attempt < 5; attempt++ { |
| rec, etag, _, st, msg := s.readUpdatesTarget(ctx, acct, app, host) |
| if st != 0 { |
| @@ -221,7 +235,10 @@ func (s *Server) requestInstall(ctx context.Context, acct *Account, app, princip |
| } |
| next := *rec |
| next.InstallRequest = &provision.InstallRequest{ID: id, FastTrack: fast, At: time.Now().UTC().Truncate(time.Second), By: principal} |
| - err := s.withRecordLock(next.Account, next.App, func() error { return provision.UpdateRecord(ctx, s.cfg.Releases, next, etag) }) |
| + if ref := s.copiesRecordRefusal(ctx, acct, next, false); ref != nil { |
| + return 0, ref.Status, ref.Msg |
| + } |
| + err := provision.UpdateRecord(ctx, s.cfg.Releases, next, etag) |
| if errors.Is(err, release.ErrCASConflict) { |
| continue // another writer moved the record: read it again |
| } |
diff --git a/internal/provision/plan9_b8_census_test.go b/internal/provision/plan9_b8_census_test.go| index e32e1bcec..2d8c610d3 100644 |
| --- a/internal/provision/plan9_b8_census_test.go |
| +++ b/internal/provision/plan9_b8_census_test.go |
| @@ -366,7 +366,7 @@ func TestPlan9B8RecordWriteCensus(t *testing.T) { |
| if len(got) < 100 { |
| t.Fatalf("census found only %d units under %s; the walk is broken", len(got), root) |
| } |
| - inventory := statelessReplicasWriteCensusInventory() |
| + inventory := statelessPlacementWriteCensusInventory() |
| problems := append(censusDiff(inventory, got), censusPolicy(inventory)...) |
| if len(problems) > 0 { |
| t.Fatalf("record-write census rejected %d site(s); update the explicit inventory only after reviewing the source:\n %s", len(problems), strings.Join(problems, "\n ")) |
diff --git a/internal/provision/stateless_placement_census_test.go b/internal/provision/stateless_placement_census_test.go| new file mode 100644 |
| index 000000000..eef0bdaf6 |
| --- /dev/null |
| +++ b/internal/provision/stateless_placement_census_test.go |
| @@ -0,0 +1,42 @@ |
| +package provision |
| + |
| +// Plan 2 Task 1 slice 1b author review, including the two slice 1a CI gaps. |
| +// These notes explain each re-digest. Independent approval is controller-owned. |
| +func statelessPlacementWriteCensusInventory() []censusEntry { |
| + entries := append([]censusEntry(nil), statelessReplicasWriteCensusInventory()...) |
| + for _, next := range []censusEntry{ |
| + // P7: sidecar create keeps the existing app lock and typed writer, pins the admitted name, and refuses counts above one before hostname marks or record creation. This also covers a fleet that shrank after count admission. |
| + {"internal/console/hostsused.go", "Server.createSidecarMarked", "record-writer", "key:CreateSidecarRecord,key:SidecarRecordKey", "228da907d8e1f8cebc691c2eb728f2b8d80251f10f51e9da9673a278392f1faa"}, |
| + // P7: the default-bundle CAS preserves all fields and retains an explicit count after a decrease. It writes only config.json and its existing generation signal, never an instance record. |
| + {"internal/appconfig/copies.go", "SetCopies", "nonrecord", "sel:Put", "9de5a7707d67f23d0b549c4b5b83f9216392564bb3aa5760d84f16881ea11c89"}, |
| + // P7: an optional validation callback inspects the already-read bundle before the unchanged swap-policy CAS. Existing callers retain their path; the console refuses hold at copies>1 under its app lock. |
| + {"internal/appconfig/swap.go", "claimRawSetSwapPolicy", "nonrecord", "sel:Put", "6a9479976d7178cffdb542ccff429ebc95532a681d3ae5fb373f97981a4ba659"}, |
| + // Slice 1a registration adds the person-only copies route beside swap. No record writer, key constructor, or service role is granted. |
| + {"internal/console/authcli.go", "Server.registerCLIRoutes", "key-site", "lit:instances,lit:sidecars", "d5900b8bd600b09a3eee696b402f20afbf12aeb3111a34e26aa08d93b94fdffc"}, |
| + // Approved channel execution now holds the app/name locks across fresh count, target and assignment checks and the existing typed UpdateRecord/ETag write. |
| + {"internal/console/channelmove.go", "Server.executePendingRouteChannel", "record-writer", "key:UpdateRecord", "a9d19169ddf33dcbc5e67ffe2f3e0c81f7b4be98972aa48aef611b4c428fdfd4"}, |
| + // The direct channel door uses the same app/name lock and target checks before its unchanged typed UpdateRecord/ETag write. |
| + {"internal/console/channelmove.go", "Server.handleAPIInstanceChannel", "record-writer", "key:UpdateRecord", "209a9f818aa47beb8f7b35b004c42f5ba0c0e2b16f3cf577310706083e284cf6"}, |
| + // Create still holds the app and hostname locks. It also pins the admitted app name, checks the count and target, and stamps a new replicated binary instance always-on before marks or CreateRecord. It returns that admitted record so the API echoes the persisted setting. |
| + {"internal/console/hostsused.go", "Server.createRecordMarked", "record-writer", "key:CreateRecord,key:RecordKey", "81ddf149ce3adddd5bc189df6d99b2795c61351c39000b2876f6cee90b7562f9"}, |
| + // The lifetime create checks the same admission before any durable allocation. Existing lifetime, maintenance, hostname and CAS checks remain; assignments are not written here. |
| + {"internal/console/lifetimes_create.go", "Server.createRecordWithLifetimeLocked", "key-site", "key:RecordKey", "336652f3dbf4363e55a69363441f52b54f68c8c474bdc458ef242f0c0ecca141"}, |
| + // API/browser update settings hold the app/name locks across count and selected-build validation and the existing typed UpdateRecord/ETag write. |
| + {"internal/console/updatescore.go", "Server.applyUpdates", "record-writer", "key:UpdateRecord", "93a7d457b058237300d38cff142169755951ed625495da4bc76c626941eb12cf"}, |
| + // Install requests hold the app/name locks across fresh record/count/target checks and the unchanged monotonic request-ID UpdateRecord CAS/retry. |
| + {"internal/console/updatescore.go", "Server.requestInstall", "record-writer", "key:UpdateRecord", "200eb79d6b54c08a9fb48f8a1686bb8f36cd6bdd86100def2921f28904878f2e"}, |
| + } { |
| + found := false |
| + for i, old := range entries { |
| + if old.File == next.File && old.Unit == next.Unit { |
| + entries[i] = next |
| + found = true |
| + break |
| + } |
| + } |
| + if !found { |
| + entries = append(entries, next) |
| + } |
| + } |
| + return entries |
| +} |
diff --git a/internal/provision/testdata/plan14-root-reads-chain.tsv b/internal/provision/testdata/plan14-root-reads-chain.tsv| index 52aef395b..d8ae97bc2 100644 |
| --- a/internal/provision/testdata/plan14-root-reads-chain.tsv |
| +++ b/internal/provision/testdata/plan14-root-reads-chain.tsv |
| @@ -58,3 +58,4 @@ plan14-root-reads-rootfs-default-home.tsv 7a0a3da3d6fe7e3c77abb22676db000af2a276 |
| plan14-root-reads-probe-burst-limit.tsv 5f805400717bad7726bd9d62744b8103a40eb5f5823b0ab7c960a5c0965cb3bc |
| plan14-root-reads-region-ha-p1b3a.tsv 5d20b3777026e43906bfba301186bce0ae58daa9d8ad5019879b7833f14dc6ff |
| plan14-root-reads-stateless-replicas-1.tsv df8bf8056d80b9d78edc957fe7f2adbc75885e15f581e58167768346c4e05771 |
| +plan14-root-reads-stateless-replicas-2.tsv df8bf8056d80b9d78edc957fe7f2adbc75885e15f581e58167768346c4e05771 |
diff --git a/internal/provision/testdata/plan14-root-reads-stateless-replicas-2.tsv b/internal/provision/testdata/plan14-root-reads-stateless-replicas-2.tsv| new file mode 100644 |
| index 000000000..ef04e389c |
| --- /dev/null |
| +++ b/internal/provision/testdata/plan14-root-reads-stateless-replicas-2.tsv |
| @@ -0,0 +1,6 @@ |
| +# Census overlay stateless-replicas-2, written by census-propose (#369). census-ruling-stateless-replicas-2, independent approval on #280 is required before the merge; the approval card is docs/superpowers/notes/census-proposal-stateless-replicas-2.md. |
| +# 0 body, 0 sites, 4 envelope: each changed unit re-frozen at its existing disposition with its claim appended. |
| +@coverage . 843fbfa4551775db1d9e9812ed4f6f6b457a9132bfbf455b159f9ffd1a07a8ec |
| +@coverage internal/appconfig 32d5f27628b319917ed88ac39e0b22e25292f8f16ba5ef4e69a57ea35471bf77 |
| +@coverage internal/provision ae4676e47acb446f5377c9d5750de83f24c1eadad225e6ff6622cf8c723fe71e |
| +@coverage internal/replicas 43d5d005572feb08938b489d62459752d510bc6349280bbd75437b66bca16a46 |