From 70d29c86b9d06f7bd4ec46d3f0f7aca1e0c5df40 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 28 Nov 2026 21:52:28 -0800 Subject: [PATCH] fix(storage): every HEAD commit of the chunk layer runs the object check first A detach's cancellation and an unresolved cut's re-proposal now run the object check before their CAS, as the cut's commit does. The cancellation adds no chunk, but its new root's segments and root were looked up inside the HEAD step's fixed limit. The guard requires the check before every HEAD commit site and lists no exemption; the fixed-limits row names it and the cancellation's control. Co-Authored-By: Claude Opus 5.5 --- .../layout_commit_retry_plan_test.go | 41 +++++++++++ .../chunk_commit_check_callers_test.go | 73 ++++++++----------- seaweed-block/core/storage/chunk_layer.go | 38 +++++++--- seaweed-block/docs/design/invariants.md | 2 +- 4 files changed, 101 insertions(+), 53 deletions(-) diff --git a/seaweed-block/core/frontend/chunkstore/layout_commit_retry_plan_test.go b/seaweed-block/core/frontend/chunkstore/layout_commit_retry_plan_test.go index f3813d889d..48f52de033 100644 --- a/seaweed-block/core/frontend/chunkstore/layout_commit_retry_plan_test.go +++ b/seaweed-block/core/frontend/chunkstore/layout_commit_retry_plan_test.go @@ -81,3 +81,44 @@ func TestReproposalAfterAnUnknownCommitOutcomeLooksUpNothing(t *testing.T) { t.Fatal("no commit landed") } } + +// A detach whose HEAD update is lost before it applies is settled by +// cancelling it: the chunk layer publishes the base image again. That +// cancellation is a commit of its own, with no new chunk but a new root +// over the open snapshot session's segments; it is checked before its CAS +// like every HEAD commit, so the CAS (the HEAD step under the fixed limit) +// looks up no chunk, segment or root. +func TestDetachCancellationAfterALostUpdateLooksUpNothingInTheHeadStep(t *testing.T) { + lh, w, l := c1Layer(t) + var inStep atomic.Int64 + lh.ff.afterLookup = func(p string) { + if w.inCAS.Load() && (strings.Contains(p, "/pool/") || strings.Contains(p, "/seg/") || strings.Contains(p, "/root/")) { + inStep.Add(1) + } + } + var lost atomic.Bool + lh.ff.failUpdate = func(p string) error { // under ff.mu: the update is lost before it applies + if strings.HasSuffix(p, "/HEAD") && w.inCAS.Load() && !lost.Load() { + lost.Store(true) + return errors.New("connection reset: the update's reply is lost") + } + return nil + } + if _, err := l.Detach(context.Background()); err == nil { + t.Fatal("setup: the detach whose HEAD update was lost reported success") + } + if !lost.Load() { + t.Fatal("setup: no HEAD update was lost") + } + inStep.Store(0) + settled, _, err := l.SettleDetach(context.Background()) + if err != nil { + t.Fatalf("settling the detach: %v", err) + } + if settled != storage.DetachNotPublished { + t.Fatalf("settled %v, want the detach cancelled (not published)", settled) + } + if n := inStep.Load(); n != 0 { + t.Fatalf("the cancellation's HEAD step looked up %d chunks, segments or roots; want 0 (checked before its CAS)", n) + } +} diff --git a/seaweed-block/core/storage/chunk_commit_check_callers_test.go b/seaweed-block/core/storage/chunk_commit_check_callers_test.go index f51502d786..e91d08dc22 100644 --- a/seaweed-block/core/storage/chunk_commit_check_callers_test.go +++ b/seaweed-block/core/storage/chunk_commit_check_callers_test.go @@ -11,24 +11,22 @@ import ( "testing" ) -// Every HEAD commit of the chunk layer that can add chunks runs the commit's -// object check (CheckCommit) before it, with the cut's budget. A commit that -// is not checked first looks up every new chunk inside the HEAD step's fixed -// 2 s limit, which grows with the volume; the fixed-limits table states that -// path as a gap that no production caller takes, and this guard keeps that -// true. Each HEAD commit site in the package's sources is listed with why it -// is bounded; a new site fails here until it is classified. -func TestEveryHeadCommitWithNewChunksIsCheckedFirst(t *testing.T) { - // Sites that add chunks: the object check must come first in the same - // function. - checked := map[string]bool{ - "captureLocked": true, // the cut's commit - } - // Sites whose next HEAD adds no chunk the HEAD did not name, so the - // commit has nothing to look up. - noNewChunks := map[string]string{ - "SettleDetach": "cancels an unresolved detach by re-publishing its base's chunks", - "resolvePending": "re-proposes the unresolved cut's own proposal at the same base; that cut checked it, and the holder keeps the check for the session's attempts", +// Every HEAD commit of the chunk layer runs the commit's object check +// (checkCommitFirst) before its CAS, with the caller's budget. A commit that +// is not checked first runs its lookups (every new chunk, and the segments +// and root of a new root, even with no new chunk) inside the HEAD step's +// fixed 2 s limit, and they grow with the volume; the fixed-limits table +// states that path as a gap that no production caller takes, and this guard +// keeps that true for every HEAD commit site in the package's sources: a new +// site fails here until it checks first and is listed. The holder's snapshot +// of an unchanged image commits outside this package and outside the HEAD +// step: it calls the commit directly under its caller's limit, so it is not +// this path. +func TestEveryHeadCommitIsCheckedFirst(t *testing.T) { + sites := map[string]string{ + "captureLocked": "the cut's commit", + "SettleDetach": "the cancellation of an unresolved detach", + "resolvePending": "the re-proposal of an unresolved cut", } files, err := filepath.Glob("*.go") if err != nil { @@ -37,7 +35,7 @@ func TestEveryHeadCommitWithNewChunksIsCheckedFirst(t *testing.T) { fset := token.NewFileSet() seen := map[string]int{} for _, name := range files { - if strings.HasSuffix(name, "_test.go") || name == "chunk_head_belt.go" { + if strings.HasSuffix(name, "_test.go") || name == "chunk_head_belt.go" || name == "chunk_memremote.go" { continue } src, err := os.ReadFile(name) @@ -67,12 +65,10 @@ func TestEveryHeadCommitWithNewChunksIsCheckedFirst(t *testing.T) { } case *ast.SelectorExpr: switch callee.Sel.Name { - case "CheckCommit": + case "checkCommitFirst": checks = append(checks, call.Pos()) case "CASHead": - if name != "chunk_memremote.go" { - commits = append(commits, call.Pos()) - } + commits = append(commits, call.Pos()) } } return true @@ -80,37 +76,30 @@ func TestEveryHeadCommitWithNewChunksIsCheckedFirst(t *testing.T) { for _, at := range commits { site := fn.Name.Name seen[site]++ - if checked[site] { - first := false - for _, c := range checks { - if c < at { - first = true - } - } - if !first { - t.Errorf("%s: %s commits HEAD without the object check before it", fset.Position(at), site) - } + if _, ok := sites[site]; !ok { + t.Errorf("%s: %s commits HEAD and is not a listed site: check the commit first (checkCommitFirst) and list it", fset.Position(at), site) continue } - if _, ok := noNewChunks[site]; !ok { - t.Errorf("%s: %s commits HEAD and is not classified: check the commit first, or list why its next HEAD adds no chunk", fset.Position(at), site) + first := false + for _, c := range checks { + if c < at { + first = true + } + } + if !first { + t.Errorf("%s: %s (%s) commits HEAD without checkCommitFirst before it", fset.Position(at), site, sites[site]) } } } } var missing []string - for site := range checked { - if seen[site] == 0 { - missing = append(missing, site) - } - } - for site := range noNewChunks { + for site := range sites { if seen[site] == 0 { missing = append(missing, site) } } sort.Strings(missing) if len(missing) > 0 { - t.Errorf("classified HEAD commit sites no longer found: %v; update the lists", missing) + t.Errorf("listed HEAD commit sites no longer found: %v; update the list", missing) } } diff --git a/seaweed-block/core/storage/chunk_layer.go b/seaweed-block/core/storage/chunk_layer.go index 277becf626..54bafb5d3a 100644 --- a/seaweed-block/core/storage/chunk_layer.go +++ b/seaweed-block/core/storage/chunk_layer.go @@ -1112,16 +1112,11 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch return chunkCutResult{H: h, Head: copyHead(cur), Noop: true, FullHash: all}, nil } expected := chunkHeadVersion{Gen: baseHead.Gen, Epoch: baseHead.Epoch} - // The commit's object check runs here, with the cut's budget: inside the - // CAS it would share the 2 s HEAD update. A lookup failure writes nothing - // and leaves the session open; the dirty set returns for the next cut. A - // precondition or fence goes on to the CAS, which answers it from HEAD - // (before any lookup) and resolves it as without the check. - if c, ok := l.remote.(chunkCommitChecker); ok { - if err := c.CheckCommit(ctx, expected, next); err != nil && !errors.Is(err, errChunkHeadPrecondition) && !errors.Is(err, errChunkLayerFenced) { - l.requeueCut(all) - return chunkCutResult{}, fmt.Errorf("storage: commit check: %w: %w", errChunkRemoteUnavailable, err) - } + // A lookup failure writes nothing and leaves the session open; the dirty + // set returns for the next cut. + if err := l.checkCommitFirst(ctx, expected, next); err != nil { + l.requeueCut(all) + return chunkCutResult{}, fmt.Errorf("storage: commit check: %w: %w", errChunkRemoteUnavailable, err) } if err := l.admit(); err != nil { // admission re-checked right before the CAS l.requeueCut(all) @@ -1264,6 +1259,9 @@ func (l *chunkLayerImpl) SettleDetach(ctx context.Context) (settled detachSettle cancel := copyHead(baseHead) cancel.Epoch, cancel.Holder = l.cfg.Epoch, l.cfg.Holder cancel.State, cancel.DetachedBy = chunkHeadActive, nil + if err := l.checkCommitFirst(ctx, base, cancel); err != nil { + return 0, chunkCutResult{}, fmt.Errorf("storage: detach outcome unresolved (%w); cancel check failed: %w", errChunkCASOutcomeUnknown, err) + } gen, casErr := casAndConfirmChunkHead(ctx, l.remote, base, cancel) if casErr == nil { cancel.Gen = gen @@ -1371,6 +1369,23 @@ func sameProposal(cur, next chunkHead) bool { } // resolvePending re-reads HEAD when an earlier CAS outcome is unresolved. +// checkCommitFirst runs a HEAD commit's object check (chunkCommitChecker) +// before its CAS, with the caller's budget: inside the CAS it would run in +// the HEAD step's fixed limit, and its lookups grow with the volume. Every +// HEAD commit of this layer calls it first. A remote without the check +// passes. A precondition or fence goes on to the CAS, which answers it from +// HEAD (before any lookup) and resolves it as without the check. +func (l *chunkLayerImpl) checkCommitFirst(ctx context.Context, expected chunkHeadVersion, next chunkHead) error { + c, ok := l.remote.(chunkCommitChecker) + if !ok { + return nil + } + if err := c.CheckCommit(ctx, expected, next); err != nil && !errors.Is(err, errChunkHeadPrecondition) && !errors.Is(err, errChunkLayerFenced) { + return err + } + return nil +} + func (l *chunkLayerImpl) resolvePending(ctx context.Context) (err error) { // Registered before the state unlock, so invalidation runs without stMu. defer func() { @@ -1399,6 +1414,9 @@ func (l *chunkLayerImpl) resolvePending(ctx context.Context) (err error) { if err := l.admit(); err != nil { return fmt.Errorf("storage: capture: earlier CAS outcome still unresolved (%w); re-proposal refused: %w", errChunkCASOutcomeUnknown, err) } + if err := l.checkCommitFirst(ctx, base, *pending); err != nil { + return fmt.Errorf("storage: capture: earlier CAS outcome still unresolved (%w); re-proposal check failed: %w", errChunkCASOutcomeUnknown, err) + } gen, casErr := casAndConfirmChunkHead(ctx, l.remote, base, copyHead(*pending)) if casErr == nil { cur = copyHead(*pending) diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 83cf024f50..6147f898d1 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -1179,7 +1179,7 @@ One row per fixed time limit on a volume's path that surrounds, or once surround | Site | Limit | Inside the limit | Grows with the volume | Outside it, judged by progress | Test at 262,144 chunks | |---|---|---|---|---|---| | `core/storage/chunk_head_belt.go` `casChunkHead`, applied by `LayoutRemote.commitStepLocked` | 2 s per attempt | one HEAD step: the HEAD read, the commit's decision from its plan, the conditional write | no | the commit's preparation (the previous manifest, the next root and segments, the plan) and its object lookups, under the cut's limit; a commit after a passed check reuses the preparation | `TestHolderCommitAtOneTiBKeepsItsPreparationOutOfTheHeadStep`, `TestCommitUpdateStepDoesNotRereadTheManifests` | -| the same step, for a commit that was NOT checked first | 2 s per attempt | the step and the object lookups of every new chunk | **yes** | nothing: no production caller commits without the check; a new caller must check first | none: a known gap, stated here so it is not claimed. Kept true by `TestEveryHeadCommitWithNewChunksIsCheckedFirst`, which enumerates every HEAD commit of the chunk layer and refuses one that adds chunks without the object check before it | +| the same step, for a commit that was NOT checked first | 2 s per attempt | the step and the object lookups of every new chunk, and of a new root's segments and root even when no chunk is new | **yes** | nothing: no production caller commits without the check; a new caller must check first | none: a known gap, stated here so it is not claimed. Kept true by `TestEveryHeadCommitIsCheckedFirst`: every HEAD commit of the chunk layer (a cut's commit, a detach's cancellation, an unresolved cut's re-proposal) runs the object check before its CAS, and a new site fails until it does. `TestDetachCancellationAfterALostUpdateLooksUpNothingInTheHeadStep` measures the cancellation. The snapshot of an unchanged image commits under its caller's limit, not in this step | | `DurableProvider.chunkCutContext` (`ChunkCutTimeout`) | 5 min per attempt | staging the changed chunks, the check, the commit | yes | uploads finished by an attempt are kept; the next attempt uploads only the rest (same process) | `TestACutAttemptThatRunsOutOfTimeLeavesUploadsTheNextAttemptKeeps` | | the cleaning pass (`boundedPass`) | the configured pass limit | listing and removing by page | yes | the pass resumes at its cursor; a session after a restart starts at the root page | the cleaning cursor's tests | | `core/host/volume/chunk_control.go` `chunkContext` (a chunk control operation: a cut, a snapshot or a detach, each of which takes a cut; the chunk status read also runs under it and reads one HEAD) | 5 min, or the request's shorter limit | the operation, including the cut it takes | yes | the cut's uploads, as the cut's row: an attempt that runs out of time keeps what it uploaded | STUB: no test at the control operation's level yet |