carlos / platform Public

fix: preserve copies admission for ordinary claim creates

Apply P9 by keeping the initial app lock and memo through non-private
claim completion. Only private-storage creates release that hold for
the storage walk and re-read admission afterward.

Measure the claim-enabled create path in the write-route performance
gate, including exactly one default-config GET and a published record.
Keep existing budgets and add the measured claim protocol budget.

Start the hibernating manifest timeout after lock acquisition. Check the
copies help default exactly once and prove the duplicate-default check
fails when the flag's old nonzero default is restored.
Co-Authored-By: Codex (gpt-6-astra) <noreply@openai.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev caf48a071e1c5d268e3e4dbb593d1f0b9e17ab98 parent 61581b9
5 files changed, +156 −11
  • apps_copies_test.go +8 −2
  • internal/console/apiinstances.go +14 −5
  • internal/console/copies_upload_test.go +54 −0
  • internal/console/copiespublication.go +7 −4
  • internal/console/perfwrites_test.go +73 −0

CI failed — run details

Intent

Human

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

Human

<task-notification> <task-id>ad7c64d049e96bac7</task-id> <tool-use-id>toolu_018SNvjPDJEgbaHySsqgparM</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/7c5a7d70-0e28-42b9-896c-5d73b2d2a05d/tasks/ad7c64d049e96bac7.output</output-file> <status>completed</status> <summary>Agent "Re-review Task 1 fix round 1" 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>### Finding Verdicts - **Important 1: the app lock was held across artifact uploads.** ADDRESSED. - **Binary ship:** `beginCopiesMutation` and `copiesPublicationRefusal` are removed (diff of `internal/console/apicli.go` near line 2478). The binary path refuses hibernate meta at `apicli.go:2281`, so no hibernating binary can skip the gate. - **Always-on rootfs ship:** the lock is removed (`apiship_rootfs.go` near line 262). `copiesShipManifestGate` returns straight away when `!target.Hibernate` (`copiespublication.go`, new function after `writeCopiesRefusal`). - **Hibernating rootfs ship:** the gate now runs inside `claimRawShipSpooled`, after every `putImmutableFrom` and just before `putImmutableManifest` (`internal/release/rootfs_ship.go:427-437`). The gate takes the app lock and then the name lock through `beginCopiesMutation`, rechecks the incarnation and count under a fresh memo, and the deferred `done()` releases the hold after the manifest write, on success or failure. - **Hibernating reship:** checks under a short hold and calls `done()` before `mintShippedAssets` (`apiship_rootfs.go` near line 269). - **Claim create:** `createUnlock()` runs after `beginClaimCreate` and before `instanceStoreProvision`. The held token is overwritten with a zero `copiesHeld{}`. `finishCopiesClaimCreate` takes a fresh hold, re-reads the count and validates the registered record body (`apiinstances.go:2403-2410`). - **Tests:** `TestCopiesShipUploadDoesNotBlockRollback` covers all three ship kinds, `TestCopiesHibernatingShipRechecksAfterUpload` covers a count raised during upload, and `TestCopiesClaimStorageWalkDoesNotHoldAppLock` plus `TestCopiesClaimFinishRechecksAfterStorage` cover the claim path. - **Questions you asked me to check:** - **Can a copies&gt;1 edit slip in during a hibernating upload?** No. The recheck and the manifest write share one hold, and a copies edit takes the same app lock. An edit committed during the upload is seen by the gate and refused (tested). An edit committed after the manifest write finds an unselected release, and promote is still gated. - **Lock order:** app lock before name lock everywhere. - **Released locks on every return path:** the gate unlocks and cancels on refusal and defers both on success. `beginCopiesMutation` unlocks itself before it returns a refusal. `finishCopiesClaimCreate` defers its unlock. `createUnlock` is set to nil after its explicit call, so the deferred guard cannot unlock twice. Every early return before that call goes through the deferred guard. - **m1: the account was resolved before checking whether copies is explicit, and a capture SQL failure returned 409.** ADDRESSED. - `statelessSelectionGuard` calls `AccountBySqid` only when the config read succeeded and copies is explicit (`rootfs.go:913-921`). `copiesCreateCheck` and `copiesSidecarRefusal` now read the config first. - `captureErr` is kept on the admission, and `copiesStillApp` returns 503 C06 when it is set (`copiespublication.go:658-660`). `TestCopiesCaptureFailureIsUnavailable` and `TestCopiesLegacySelectionDoesNotResolveAccount` cover this. No new strings. - **m2: the `--copies` help printed the default twice.** ADDRESSED. The flag default is now 0 (`apps_swap.go:167`), explicit values still go through `flagWasSet` (lines 212 and 223), and the C01 text is unchanged (`apps_copies.go:9`). The new test is weak, though; see Minor below. - **m3: binary and non-hibernating ships paid the config GET.** ADDRESSED. The no-op return now comes before `copiesDefault` (`copiespublication.go:703-706`), and the ship request cap goes from 33 back to 32 (`perfwrites_test.go:880`). - **m4: the zero-write check started from a 2-&gt;2 no-op edit.** ADDRESSED. The test now decreases to 1 before installing the counter, so the stateful 1-&gt;2 attempt can fail (`appcopies_test.go:322-324`). ### New Breakage in the Fix Diff - **Important: claim create now does two default-config GETs for every legacy app, against merge gate P7.** P7 allows at most one per create mutation. - `finishCopiesClaimCreate` always wraps the context in a fresh `withWriteMemo`, takes a new hold, and calls `copiesRecordRefusal`. That function calls `copiesDefault` again, plus another SQL incarnation read (`copiespublication.go`, `finishCopiesClaimCreate`; `apiinstances.go:2409-2410`). - This runs on every `HostClaim` create, not only when `m.PrivateStorage` triggers the slow walk. The report's door-cost table says so openly ("One during initial admission and one fresh read before completion"). - The perf cap for instance create stayed at 53, which suggests the claim path is not measured there; I did not confirm that. - Fix: - When `!m.PrivateStorage`, keep the single hold through `finishClaimCreate`. Nothing slow sits between the two holds, so there is no reason to release. - For the private-storage claim path, the second read is defensible for correctness but breaks P7 as written. It needs an explicit controller ruling, or a design that keeps one GET (for example, reuse the first read's ETag as a conditional read). - **Minor: `TestCopiesHelpHasOneDefault` cannot fail.** Go's flag package prints ` (default 1)` with no colon, so the forbidden string `"(default 1) (default: 1)"` never appeared in the old output either (`apps_copies_test.go:45`). It should assert that `"(default 1)"` appears exactly once. - **Minor: the gate's timeout starts before the lock wait.** The 15-second `configStoreTimeout` begins before `beginCopiesMutation`, and `lockApp` ignores the context. A long lock wait can leave the manifest write little time, so a 15-minute upload could fail with 502 (`copiespublication.go`, `copiesShipManifestGate`). Start the timeout after the lock is acquired. - **Note, not a defect:** hibernating ship now takes the durable `WithAppMutation` operation first and the app lock second, the reverse of rollback and other doors. `BeginExclusive` fails fast with `ErrPending` rather than waiting (`hostops/control_writer.go:277-281`), so this cannot deadlock. The worst case is that whichever side comes second is refused. ### Out-of-Scope Observations - With `HostClaim` boundaries in production, `release.Ship` and `ShipSpooled` still hold the durable exclusive app operation across the whole upload. That predates this fix. A rollback or config write during an upload is therefore still refused with `ErrPending` in production, even with the in-process lock gone. The new rollback test passes only because its fixture store is not an `AppMutationRunner`. - A copies refusal in `finishCopiesClaimCreate` comes after the private bucket has been provisioned. That is the failure order the handler's comment says it exists to avoid. Other completion failures already had this property. ### Verdict **Fix round:** Findings remain open. Important 1 and m1-m4 are addressed, but the fix adds one Important problem: claim create's second default-config GET for legacy apps breaks the P7 merge gate. It applies to every claim create and is unconditional when there is no private storage. Two Minor items are also open: the `--copies` help test that cannot fail, and the gate timeout that starts before the lock wait.</result> <usage><subagent_tokens>88448</subagent_tokens><tool_uses>11</tool_uses><duration_ms>167750</duration_ms></usage> </task-notification>

Attributed to this commit: 36.8 g CO₂e (4,421,095 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 c472f97d9..4c053da60 100644
--- a/apps_copies_test.go
+++ b/apps_copies_test.go
@@ -63,7 +63,13 @@ func TestCopiesHelpHasOneDefault(t *testing.T) {
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)
+ for _, line := range strings.Split(string(out), "\n") {
+ if strings.Contains(line, appsSetFlagCopies) {
+ if strings.Count(line, "(default 1)") != 1 || strings.Count(line, "(default") != 1 {
+ t.Fatalf("copies help default: %s", line)
+ }
+ return
+ }
}
+ t.Fatalf("copies help missing: %s", out)
}
diff --git a/internal/console/apiinstances.go b/internal/console/apiinstances.go
index 90b125f43..4a436f76a 100644
--- a/internal/console/apiinstances.go
+++ b/internal/console/apiinstances.go
@@ -2410,10 +2410,13 @@ func (s *Server) handleAPIInstanceCreate(w http.ResponseWriter, r *http.Request)
return
}
defer claimRequest.Close()
- createUnlock()
- createUnlock = nil
- createContext = context.WithValue(claimRequest.Context, copiesHeldKey{}, copiesHeld{})
- claimRequest.Context = createContext
+ createContext = claimRequest.Context
+ if m.PrivateStorage {
+ createUnlock()
+ createUnlock = nil
+ createContext = context.WithValue(createContext, copiesHeldKey{}, copiesHeld{})
+ claimRequest.Context = createContext
+ }
}
if m.PrivateStorage {
// r.Context(), not ctx: the walk takes storeGrantTimeout, which is
@@ -2442,10 +2445,16 @@ func (s *Server) handleAPIInstanceCreate(w http.ResponseWriter, r *http.Request)
}
var recordWriteErr error
switch {
- case claimRequest != nil:
+ case claimRequest != nil && m.PrivateStorage:
if !s.finishCopiesClaimCreate(w, claimRequest, acct, app) {
return
}
+ case claimRequest != nil:
+ // P9: no storage walk released the hold, so keep its admission and
+ // memo through publication without a second config/incarnation read.
+ if !s.finishClaimCreate(w, claimRequest) {
+ return
+ }
case lifetimesUnit(ctx):
// Dispatch by the admitted unit (lifetimes.go): the lifetime
// create, which answers the record as written.
diff --git a/internal/console/copies_upload_test.go b/internal/console/copies_upload_test.go
index 33a6dac0b..7b001b97f 100644
--- a/internal/console/copies_upload_test.go
+++ b/internal/console/copies_upload_test.go
@@ -10,6 +10,7 @@ import (
"os"
"strings"
"sync"
+ "sync/atomic"
"testing"
"time"
@@ -269,3 +270,56 @@ func TestCopiesClaimFinishRechecksAfterStorage(t *testing.T) {
t.Fatal("finish leaked app lock")
}
}
+
+func TestCopiesClaimCreateReadsDefaultOnce(t *testing.T) {
+ cx := newClaimCase(t)
+ enableInstances(t, cx.consoleFixture, "titogo", titoManifest())
+ var reads atomic.Int32
+ cx.rel.(*deletableStore).setGetHook(func(_ context.Context, key string) error {
+ if key == appconfig.Key(cx.sqid, "titogo") {
+ reads.Add(1)
+ }
+ return nil
+ })
+ code, _, body := rawReq(t, "POST", cx.ts.URL+"/api/cli/apps/bab/titogo/instances", cx.bearer,
+ `{"host":"new.go.tito.io","region":"ie","channel":"edge"}`)
+ if code != http.StatusCreated && code != http.StatusAccepted {
+ t.Fatalf("claim create: %d %s", code, body)
+ }
+ if n := reads.Load(); n != 1 {
+ t.Fatalf("legacy non-private claim create: %d default-config GETs, want 1", n)
+ }
+}
+
+func TestCopiesShipManifestBudgetStartsAfterLock(t *testing.T) {
+ fx, _ := copiesWorld(t)
+ acct, _ := fx.st.AccountBySqid(fx.sqid)
+ releaseLock := fx.srv.lockApp(fx.sqid, "shop")
+ var released sync.Once
+ defer released.Do(releaseLock)
+ waiting := make(chan struct{})
+ appLockWaits(t, fx.sqid, waiting)
+ type result struct {
+ ctx context.Context
+ done func()
+ err error
+ }
+ out := make(chan result, 1)
+ go func() {
+ ctx, done, err := fx.srv.copiesShipManifestGate(acct)(context.Background(), &release.Manifest{App: "shop", Hibernate: true})
+ out <- result{ctx, done, err}
+ }()
+ <-waiting
+ time.Sleep(300 * time.Millisecond)
+ releasedAt := time.Now()
+ released.Do(releaseLock)
+ r := <-out
+ defer r.done()
+ if r.err != nil {
+ t.Fatal(r.err)
+ }
+ deadline, ok := r.ctx.Deadline()
+ if !ok || deadline.Before(releasedAt.Add(configStoreTimeout)) {
+ t.Fatalf("manifest budget spent during lock wait: deadline %s, acquired after %s", deadline, releasedAt)
+ }
+}
diff --git a/internal/console/copiespublication.go b/internal/console/copiespublication.go
index c4143966a..f73c3f972 100644
--- a/internal/console/copiespublication.go
+++ b/internal/console/copiespublication.go
@@ -312,11 +312,14 @@ func (s *Server) copiesShipManifestGate(acct *Account) release.ManifestGate {
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)
+ held, unlock, ref := s.beginCopiesMutation(withWriteMemo(ctx), acct, target.App)
+ if ref != nil {
+ unlock()
+ return ctx, func() {}, &statelessSelectionError{ref}
}
+ // Waiting for the app lock must not spend the publication budget.
+ held, cancel := context.WithTimeout(held, configStoreTimeout)
+ ref = s.copiesPublicationRefusal(held, acct, target.App, target, "", true)
if ref != nil {
unlock()
cancel()
diff --git a/internal/console/perfwrites_test.go b/internal/console/perfwrites_test.go
index 2d8fb65a5..6c5e7ea93 100644
--- a/internal/console/perfwrites_test.go
+++ b/internal/console/perfwrites_test.go
@@ -16,6 +16,7 @@ import (
"testing"
"time"
+ "github.com/carlosframework/platform/internal/appconfig"
"github.com/carlosframework/platform/internal/plans"
"github.com/carlosframework/platform/internal/provision"
"github.com/carlosframework/platform/internal/release"
@@ -386,4 +387,76 @@ func TestPerfWriteRoutesMeetTheBudget(t *testing.T) {
}
}
t.Logf("door\tS3\ttime\tbudget\n%s", strings.Join(table, "\n"))
+ t.Run("claim instance create", perfClaimInstanceCreate)
+}
+
+// The original write fixture uses lifetimes with HostClaim off. Exercise
+// the claim protocol through its real S3 store too, including completion.
+func perfClaimInstanceCreate(t *testing.T) {
+ lat := &perfLatency{S3Delay: 25 * time.Millisecond}
+ cx := newClaimCaseWith(t, func(cfg *Config) {
+ raw := cfg.Releases.(*claimRawStore)
+ cfg.Releases = fixtureS3Store(t, raw.inner, lat, nil)
+ })
+ if !cx.srv.cfg.HostClaim || cx.srv.cfg.HostClaimOps == nil {
+ t.Fatal("claim create budget is measuring the legacy path")
+ }
+ enableInstances(t, cx.consoleFixture, "titogo", titoManifest())
+ var bodyEnd atomic.Pointer[time.Time]
+ cx.srv.cliBodyWrap = func(r *http.Request) io.ReadCloser {
+ return &bodyEndStamp{ReadCloser: r.Body, want: r.ContentLength, at: &bodyEnd}
+ }
+ t.Cleanup(func() { cx.srv.cliBodyWrap = nil })
+ var times []time.Duration
+ most := 0
+ for n := 0; n < 4; n++ {
+ recorder := recordS3(lat, nil)
+ lat.Enable(true)
+ host := fmt.Sprintf("perf%d.go.tito.io", n)
+ code, _, body := rawReq(t, http.MethodPost, cx.ts.URL+"/api/cli/apps/bab/titogo/instances", cx.bearer,
+ fmt.Sprintf(`{"host":%q,"region":"ie","channel":"edge"}`, host))
+ end := time.Now()
+ lat.Enable(false)
+ if code != http.StatusCreated && code != http.StatusAccepted {
+ t.Fatalf("claim create #%d: %d %s", n, code, body)
+ }
+ readAt := bodyEnd.Swap(nil)
+ if readAt == nil {
+ t.Fatal("claim create did not consume its body")
+ }
+ if n > 0 {
+ times = append(times, end.Sub(*readAt))
+ }
+ requests := recorder.all()
+ most = max(most, len(requests))
+ if len(requests) > 107 {
+ t.Errorf("claim create #%d: %d S3 requests, budget 107", n, len(requests))
+ }
+ configReads := 0
+ for _, q := range requests {
+ if q.Method == http.MethodGet && q.Key == appconfig.Key(cx.sqid, "titogo") {
+ configReads++
+ }
+ }
+ if configReads != 1 {
+ t.Errorf("claim create #%d: %d default-config GETs, want 1", n, configReads)
+ }
+ if _, err := provision.GetRecord(context.Background(), cx.rel, cx.sqid, "titogo", host); err != nil {
+ t.Fatalf("claim create #%d did not publish its record: %v", n, err)
+ }
+ }
+ slices.Sort(times)
+ // P9 baseline: 107 requests and 3.50s at 25ms/S3, including claim
+ // registration, ownership/record effects and completion. This is a
+ // separate protocol budget; the claims-off limits above stay unchanged.
+ median := times[len(times)/2]
+ budget := 4 * time.Second
+ if median > budget {
+ if perfEnforce() {
+ t.Errorf("claim create: median %s ms after the body, budget %v", ms(median), budget)
+ } else {
+ t.Logf("(not enforced locally) claim create: median %s ms after the body, budget %v", ms(median), budget)
+ }
+ }
+ t.Logf("claim instance create: %d S3 at most, median %s ms after the body, budget %v", most, ms(median), budget)
}