carlos / platform Public

fix: keep ship uploads outside the app copies lock

Skip copies locking and config reads for binary and always-on ships.
For hibernating rootfs ships, recheck admission after streaming and hold
only through immutable manifest publication. Release claim-create locks
before private storage provisioning and revalidate the registered body
under a fresh short hold before completion.

Apply P8: resolve accounts only for explicit copies configurations,
return 503 for failed incarnation captures, show the CLI default once,
and exercise a real 1-to-2 stateful refusal in the zero-write test.

Add upload/rollback and storage-walk regressions, restore the 32-request
ship cap, and refresh the census proposal. Independent census review
and recording on #280 remain outstanding.
Co-Authored-By: Codex (gpt-6-astra) <noreply@openai.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev 61581b9f1d82829d72881971b1928f6aed124569 parent 1f3ce3d
14 files changed, +433 −57
  • apps_copies_test.go +10 −0
  • apps_swap.go +1 −1
  • docs/superpowers/notes/census-proposal-stateless-replicas-2.md +1 −1
  • internal/console/apicli.go +0 −10
  • internal/console/apiinstances.go +12 −5
  • internal/console/apiship_rootfs.go +12 −11
  • internal/console/appcopies_test.go +3 −0
  • internal/console/copies_upload_test.go +271 −0
  • internal/console/copiespublication.go +89 −16
  • internal/console/perfwrites_test.go +3 −2
  • internal/console/rootfs.go +12 −6
  • internal/provision/testdata/plan14-root-reads-stateless-replicas-2.tsv +3 −2
  • internal/release/claim_app_writes.go +2 −2
  • internal/release/rootfs_ship.go +14 −1

CI cancelled — superseded by a newer push — run details

Intent

Human

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

Human

<task-notification> <task-id>a70f5ead2fe14658c</task-id> <tool-use-id>toolu_01LHEQvfCw3fD5J2quxCnFqa</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/7c5a7d70-0e28-42b9-896c-5d73b2d2a05d/tasks/a70f5ead2fe14658c.output</output-file> <status>completed</status> <summary>Agent "Review Task 1 (spec + quality)" finished</summary> <note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note> <result>### Spec Compliance ❌ **Issues found.** The gates are functionally complete, but one change breaks the "inert for existing apps" merge gate: - **Ship and claim-create doors now hold the app lock across long bucket work** (Important 1 below). This is a behaviour change on ordinary ship and create paths. P7 allows one config GET under the app lock. It does not allow holding that lock across artifact uploads. Checked and compliant: - **Interfaces match the brief:** `CopiesOf`, `SetCopies`, `handleAPICopies` at `PUT .../copies`, `copiesRefusal(ctx, acct, app, n, target)`, `replicasActive`, and `AtReplicaFloor` from the heartbeat join (`fleetbox.go:3197`). - **P1 types and record field:** - `Assignment` and `Expect` are defined as specified (`internal/replicas/assignment.go`). - `ReplicaAssignment` is additive. - Ordinary writers are fenced by `replicaFieldsFixed` and the lifetime snapshot copies the field. - **P2:** `replicaEligible = AtReplicaFloor &amp;&amp; destinationFor(rootfs)`. The floor check covers draining roster boxes. - **P7:** - The explicit field survives a decrease (`copies.go:686-690`). - An absent field returns after one memoised GET (`copiespublication.go:2380`). - Unsafe targets refuse with C04 above 1, and with C11 at 1 when any record has more than one Box or any Retiring (`appcopies.go:1492-1501`). Unreadable evidence refuses with C06. - **Doors gated:** promote, deploy and retry; rollback (via the guard on the actual CAS target); new canary; pending promote, fast-track and channel; bake waiver; pin, update and install; default-channel and enable; ship and reship; create (lifetime, non-lifetime and claim); sidecar; swap hold. - **Copy:** text is verbatim from the deck (C01-C09, C11-C17), and supersession metadata is recorded in the older decks. - **Within budget:** three effective mutation checks (out of six attempts). Perf deltas are exactly +1 GET on four routes. - **Lock order:** I checked for a deadlock risk and found none. Every site that takes both the app lock and the name lock takes the app lock first: rename `appsettings.go:860→954`, account move `:1644`, region set `appregionset.go:330`, and the new `beginCopiesMutation`. ⚠️ **Cannot verify from the diff:** - Independent census approval on #280 has not been obtained. The record-write census notes in `stateless_placement_census_test.go` are the author's own. - The dev smoke is deferred under P4. Remote CI has not run. - The direct-bucket CLI promote (`cli.go:3004`) still bypasses the console gate. This is an operator path and spans tasks. ### Strengths - **Admission is fenced by incarnation,** captured before uploads and lock waits. Trash, purge and recreate are covered by tests, including same-name reuse. - **Selection is checked on the pointer actually being written** (`statelessSelectionGuard`), not on a pre-read version. - **Tests exercise real API doors** and park at the CAS to witness the lock (`TestCopiesAdmissionSerializesAppMutations`). Per-door read counts are asserted (`TestCopiesPublicationEvidence`). - **The mutation checks forced better assertions:** the floor test now tells floor refusals apart from capacity refusals, and the lock test proves who holds the lock. ### Issues #### Critical (Must Fix) None. #### Important (Should Fix) 1. **The app lock is held across artifact uploads, a behaviour change for every existing app.** Locations: `internal/console/apicli.go:966-976` (binary ship), `internal/console/apiship_rootfs.go:1158-1167` (rootfs ship), `internal/console/apiinstances.go:1002-1009` (claim create). - **What changed:** `beginCopiesMutation` takes `lockApp` and the name lock, and the deferred unlock runs only when the handler returns. So the lock now covers all of `release.Ship` (2-minute timeout), all of `ShipSpooled` (`apiShipRootfsStoreTimeout = 15*time.Minute`), and the claim path's `instanceStoreProvision` storage walk. Before this change, ship took `lockApp` only inside `fixFirstRootfsKindLocked`. - **Why it blocks for that long:** `lockApp` is a plain mutex that ignores context (`applocks.go:62`). - **Who waits behind an upload:** - rollback, including emergency rollback; its 15 s context expires while it waits, so it then fails - promote and channel moves - creates - env and config writes (`apienv.go`, `apiconfig.go:850`) - coordinator renewals (`replicacoordinator.go:70,130` use `withRecordLock`) - the expiry pass - **For binary ships the lock buys nothing:** `copiesPublicationRefusal` always returns nil when `ship &amp;&amp; !target.Hibernate` (`copiespublication.go:2377`). - **Fix:** - Do not take the lock for binary or non-hibernating ships. - For hibernating rootfs ships, take the lock only around a gate recheck plus manifest publication, after the image has been streamed. - In claim create, release the lock before the private-storage walk, or recheck under a short hold before `finishClaimCreate`. #### Minor (Nice to Have) 1. **SR-2-C06 appears on doors that never touched copies.** Locations: `copiespublication.go:2308,2392,2424` and `rootfs.go:3520-3522`. Triggers: - a config read failure with an unsafe target - an `AccountBySqid` SQL error in `statelessSelectionGuard`, which runs before it even checks whether the app is explicit - an incarnation mismatch The text reads "...so the copy count was left unchanged", which is wrong on a promote, rollback or create. A capture SQL error also returns 409 instead of 503 (`copiesStillApp`). Fix: resolve the account only for explicit apps, return 503 when the capture failed, and consider a door-neutral row. 2. **The `--copies` help prints its default twice** (`apps_swap.go:316` plus the C01 text): "...fleet (default 1) (default: 1)". `cliflag.Usage` appends the default for any non-zero value. Fix: drop "(default 1)" from the string (needs copy review), or register the flag with a zero default. 3. **Binary ship pays the config GET before the no-op short-circuit** (`copiespublication.go:2376-2379`). Move the `ship &amp;&amp; !Hibernate` return above `copiesDefault` to save a pointless legacy read. 4. **`TestCopiesApplyToEveryInstance` asserts less than it appears to** (`appcopies_test.go:1794-1807`). - `hostACopies` and `hostBCopies` both come from the same manifest. - The zero-write check runs on a 2→2 edit, which `SetCopies` already turns into a no-op, so it cannot fail. The 409 check does carry the test. Starting from 1→2 would make the write check meaningful. 5. **`apps set --copies 2 --swap hold` applies partially.** The count commits first, then hold is refused (`apps_swap.go:353-366`). This is a documented decision, but the user sees a half-applied command. 6. **The C14/C15 paragraphs sit under `### carlos ship`,** ahead of that section's own description, not under `carlos apps set` (`docs/site/cli.md:449-451`). 7. **Reported test output contains a repeated log line:** `console: CARLOS_SECRETS_PUBKEY is unset...`. It is likely pre-existing fixture noise; confirm, or quiet it. ### Assessment **Task quality:** Needs fixes **Reasoning:** The copy gates are thorough, well-tested and match P1/P2/P3/P7. But the ship and claim-create doors now hold a mutex that ignores context for up to 15 minutes. On every existing app, that blocks rollback, config writes and coordinator renewals behind an upload. This breaks the "inert for existing apps" merge gate for a lock that, on binary ships, protects nothing. I reviewed the whole diff in passes and needed no extra reads of changed files. Outside the diff I made one focused read per named risk: lock semantics, lock-order holders, the claim-create flow, and the rootfs ship timeout.</result> <usage><subagent_tokens>206889</subagent_tokens><tool_uses>41</tool_uses><duration_ms>477931</duration_ms></usage> </task-notification>

Human

<task-notification> <task-id>b58kimbv2</task-id> <tool-use-id>toolu_01Kv8CbWKZojRgb2X1Nb1y8s</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/7c5a7d70-0e28-42b9-896c-5d73b2d2a05d/tasks/b58kimbv2.output</output-file> <status>completed</status> <summary>Background command "Wait for fix round 1" completed (exit code 0)</summary> </task-notification>

Attributed to this commit: 14.6 g CO₂e (1,707,506 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/apps_copies_test.go b/apps_copies_test.go
index b2399b5b9..c472f97d9 100644
--- a/apps_copies_test.go
+++ b/apps_copies_test.go
@@ -57,3 +57,13 @@ func TestCopiesNeverFallsBackToBucket(t *testing.T) {
t.Fatalf("direct mode: %v %s", err, out)
}
}
+
+func TestCopiesHelpHasOneDefault(t *testing.T) {
+ cmd := exec.Command(sharedCarlos(t), "apps", "set", "--help")
+ cmd.Dir = t.TempDir()
+ cmd.Env = carlosTestEnv(t)
+ out, _ := cmd.CombinedOutput()
+ if !strings.Contains(string(out), appsSetFlagCopies) || strings.Contains(string(out), "(default 1) (default: 1)") {
+ t.Fatalf("copies help default: %s", out)
+ }
+}
diff --git a/apps_swap.go b/apps_swap.go
index 1a96bd75d..d74e31953 100644
--- a/apps_swap.go
+++ b/apps_swap.go
@@ -164,7 +164,7 @@ func runAppsSet(args []string) {
lead, args := leadingArg(args)
fs := flag.NewFlagSet("apps set", flag.ExitOnError)
appF := appFlag(fs, appsSetFlagApp)
- copies := fs.Int("copies", 1, appsSetFlagCopies)
+ copies := fs.Int("copies", 0, appsSetFlagCopies)
messageFlags := addMutationMessageFlags(fs)
swap := fs.String("swap", "", appsSetFlagSwap)
concurrency := fs.Int("swap-concurrency", 0, appsSetFlagConcurrency)
diff --git a/docs/superpowers/notes/census-proposal-stateless-replicas-2.md b/docs/superpowers/notes/census-proposal-stateless-replicas-2.md
index 6ddeae6d7..9bc46840b 100644
--- a/docs/superpowers/notes/census-proposal-stateless-replicas-2.md
+++ b/docs/superpowers/notes/census-proposal-stateless-replicas-2.md
@@ -4,7 +4,7 @@ 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`.
+Envelopes re-pinned: `.`, `internal/appconfig`, `internal/provision`, `internal/release`, `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.
diff --git a/internal/console/apicli.go b/internal/console/apicli.go
index 67ecb1207..943f74daf 100644
--- a/internal/console/apicli.go
+++ b/internal/console/apicli.go
@@ -2476,17 +2476,7 @@ 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 afe0a4632..90b125f43 100644
--- a/internal/console/apiinstances.go
+++ b/internal/console/apiinstances.go
@@ -2368,15 +2368,19 @@ func (s *Server) handleAPIInstanceCreate(w http.ResponseWriter, r *http.Request)
// write, the environment binding below, so a create refused for want of
// room changes nothing. beginClaimCreate keeps this choice.
createContext := r.Context()
+ var createUnlock func()
+ defer func() {
+ if createUnlock != nil {
+ createUnlock()
+ }
+ }()
if s.cfg.HostClaim {
- var unlock func()
var ref *doorRefusal
- createContext, unlock, ref = s.beginCopiesMutation(createContext, acct, app)
+ createContext, createUnlock, 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) {
@@ -2406,7 +2410,10 @@ func (s *Server) handleAPIInstanceCreate(w http.ResponseWriter, r *http.Request)
return
}
defer claimRequest.Close()
- createContext = claimRequest.Context
+ createUnlock()
+ createUnlock = nil
+ createContext = context.WithValue(claimRequest.Context, copiesHeldKey{}, copiesHeld{})
+ claimRequest.Context = createContext
}
if m.PrivateStorage {
// r.Context(), not ctx: the walk takes storeGrantTimeout, which is
@@ -2436,7 +2443,7 @@ func (s *Server) handleAPIInstanceCreate(w http.ResponseWriter, r *http.Request)
var recordWriteErr error
switch {
case claimRequest != nil:
- if !s.finishClaimCreate(w, claimRequest) {
+ if !s.finishCopiesClaimCreate(w, claimRequest, acct, app) {
return
}
case lifetimesUnit(ctx):
diff --git a/internal/console/apiship_rootfs.go b/internal/console/apiship_rootfs.go
index 608916e1a..866426324 100644
--- a/internal/console/apiship_rootfs.go
+++ b/internal/console/apiship_rootfs.go
@@ -259,16 +259,6 @@ 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
@@ -293,6 +283,14 @@ func (s *Server) shipRootfsParts(w http.ResponseWriter, r *http.Request, mr *mul
if refuseAssetsConflict(w, existing.Assets, meta.Assets, ver) {
return
}
+ // A reship publishes no manifest. Check a hibernating release under
+ // a short hold, then release before any assets backfill.
+ _, done, err := s.copiesShipManifestGate(acct)(ctx, existing)
+ if err != nil {
+ writeCopiesRefusal(w, err)
+ return
+ }
+ done()
// The binary path's re-ship short-circuit: the stored folders are
// echoed and the backfill runs again, so a re-ship finishes one that
// failed part way.
@@ -310,7 +308,10 @@ func (s *Server) shipRootfsParts(w http.ResponseWriter, r *http.Request, mr *mul
jsonError(w, ref.Status, ref.Msg)
return
}
- if err := release.ShipSpooled(ctx, s.cfg.Releases, acct.Sqid, m, map[string]string{release.RootfsArtifactKey: spool}); err != nil {
+ if err := release.ShipSpooled(ctx, s.cfg.Releases, acct.Sqid, m, map[string]string{release.RootfsArtifactKey: spool}, s.copiesShipManifestGate(acct)); err != nil {
+ if writeCopiesRefusal(w, err) {
+ return
+ }
log.Printf("console: api ship %s %s (rootfs): %v", app, ver, err)
if shipKindRefusedAtPublication(w, err) {
return
diff --git a/internal/console/appcopies_test.go b/internal/console/appcopies_test.go
index d28e2605a..2b0745b70 100644
--- a/internal/console/appcopies_test.go
+++ b/internal/console/appcopies_test.go
@@ -104,6 +104,9 @@ func TestCopiesApplyToEveryInstance(t *testing.T) {
t.Fatal(err)
}
hostACopies, hostBCopies := appconfig.CopiesOf(m), appconfig.CopiesOf(m)
+ if code, out := copiesPut(t, fx, token, `{"copies":1}`); code != 200 {
+ t.Fatalf("prepare increase: %d %s", code, out)
+ }
counter := &copiesWriteCounter{Store: fx.rel, key: appconfig.Key(fx.sqid, "shop")}
fx.srv.cfg.Releases = counter
before, etag, _ := fx.rel.Get(context.Background(), appconfig.Key(fx.sqid, "shop"))
diff --git a/internal/console/copies_upload_test.go b/internal/console/copies_upload_test.go
new file mode 100644
index 000000000..33a6dac0b
--- /dev/null
+++ b/internal/console/copies_upload_test.go
@@ -0,0 +1,271 @@
+package console
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/appconfig"
+ "github.com/carlosframework/platform/internal/hostops"
+ "github.com/carlosframework/platform/internal/objstore"
+ "github.com/carlosframework/platform/internal/provision"
+ "github.com/carlosframework/platform/internal/release"
+)
+
+type copiesUploadStore struct {
+ *copiesEvidenceStore
+ key string
+ entered, resume chan struct{}
+ once sync.Once
+}
+
+func (s *copiesUploadStore) pause(ctx context.Context, key string) {
+ if key == s.key {
+ s.once.Do(func() {
+ close(s.entered)
+ select {
+ case <-s.resume:
+ case <-ctx.Done():
+ }
+ })
+ }
+}
+func (s *copiesUploadStore) Put(ctx context.Context, key string, b []byte, etag string) (string, error) {
+ s.pause(ctx, key)
+ return s.Store.Put(ctx, key, b, etag)
+}
+func (s *copiesUploadStore) PutFrom(ctx context.Context, key string, b io.ReadSeeker, n int64, etag string) (string, error) {
+ s.pause(ctx, key)
+ return release.PutObjectFrom(ctx, s.Store, key, b, n, etag)
+}
+func copiesUploadParts(t *testing.T, version string, rootfs, hibernate bool) []shipPart {
+ t.Helper()
+ if rootfs {
+ img := []byte("rootfs test image")
+ return []shipPart{rootfsMeta(t, version, len(img), hibernate), {name: "rootfs-linux-arm64", body: img}}
+ }
+ return []shipPart{metaPart(t, version, "binary"), {name: "linux-amd64", body: tinyProgramForConsole(t, "example.com/shop")}}
+}
+func TestCopiesShipUploadDoesNotBlockRollback(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ rootfs, hibernate bool
+ }{
+ {"binary", false, false}, {"rootfs always-on", true, false}, {"rootfs hibernating", true, true},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ f := rootfsShipFixture(t)
+ fx := f.fx
+ for _, v := range []string{"v1", "v2"} {
+ if code, out := postShip(t, f.url("shop"), f.token, copiesUploadParts(t, v, tc.rootfs, tc.hibernate)); code != 201 {
+ t.Fatalf("setup: %d %v", code, out)
+ }
+ if err := release.Promote(context.Background(), fx.rel, fx.priv, fx.sqid, "shop", "canary/x", v); err != nil {
+ t.Fatal(err)
+ }
+ }
+ file := "linux-amd64"
+ if tc.rootfs {
+ file = release.RootfsArtifactFile
+ }
+ st := &copiesUploadStore{copiesEvidenceStore: &copiesEvidenceStore{Store: fx.rel, gets: map[string]int{}}, key: release.ArtifactKey(fx.sqid, "shop", "v3", file), entered: make(chan struct{}), resume: make(chan struct{})}
+ fx.srv.cfg.Releases = st
+ var resume sync.Once
+ defer resume.Do(func() { close(st.resume) })
+ parts := copiesUploadParts(t, "v3", tc.rootfs, tc.hibernate)
+ shipped := make(chan int, 1)
+ go func() { c, _ := postShip(t, f.url("shop"), f.token, parts); shipped <- c }()
+ select {
+ case <-st.entered:
+ case <-time.After(5 * time.Second):
+ t.Fatal("ship never began artifact upload")
+ }
+ cfgKey := appconfig.Key(fx.sqid, "shop")
+ st.mu.Lock()
+ earlyReads := st.gets[cfgKey]
+ st.mu.Unlock()
+ if earlyReads != 0 {
+ t.Errorf("ship read copies config before upload finished: %d", earlyReads)
+ }
+ rolled := make(chan int, 1)
+ go func() {
+ c, _ := copiesCall(t, fx, f.token, copiesDoor{method: "POST", path: "/rollback", body: `{"channel":"canary/x"}`})
+ rolled <- c
+ }()
+ early := false
+ select {
+ case c := <-rolled:
+ early = true
+ if c != 200 {
+ t.Errorf("rollback: %d", c)
+ }
+ case <-time.After(3 * time.Second):
+ t.Error("rollback blocked behind artifact upload")
+ }
+ resume.Do(func() { close(st.resume) })
+ if !early {
+ if c := <-rolled; c != 200 {
+ t.Errorf("delayed rollback: %d", c)
+ }
+ }
+ if c := <-shipped; c != 201 {
+ t.Fatalf("ship: %d", c)
+ }
+ st.mu.Lock()
+ reads := st.gets[cfgKey]
+ st.mu.Unlock()
+ want := 1 // rollback only; a hibernating ship adds its publication read.
+ if tc.hibernate {
+ want++
+ }
+ if reads != want {
+ t.Errorf("config GETs=%d, want %d", reads, want)
+ }
+ })
+ }
+}
+
+func TestCopiesHibernatingShipRechecksAfterUpload(t *testing.T) {
+ f := rootfsShipFixture(t)
+ fx := f.fx
+ st := &copiesUploadStore{copiesEvidenceStore: &copiesEvidenceStore{Store: fx.rel, gets: map[string]int{}}, key: release.ArtifactKey(fx.sqid, "shop", "v1", release.RootfsArtifactFile), entered: make(chan struct{}), resume: make(chan struct{})}
+ fx.srv.cfg.Releases = st
+ var resume sync.Once
+ defer resume.Do(func() { close(st.resume) })
+ parts := copiesUploadParts(t, "v1", true, true)
+ done := make(chan int, 1)
+ go func() { c, _ := postShip(t, f.url("shop"), f.token, parts); done <- c }()
+ select {
+ case <-st.entered:
+ case <-time.After(5 * time.Second):
+ t.Fatal("no artifact upload")
+ }
+ // Fixture a count committed during the upload; admission must not reuse
+ // evidence from before those bytes streamed.
+ if _, err := appconfig.SetCopies(context.Background(), fx.rel, fx.sqid, "shop", 2); err != nil {
+ t.Fatal(err)
+ }
+ resume.Do(func() { close(st.resume) })
+ if c := <-done; c != 409 {
+ t.Fatalf("hibernating manifest published after count increased: %d", c)
+ }
+ if _, _, err := fx.rel.Get(context.Background(), release.ManifestKey(fx.sqid, "shop", "v1")); !errors.Is(err, os.ErrNotExist) {
+ t.Fatalf("manifest exists: %v", err)
+ }
+}
+
+func TestCopiesLegacySelectionDoesNotResolveAccount(t *testing.T) {
+ // A nil SQL store makes an accidental AccountBySqid observable. A legacy
+ // absent config/manifest needs no account lookup at this callback.
+ s := &Server{cfg: Config{Releases: release.NewDirStore(t.TempDir())}}
+ if err := s.statelessSelectionGuard(withWriteMemo(context.Background()), "bab", "shop", "edge")("v1"); err != nil {
+ t.Fatal(err)
+ }
+}
+
+func TestCopiesCaptureFailureIsUnavailable(t *testing.T) {
+ fx, _ := copiesWorld(t)
+ acct, _ := fx.st.AccountBySqid(fx.sqid)
+ ctx, cancel := context.WithCancel(context.Background())
+ cancel()
+ r := httptest.NewRequest("POST", "/", nil).WithContext(ctx)
+ fx.srv.captureCopiesAdmission(r, acct, "shop")
+ _, unlock, ref := fx.srv.beginCopiesMutation(context.WithoutCancel(r.Context()), acct, "shop")
+ defer unlock()
+ if ref == nil || ref.Status != 503 || ref.Msg != copiesUnread {
+ t.Fatalf("capture SQL failure: %+v, want 503 C06", ref)
+ }
+}
+
+type copiesSlowProvisioner struct {
+ objstore.Provisioner
+ entered, resume chan struct{}
+ once sync.Once
+}
+
+func (p *copiesSlowProvisioner) EnsureBucket(ctx context.Context, name string) (string, error) {
+ p.once.Do(func() {
+ close(p.entered)
+ select {
+ case <-p.resume:
+ case <-ctx.Done():
+ }
+ })
+ return p.Provisioner.EnsureBucket(ctx, name)
+}
+func TestCopiesClaimStorageWalkDoesNotHoldAppLock(t *testing.T) {
+ cx := newClaimCase(t)
+ approveStoreAccount(t, cx.consoleFixture, "operator@keymail.dev")
+ m := titoManifest()
+ m.PrivateStorage = true
+ enableInstances(t, cx.consoleFixture, "titogo", m)
+ slow := &copiesSlowProvisioner{Provisioner: cx.srv.cfg.StoreProvisioner, entered: make(chan struct{}), resume: make(chan struct{})}
+ cx.srv.cfg.StoreProvisioner = slow
+ var resume sync.Once
+ defer resume.Do(func() { close(slow.resume) })
+ done := make(chan int, 1)
+ go func() {
+ done <- cx.api(t, "POST", "/api/cli/apps/bab/titogo/instances", `{"host":"new.go.tito.io","region":"ie","channel":"edge"}`)
+ }()
+ select {
+ case <-slow.entered:
+ case code := <-done:
+ t.Fatalf("create did not walk private storage: %d", code)
+ case <-time.After(10 * time.Second):
+ t.Fatal("no private storage walk")
+ }
+ if cx.srv.appLocks.held("bab/titogo") {
+ t.Error("private storage walk holds the app copies lock")
+ }
+ lockDone := make(chan struct{})
+ go func() { _ = cx.srv.withRecordLock("bab", "titogo", func() error { close(lockDone); return nil }) }()
+ select {
+ case <-lockDone:
+ case <-time.After(3 * time.Second):
+ t.Error("record writer blocked behind private storage walk")
+ }
+ resume.Do(func() { close(slow.resume) })
+ if code := <-done; code != 201 && code != 202 {
+ t.Fatalf("create: %d", code)
+ }
+}
+
+func TestCopiesClaimFinishRechecksAfterStorage(t *testing.T) {
+ fx, _ := copiesWorld(t)
+ acct, _ := fx.st.AccountBySqid(fx.sqid)
+ r := httptest.NewRequest("POST", "/", nil)
+ fx.srv.captureCopiesAdmission(r, acct, "shop")
+ held, unlock, ref := fx.srv.beginCopiesMutation(r.Context(), acct, "shop")
+ if ref != nil {
+ t.Fatal(ref)
+ }
+ if _, err := fx.srv.copiesDefault(held, fx.sqid, "shop"); err != nil {
+ unlock()
+ t.Fatal(err)
+ }
+ unlock()
+ unlocked := context.WithValue(held, copiesHeldKey{}, copiesHeld{})
+ rec := provision.Record{Schema: 1, Account: fx.sqid, App: "shop", Host: "new.example.com", Slug: "new", Region: "fleet/pi", Channel: "edge"}
+ body, _ := json.Marshal(rec)
+ q := &claimCreateRequest{Context: unlocked, Record: hostops.Record{Body: body}}
+ // The captured default memo is now stale. No authority implementation is
+ // installed: a missed refusal would reach RecordEffects and panic.
+ if _, err := appconfig.SetCopies(context.Background(), fx.rel, fx.sqid, "shop", 2); err != nil {
+ t.Fatal(err)
+ }
+ w := httptest.NewRecorder()
+ if fx.srv.finishCopiesClaimCreate(w, q, acct, "shop") || w.Code != http.StatusConflict || !strings.Contains(w.Body.String(), copiesRelease) {
+ t.Fatalf("finish reused admission from before storage: %d %s", w.Code, w.Body.String())
+ }
+ if fx.srv.appLocks.held(fx.sqid + "/shop") {
+ t.Fatal("finish leaked app lock")
+ }
+}
diff --git a/internal/console/copiespublication.go b/internal/console/copiespublication.go
index 7dacc27fc..c4143966a 100644
--- a/internal/console/copiespublication.go
+++ b/internal/console/copiespublication.go
@@ -20,6 +20,7 @@ type copiesAdmission struct {
app string
incarnation AppIncarnation
valid bool
+ captureErr error
}
type copiesHeldKey struct{}
@@ -37,7 +38,7 @@ func (s *Server) captureCopiesAdmission(r *http.Request, acct *Account, app stri
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}))
+ *r = *r.WithContext(context.WithValue(r.Context(), copiesAdmissionKey{}, copiesAdmission{acct.ID, app, inc, ok, err}))
}
func copiesUnavailable() *doorRefusal {
@@ -49,6 +50,9 @@ func (s *Server) copiesStillApp(ctx context.Context, acct *Account, app string)
if !present {
return nil
} // Internal callers capture at their mutation boundary.
+ if admitted.captureErr != nil {
+ return copiesUnavailable()
+ }
inc, ok, err := s.store.AppIncarnationContext(ctx, acct.ID, app)
if err != nil {
return copiesUnavailable()
@@ -67,7 +71,7 @@ func (s *Server) beginCopiesMutation(ctx context.Context, acct *Account, app str
}
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})
+ ctx = context.WithValue(ctx, copiesAdmissionKey{}, copiesAdmission{acct.ID, app, inc, live, err})
}
unlockApp := s.lockApp(acct.Sqid, app)
unlockName := s.store.lockAppNames(appNameKey{acct.ID, app})
@@ -122,10 +126,10 @@ func safeCopiesTarget(m *release.Manifest) bool { return m != nil && m.Stateless
// 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
}
+ cfg, err := s.copiesDefault(ctx, acct.Sqid, app)
if err == nil && !cfg.explicit {
return nil
}
@@ -202,15 +206,26 @@ func (s *Server) copiesRecordRefusal(ctx context.Context, acct *Account, rec pro
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 {
+ admitted, ok := ctx.Value(copiesAdmissionKey{}).(copiesAdmission)
+ if !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() {
+ if err == nil && !cfg.explicit {
+ if ref := s.copiesStillApp(ctx, &Account{ID: admitted.account, Sqid: rec.Account}, rec.App); ref != nil {
+ return &statelessSelectionError{ref}
+ }
+ return nil
+ }
+ configErr := err
+ acct := &Account{ID: admitted.account, Sqid: rec.Account}
+ if configErr == nil {
+ acct, err = s.store.AccountBySqid(rec.Account)
+ if err != nil || acct == nil {
+ return &statelessSelectionError{copiesUnavailable()}
+ }
+ }
+ if configErr == 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 {
@@ -260,9 +275,17 @@ func (s *Server) copiesChannelRefusal(ctx context.Context, acct *Account, app, c
// 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 {
+ admitted, ok := ctx.Value(copiesAdmissionKey{}).(copiesAdmission)
+ if !ok {
return nil
}
+ cfg, err := s.copiesDefault(ctx, account, app)
+ if err != nil {
+ return copiesUnavailable()
+ }
+ if !cfg.explicit {
+ return s.copiesStillApp(ctx, &Account{ID: admitted.account, Sqid: account}, app)
+ }
acct, err := s.store.AccountBySqid(account)
if err != nil || acct == nil {
return copiesUnavailable()
@@ -270,12 +293,62 @@ func (s *Server) copiesSidecarRefusal(ctx context.Context, account, app string)
if ref := s.copiesStillApp(ctx, acct, app); ref != nil {
return ref
}
- cfg, err := s.copiesDefault(ctx, account, app)
- if err != nil {
- return copiesUnavailable()
+ return s.copiesRefusal(ctx, acct, app, appconfig.CopiesOf(&cfg.manifest), &release.Manifest{Stateless: true, Kind: "sidecar"})
+}
+
+func writeCopiesRefusal(w http.ResponseWriter, err error) bool {
+ var selection *statelessSelectionError
+ if !errors.As(err, &selection) {
+ return false
}
- if !cfg.explicit {
- return nil
+ jsonError(w, selection.ref.Status, selection.ref.Msg)
+ return true
+}
+
+// No lock or config read for a non-hibernating artifact. The gate for a
+// hibernating one runs after streaming and holds only validation + manifest.
+func (s *Server) copiesShipManifestGate(acct *Account) release.ManifestGate {
+ return func(ctx context.Context, target *release.Manifest) (context.Context, func(), error) {
+ if !target.Hibernate {
+ return ctx, func() {}, nil
+ }
+ short, cancel := context.WithTimeout(withWriteMemo(ctx), configStoreTimeout)
+ held, unlock, ref := s.beginCopiesMutation(short, acct, target.App)
+ if ref == nil {
+ ref = s.copiesPublicationRefusal(held, acct, target.App, target, "", true)
+ }
+ if ref != nil {
+ unlock()
+ cancel()
+ return ctx, func() {}, &statelessSelectionError{ref}
+ }
+ return held, func() { unlock(); cancel() }, nil
}
- return s.copiesRefusal(ctx, acct, app, appconfig.CopiesOf(&cfg.manifest), &release.Manifest{Stateless: true, Kind: "sidecar"})
+}
+
+// The storage walk runs without an app/name lock or a live held-lock token.
+// Re-read the count in a new memo and validate the already-prepared record;
+// do not change its registered body while completing the claim.
+func (s *Server) finishCopiesClaimCreate(w http.ResponseWriter, q *claimCreateRequest, acct *Account, app string) bool {
+ ctx, cancel := context.WithTimeout(withWriteMemo(q.Context), instanceStoreTimeout)
+ defer cancel()
+ ctx, unlock, ref := s.beginCopiesMutation(ctx, acct, app)
+ if ref != nil {
+ jsonError(w, ref.Status, ref.Msg)
+ return false
+ }
+ defer unlock()
+ var rec provision.Record
+ if err := json.Unmarshal(q.Record.Body, &rec); err != nil {
+ jsonError(w, http.StatusServiceUnavailable, copiesUnread)
+ return false
+ }
+ if ref := s.copiesRecordRefusal(ctx, acct, rec, true); ref != nil {
+ jsonError(w, ref.Status, ref.Msg)
+ return false
+ }
+ previous := q.Context
+ q.Context = ctx
+ defer func() { q.Context = previous }()
+ return s.finishClaimCreate(w, q)
}
diff --git a/internal/console/perfwrites_test.go b/internal/console/perfwrites_test.go
index e3e136cf3..2d8fb65a5 100644
--- a/internal/console/perfwrites_test.go
+++ b/internal/console/perfwrites_test.go
@@ -327,11 +327,12 @@ type perfWriteLimit struct {
// 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
+// one for instance create, promote and instances-manifest put; other
// request caps and every timing budget remain unchanged.
+// P8: binary/non-hibernating ships again read no copies config.
func perfWriteLimits() map[string]perfWriteLimit {
return map[string]perfWriteLimit{
- "ship": {Calls: 33, Budget: perfWriteBudget},
+ "ship": {Calls: 32, 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: 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"},
diff --git a/internal/console/rootfs.go b/internal/console/rootfs.go
index 00321efb3..1f720072b 100644
--- a/internal/console/rootfs.go
+++ b/internal/console/rootfs.go
@@ -90,12 +90,18 @@ 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}
+ cfg, err := s.copiesDefault(ctx, acct, app)
+ if err != nil || cfg.explicit {
+ account := &Account{Sqid: acct}
+ if err == nil {
+ 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/provision/testdata/plan14-root-reads-stateless-replicas-2.tsv b/internal/provision/testdata/plan14-root-reads-stateless-replicas-2.tsv
index ef04e389c..9d9f5eb76 100644
--- a/internal/provision/testdata/plan14-root-reads-stateless-replicas-2.tsv
+++ b/internal/provision/testdata/plan14-root-reads-stateless-replicas-2.tsv
@@ -1,6 +1,7 @@
# 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
+# 0 body, 0 sites, 5 envelope: each changed unit re-frozen at its existing disposition with its claim appended.
+@coverage . 9857cb346182ee701b2dff653cee0c4b7ed36b038975d3eeaea75cc85da938b7
@coverage internal/appconfig 32d5f27628b319917ed88ac39e0b22e25292f8f16ba5ef4e69a57ea35471bf77
@coverage internal/provision ae4676e47acb446f5377c9d5750de83f24c1eadad225e6ff6622cf8c723fe71e
+@coverage internal/release 6c7784eb02f9c2b68045266dabf5a79fb656bcb11a06427787d74ca8f3f96dd6
@coverage internal/replicas 43d5d005572feb08938b489d62459752d510bc6349280bbd75437b66bca16a46
diff --git a/internal/release/claim_app_writes.go b/internal/release/claim_app_writes.go
index 6a560f8d5..aea9cb7fb 100644
--- a/internal/release/claim_app_writes.go
+++ b/internal/release/claim_app_writes.go
@@ -23,9 +23,9 @@ func Ship(ctx context.Context, s Store, acct string, m Manifest, files map[strin
// ShipSpooled is claimRawShipSpooled under the app mutation of the
// manifest's app: Ship for artifacts on disk (paths maps each artifact key to
// a local file), each streamed into the bucket rather than held in memory.
-func ShipSpooled(ctx context.Context, s Store, acct string, m Manifest, paths map[string]string) error {
+func ShipSpooled(ctx context.Context, s Store, acct string, m Manifest, paths map[string]string, gates ...ManifestGate) error {
return WithAppMutation(ctx, s, acct, m.App, "release.ShipSpooled", func(ctx context.Context) error {
- return claimRawShipSpooled(ctx, s, acct, m, paths)
+ return claimRawShipSpooled(ctx, s, acct, m, paths, gates...)
})
}
diff --git a/internal/release/rootfs_ship.go b/internal/release/rootfs_ship.go
index f2e7d5f46..53b4a8b19 100644
--- a/internal/release/rootfs_ship.go
+++ b/internal/release/rootfs_ship.go
@@ -363,12 +363,17 @@ func IsRootfsArtifactKey(key string) bool {
ValidAccount(p[1]) && ValidApp(p[2]) && ValidVersion(p[4])
}
+// ManifestGate admits the small manifest publication after artifact upload.
+// Its returned context bounds publication and its release function runs after
+// the immutable manifest write. Callers without a gate retain the old path.
+type ManifestGate func(context.Context, *Manifest) (context.Context, func(), error)
+
// claimRawShipSpooled is claimRawShip over files on disk, for an image too
// large to hold in memory: paths maps each artifact key to a local file.
// The same checks, then each file hashed and sized by streaming it once,
// the kind established before the first write, each artifact streamed
// create-only, and the manifest last.
-func claimRawShipSpooled(ctx context.Context, s Store, acct string, m Manifest, paths map[string]string) error {
+func claimRawShipSpooled(ctx context.Context, s Store, acct string, m Manifest, paths map[string]string, gates ...ManifestGate) error {
if !ValidAccount(acct) {
return fmt.Errorf("ship: invalid account %q", acct)
}
@@ -415,6 +420,14 @@ func claimRawShipSpooled(ctx context.Context, s Store, acct string, m Manifest,
if err != nil {
return err
}
+ for _, gate := range gates {
+ var done func()
+ ctx, done, err = gate(ctx, &m)
+ if err != nil {
+ return err
+ }
+ defer done()
+ }
if err := putImmutableManifest(ctx, s, acct, &m, raw); err != nil {
return fmt.Errorf("ship: manifest: %w", err)
}