From def2a78fac4f72b8c5537065092df2de8a37ad4a Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 2 Dec 2026 02:41:20 -0800 Subject: [PATCH] Resume persisted delete intents through holder maintenance --- .../core/frontend/chunkstore/layout_remote.go | 47 +++++++-- .../chunkstore/layout_remote_intent_test.go | 99 +++++++++++++++++++ seaweed-block/docs/design/invariants.md | 4 +- 3 files changed, 139 insertions(+), 11 deletions(-) create mode 100644 seaweed-block/core/frontend/chunkstore/layout_remote_intent_test.go diff --git a/seaweed-block/core/frontend/chunkstore/layout_remote.go b/seaweed-block/core/frontend/chunkstore/layout_remote.go index 6ef684ee2e..cfd465719b 100644 --- a/seaweed-block/core/frontend/chunkstore/layout_remote.go +++ b/seaweed-block/core/frontend/chunkstore/layout_remote.go @@ -31,8 +31,7 @@ import ( // alone resolves the owner's directory and is verified by name. // sessionStore is what the remote writes through: HEAD and the objects. type sessionStore interface { - layout.HeadStore - layout.ObjectStore + layout.ListChainStore } type LayoutRemote struct { @@ -1261,7 +1260,11 @@ func (l *LayoutRemote) LastCommit() layout.Head { return l.lastCommit } -// Clean runs one cleaning of this holder between sessions: clean(c) opens +// Clean first resumes a persisted snapshot-delete intent between sessions, +// using the same cancellation/join as the subsequent compatibility sweep. +// The attached holder is checked before intent effects; the intent itself +// remains receipt-independent authority under its live-root guards. +// Then clean(c) opens // HEAD, run removes unreachable names under session c, and clean(c) ends. // A cut or a stop that needs HEAD meanwhile cancels run's context and // waits for it to end: neither waits on a cleaning nor fails busy. A pass @@ -1276,7 +1279,8 @@ func (l *LayoutRemote) Clean(ctx context.Context, run func(ctx context.Context, l.mu.Unlock() return layout.ErrBusy } - if _, err := l.rollBackLocked(ctx); err != nil { + h, err := l.rollBackLocked(ctx) + if err != nil { l.mu.Unlock() return err } @@ -1286,16 +1290,43 @@ func (l *LayoutRemote) Clean(ctx context.Context, run func(ctx context.Context, return err } c := "c-" + hex.EncodeToString(b[:]) - bh, err := layout.RunBeginClean(ctx, l.st, l.me, c) - if err != nil { + // Validate the attached holder before applying offline intent effects. The + // pure transition performs the same guard without opening clean activity: + // the persisted intent consumer requires HEAD to remain idle. + if _, _, err := h.BeginClean(l.me, c); err != nil { l.mu.Unlock() return layoutRemoteErr(err) } - l.ownGen = bh.Gen cctx, cancel := context.WithCancel(ctx) done := make(chan struct{}) l.cleaning, l.cleanCancel, l.cleanDone = c, cancel, done l.mu.Unlock() + defer func() { + cancel() + l.mu.Lock() + l.cleaning, l.cleanCancel = "", nil + close(done) + l.mu.Unlock() + }() + + // Resume only the dedicated delete intent. A generic list is consumed by + // its own protocol; membership alone must not grant delete authority. + for h.List != nil && h.List.Kind == layout.ListSnapshotDeleteIntent { + if err := cctx.Err(); err != nil { + return err + } + h, err = layout.RunConsumeSnapshotDeleteIntent(cctx, l.st, l.r) + if err != nil { + return layoutRemoteErr(err) + } + } + bh, err := layout.RunBeginClean(cctx, l.st, l.me, c) + if err != nil { + return layoutRemoteErr(err) + } + l.mu.Lock() + l.ownGen = bh.Gen + l.mu.Unlock() runErr := run(cctx, l.me, c) // Bounded by the caller's context: a stop on a hung filer does not @@ -1308,8 +1339,6 @@ func (l *LayoutRemote) Clean(ctx context.Context, run func(ctx context.Context, if endErr == nil { l.ownGen = eh.Gen } - l.cleaning, l.cleanCancel = "", nil - close(done) l.mu.Unlock() if runErr != nil && !errors.Is(runErr, context.Canceled) { return runErr diff --git a/seaweed-block/core/frontend/chunkstore/layout_remote_intent_test.go b/seaweed-block/core/frontend/chunkstore/layout_remote_intent_test.go new file mode 100644 index 0000000000..b9f349c958 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/layout_remote_intent_test.go @@ -0,0 +1,99 @@ +package chunkstore + +import ( + "context" + "errors" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +func TestHolderMaintenanceResumesThePersistedDeleteIntent(t *testing.T) { + for _, wrongClaim := range []bool{false, true} { + t.Run(map[bool]string{false: "holder", true: "wrong claim"}[wrongClaim], func(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + cat, ref, cost := largeIntentCatalog(t, 1024) + me := cleanHolder + if wrongClaim { + me.ClaimID += "-old" + } + remote, err := NewLayoutRemote(cat, ref, me) + if err != nil { + t.Fatal(err) + } + called := false + err = remote.Clean(ctx, func(ctx context.Context, _ layout.HolderID, _ string) error { + called = true + h, err := remote.ReadHead(ctx) + if err == nil && h.List != nil { + t.Error("fallback sweep started before the persisted intent finished") + } + return err + }) + if wrongClaim { + if !errors.Is(err, storage.ErrChunkLayerFenced) || called || len(cost.deletes) != 0 { + t.Fatalf("wrong holder removed work: err=%v callback=%v deletes=%v", err, called, cost.deletes) + } + return + } + if err != nil || !called || len(cost.deletes) != 4 || cost.lists != 0 { + t.Fatalf("intent continuation: err=%v callback=%v deletes=%v namespace lists=%d", err, called, cost.deletes, cost.lists) + } + }) + } +} + +type blockedMaintenanceIntent struct { + sessionStore + entered chan struct{} +} + +func (s blockedMaintenanceIntent) ReadListPage(ctx context.Context, _ layout.ListRef) ([]byte, bool, error) { + close(s.entered) + <-ctx.Done() + return nil, false, ctx.Err() +} + +func TestHolderMaintenanceIntentIsCancelledBeforeTheCutJoins(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + cat, ref, cost := largeIntentCatalog(t, 1024) + remote, err := NewLayoutRemote(cat, ref, cleanHolder) + if err != nil { + t.Fatal(err) + } + entered := make(chan struct{}) + remote.st = blockedMaintenanceIntent{sessionStore: remote.st, entered: entered} + result := make(chan error, 1) + go func() { + result <- remote.Clean(ctx, func(context.Context, layout.HolderID, string) error { + return errors.New("fallback must not run after cancellation") + }) + }() + select { + case <-entered: + case <-ctx.Done(): + t.Fatal("intent did not enter its page read") + } + remote.mu.Lock() + err = remote.stopCleaningLocked(ctx) + remote.mu.Unlock() + if err != nil { + t.Fatal(err) + } + select { + case err := <-result: + if !errors.Is(err, context.Canceled) { + t.Fatalf("intent cancellation: %v", err) + } + case <-ctx.Done(): + t.Fatal("maintenance did not join") + } + h, err := remote.ReadHead(ctx) + if err != nil || h.List == nil || h.Activity.Kind != layout.ActIdle || len(cost.deletes) != 0 { + t.Fatalf("cancelled work lost its continuation: head=%+v err=%v deletes=%v", h, err, cost.deletes) + } +} diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 78d260e3d5..950f38cb16 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -585,7 +585,7 @@ stateDiagram-v2 | clean(c), current list page | clean(c), next continuation or none | exact observed cursor CAS only after authenticated page effects succeed; failed reads and failed effects leave cursor unchanged | `list_chain.go` `RunAdvanceList` | `INV-LIST-CURSOR-001` | | clean(c), stored list page | clean(c), unreached page removed | tags before HEAD; current clean session; spare all current-chain pages; conditional mark then delete | `remove.go` `Cleaner.Page` | `INV-LIST-RETIRE-001` | | idle/snap, retained snapshot | same activity, row removed and intent published | one CAS removes only captured name/gen and names its durable chain; each page present, this attempt's tag, unmarked; clean activity refuses | `delete_intent.go` `RunDeleteSnapshotWithIntent` | `INV-SNAPSHOT-DELETE-INTENT-001`, `INV-SNAPSHOT-DELETE-ADOPT-001` | -| idle live/detached, persisted delete intent | idle live/detached, next intent page or none | receipt-independent continuation from current HEAD; live-root and conditional effect guards; cursor follows completed effects | `delete_intent.go` `RunConsumeSnapshotDeleteIntent`; `BCatalog.CleanSnapshotDeletePage` | `INV-SNAPSHOT-DELETE-CONSUME-001` | +| idle live/detached, persisted delete intent | idle live/detached, next intent page or none | receipt-independent continuation from current HEAD; live-root and conditional effect guards; cursor follows completed effects | `delete_intent.go` `RunConsumeSnapshotDeleteIntent`; `BCatalog.CleanSnapshotDeletePage`; `LayoutRemote.Clean` | `INV-SNAPSHOT-DELETE-CONSUME-001` | | idle | snap(s) | caller is the holder at HEAD's epoch (epoch, server and claim id); HEAD present; snap(s) again is a replay, any other activity is refused | head.go `Head.Begin`, `runTransition` | `INV-SNAPK-HEAD-WRITE-001`, `INV-SNAPK-BEGIN-001` | | snap(s) | idle | holder at HEAD's epoch (epoch, server and claim id); activity is snap(s); over idle it succeeds without a write and means only that no activity remains; before resuming a failed stop, abort its still-open session and re-read HEAD: only matching live/idle resumes, detached goes Down, absent/unknown stays stopped | head.go `Head.Abort`; durable/provider_layout.go `settleLayoutStop` | `INV-SNAPK-ABORT-001` | | snap(s) | idle, current = root | holder at HEAD's epoch (epoch, server and claim id); activity is snap(s); the previous manifest builds to HEAD's current root; the new own chunks, every segment and the root are present; a new snapshot name records bounded retention facts once, while replay preserves them | commit.go `Head.Commit`, `RunCommit` | `INV-SNAPK-COMMIT-REACH-001`, `INV-SNAPK-TXN-INTERRUPT-001`, `INV-SNAPK-SNAPSHOT-META-001` | @@ -1308,7 +1308,7 @@ Notes: | `INV-LIST-CURSOR-001` | The persisted list cursor advances only after its authenticated page's idempotent effects finish; a missing page never completes work. | M9 clean -> clean | `list_chain.go` `RunAdvanceList` | `TestAdvanceList_Closure`, `TestRunAdvanceList_InterruptAtEveryStep`, `TestListMissingConsumerPageNeverCompletes` | PageChain 246,251-253; NoLostWork | DORMANT | | `INV-LIST-RETIRE-001` | List-page removal requires a clean session and the existing conditional mark/delete order; every page reached by HEAD is spared, including shared tails. | M9 clean removal | `remove.go` `Cleaner.removePlanned`; `clean_b.go` compatibility sweep | `TestListSweepSpareSessionAndReachableTail`, `TestListSharedTailSurvivesAbandonedChainAndResumes`, `TestLayoutStoreListPublishConsumeAndRetire`, `TestBCatalogFullSweepKeepsTheEntireCurrentList`, `TestBCatalogListRetirementResumesAfterRestart` | PageChain 246,248-251; NoDangling | DORMANT | | `INV-SNAPSHOT-DELETE-INTENT-001` | Removing a captured snapshot incarnation and publishing its durable intent are one HEAD CAS; an unrelated metadata retry keeps the same target and durable pages. | M9 metadata delete | `delete_intent.go` `RunDeleteSnapshotWithIntent` | `TestDeleteSnapshotWithIntent_Closure`, `TestRunDeleteSnapshotWithIntent_InterruptAtEveryStep`, `TestDeleteIntentRetryKeepsDurablePagesAcrossMetadataCAS` | SnapDelete 241-245; PageChain 246-249 | DORMANT | -| `INV-SNAPSHOT-DELETE-CONSUME-001` | Only current persisted delete intent authorizes offline reclamation; live roots remain protected, failed effects retain the cursor, and receipt retirement cannot erase work. | M9 idle intent continuation | `delete_intent.go`; `remove.go` `Cleaner.removePlanned` | `TestConsumeSnapshotDeleteIntent_Closure`, `TestDeleteIntentOfflineAndReplacementPreserved`, `TestDeleteIntentMarkConflictKeepsUnfinishedPage`, `TestLayoutSnapshotDeleteIntentResumesWithoutReceipt`, `TestCatalogDeleteIntentResumesOnePageWithoutNamespaceScan`, `TestCatalogIntentCursorInterruptAndLostReply` | PageChain 246,251-253; offline authority refinement awaits model/code read | DORMANT | +| `INV-SNAPSHOT-DELETE-CONSUME-001` | Only current persisted delete intent authorizes offline reclamation; live roots remain protected, failed effects retain the cursor, and receipt retirement cannot erase work. | M9 idle intent continuation | `delete_intent.go`; `remove.go` `Cleaner.removePlanned`; `layout_remote.go` `LayoutRemote.Clean` | `TestConsumeSnapshotDeleteIntent_Closure`, `TestDeleteIntentOfflineAndReplacementPreserved`, `TestDeleteIntentMarkConflictKeepsUnfinishedPage`, `TestLayoutSnapshotDeleteIntentResumesWithoutReceipt`, `TestCatalogDeleteIntentResumesOnePageWithoutNamespaceScan`, `TestCatalogIntentCursorInterruptAndLostReply`, `TestHolderMaintenanceResumesThePersistedDeleteIntent`, `TestHolderMaintenanceIntentIsCancelledBeforeTheCutJoins` | PageChain r2 246,251-253 (az1 13/13); StaleClean 159-161 | DORMANT | | `INV-SNAPSHOT-DELETE-ADOPT-001` | Publication adopts every intent page with a fresh CAS-base tag and checks it is present, this attempt's and unmarked; stale cleaners/adopters cannot remove or retag a published page, and staging never restores old tags. | M9 delete intent publication | `delete_intent.go` `adoptDeleteIntentPage`, `RunDeleteSnapshotWithIntent`, `StageSnapshotDeletePage` | `TestDeleteIntentRefreshedBaseFencesDelayedCleanerMark`, `TestDeleteIntentRefreshedBaseFencesDelayedCleanerDelete`, `TestDeleteIntentAdoptionCannotRestoreStaleTags`, `TestDeleteIntentStagingNeverRevertsPublishedTags`, `TestDeleteIntentPublicationChecksAdoptedPageMetadata`, `TestGenericIntentStagingCannotUndoRefreshedPublication` | StaleClean 159-161; exact-head refinement read required | DORMANT | The routine full-sweep scope of `INV-SNAPK-REMOVE-MARK-001` is explicit here: