diff --git a/seaweed-block/core/frontend/chunkstore/layout/delete_intent_reread_test.go b/seaweed-block/core/frontend/chunkstore/layout/delete_intent_reread_test.go index 1437bddf58..fa9f13b64a 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/delete_intent_reread_test.go +++ b/seaweed-block/core/frontend/chunkstore/layout/delete_intent_reread_test.go @@ -6,73 +6,157 @@ import ( "testing" ) -// staleWriteLandsBeforeAdoption is the store as the second run of a snapshot +// staleUpdateBeforeAdoption is the store as the second run of a snapshot // delete sees it when the first run's stalled page update lands between the -// second run's read of the page and its adoption: the page then carries the -// first run's writer tag and the data reference of a page a cleaning pass -// deleted, whose data is freed. -type staleWriteLandsBeforeAdoption struct { +// second run's read of one page (rel) and its adoption: the page then +// carries the first run's writer tag, and its data is whatever the update +// left. This is a consequence-level projection of that update: it edits the +// tag and decides what a later read of the page returns (mode). The backend +// mechanism itself, a tag-conditional whole-entry update writing a deleted +// object's chunk reference over a re-created one, is exercised on the real +// store by TestAStaleMetadataChangeOverwritesARecreatedObject in package +// chunkstore. +type staleUpdateBeforeAdoption struct { *chainStore - rel string - staleTag string - landed bool - dataFreed bool + rel string + staleTag string + mode string // "freed": the read fails; "wrong": it returns other bytes; "valid": the bytes are intact + wrong []byte + landed bool } -func (s *staleWriteLandsBeforeAdoption) Stat(ctx context.Context, rel string) (ObjectMeta, bool, error) { +func (s *staleUpdateBeforeAdoption) Stat(ctx context.Context, rel string) (ObjectMeta, bool, error) { if rel == s.rel && !s.landed { s.landed = true if o, ok := s.objs[s.full(rel)]; ok { o.meta.Session = s.staleTag } - s.dataFreed = true } return s.chainStore.Stat(ctx, rel) } -func (s *staleWriteLandsBeforeAdoption) ReadListPage(ctx context.Context, ref ListRef) ([]byte, bool, error) { - if rel, _ := ref.Path(); s.dataFreed && rel == s.rel { - return nil, false, errors.New("the page's data was freed") +func (s *staleUpdateBeforeAdoption) ReadListPage(ctx context.Context, ref ListRef) ([]byte, bool, error) { + if rel, _ := ref.Path(); s.landed && rel == s.rel { + switch s.mode { + case "freed": + return nil, false, errors.New("the page's data was freed") + case "wrong": + return append([]byte(nil), s.wrong...), true, nil + } } return s.chainStore.ReadListPage(ctx, ref) } -// The second run of a snapshot delete must not publish an intent whose page -// lost its data to the first run's stalled update. The first run checked its -// window and looked the page up, then stalled; a cleaning pass deleted the -// unlinked page; the second run staged it again and read it; then the first -// run's update landed, before the second run adopted the page. Published, -// such an intent could never be consumed: every later snapshot delete on the -// volume would be refused and its cleaning would stop. -func TestASnapshotDeleteIsNotPublishedOverAPageWhoseDataWasFreed(t *testing.T) { - s, c, p := deleteIntentFixture(t) +// rerunFixture stages a snapshot delete's intent at the first base, lets a +// cleaning pass delete the unlinked pages, and stages them again at the new +// base: the second run. With twoPages the intent has two pages and the +// stale update hits the later one, the second page the chain visits. +func rerunFixture(t *testing.T, twoPages bool) (s *chainStore, c ListCursor, hit ListRef, other []byte, firstBase, secondBase uint64) { + t.Helper() ctx := context.Background() - firstBase := s.h.Gen - if _, err := StageSnapshotDeletePage(ctx, s, firstBase, p); err != nil { - t.Fatal(err) + s, c, p := deleteIntentFixture(t) + firstBase = s.h.Gen + pages := []ListPage{p} + if twoPages { + tail := p + tail.Entries = p.Entries[1:] + tailRef, err := tail.Ref() + if err != nil { + t.Fatal(err) + } + head := p + head.Entries = p.Entries[:1] + head.Pages = 2 + head.Next = &tailRef + headRef, err := head.Ref() + if err != nil { + t.Fatal(err) + } + pages = []ListPage{tail, head} + c.Ref = headRef } - rel, err := c.Ref.Path() - if err != nil { - t.Fatal(err) + stage := func(base uint64) { + for _, pg := range pages { + if _, err := StageSnapshotDeletePage(ctx, s, base, pg); err != nil { + t.Fatal(err) + } + } } - // A cleaning pass (two HEAD generations) deletes the unlinked page, and - // the second run stages it again at the new base. - s.h.Gen = firstBase + 2 - delete(s.objs, s.full(rel)) - secondBase := s.h.Gen - if _, err := StageSnapshotDeletePage(ctx, s, secondBase, p); err != nil { - t.Fatal(err) + stage(firstBase) + s.h.Gen = firstBase + 2 // a cleaning pass + for _, pg := range pages { + ref, _ := pg.Ref() + rel, _ := ref.Path() + delete(s.objs, s.full(rel)) } - st := &staleWriteLandsBeforeAdoption{chainStore: s, rel: rel, staleTag: deleteIntentWriter(firstBase, c.Ref)} - _, publishErr := RunDeleteSnapshotWithIntent(ctx, st, secondBase, c) + secondBase = s.h.Gen + stage(secondBase) + hit, _ = pages[0].Ref() // the only page, or the tail: the later page visited + for _, pg := range pages { + if ref, _ := pg.Ref(); ref != hit { + other, _, _ = s.ReadListPage(ctx, ref) + } + } + if other == nil { + other = []byte(`{"pages":1,"entries":["not this page"]}`) + } + return s, c, hit, other, firstBase, secondBase +} - if !st.landed { - t.Fatal("fixture: the stale update never landed (the adoption did not Stat the page)") - } - if s.h.List != nil { - t.Fatalf("the intent was published over a page whose data was freed: HEAD list %+v (publish: %v)", s.h.List, publishErr) - } - if publishErr == nil { - t.Fatal("publishing over a page whose data was freed answered nil, want a refusal") +// The second run of a snapshot delete must not publish an intent whose page +// lost its data, or holds other bytes, after a stalled update from the first +// run landed between the second run's read of the page and its adoption. +// The refusal comes after the adoption (the page carries this run's tag), is +// a precondition, and writes nothing to HEAD: the snapshot stays. The same +// schedule with the page's bytes intact publishes. +func TestASnapshotDeleteIsNotPublishedOverAPageWhoseDataWasFreed(t *testing.T) { + for _, tc := range []struct { + name string + mode string + twoPages bool + publish bool + }{ + {"freed, one page", "freed", false, false}, + {"other bytes, one page", "wrong", false, false}, + {"freed, the later of two pages", "freed", true, false}, + {"other bytes, the later of two pages", "wrong", true, false}, + {"intact bytes after the stale tag, one page", "valid", false, true}, + {"intact bytes after the stale tag, two pages", "valid", true, true}, + } { + t.Run(tc.name, func(t *testing.T) { + ctx := context.Background() + s, c, hit, other, firstBase, secondBase := rerunFixture(t, tc.twoPages) + rel, err := hit.Path() + if err != nil { + t.Fatal(err) + } + st := &staleUpdateBeforeAdoption{chainStore: s, rel: rel, staleTag: deleteIntentWriter(firstBase, hit), mode: tc.mode, wrong: other} + updates := s.updates + _, publishErr := RunDeleteSnapshotWithIntent(ctx, st, secondBase, c) + if !st.landed { + t.Fatal("fixture: the stale update never landed (the adoption did not Stat the page)") + } + if tc.publish { + if publishErr != nil || s.h.List == nil { + t.Fatalf("an intact page after the stale tag did not publish: %v, list %+v", publishErr, s.h.List) + } + if _, kept := s.h.Snapshots["daily"]; kept { + t.Fatal("published, but the snapshot is still named") + } + return + } + if !errors.Is(publishErr, ErrPrecondition) { + t.Fatalf("publishing over a page whose data changed answered %v, want ErrPrecondition", publishErr) + } + if s.h.List != nil || s.updates != updates { + t.Fatalf("the refusal wrote HEAD: list %+v, %d update(s)", s.h.List, s.updates-updates) + } + if snap, kept := s.h.Snapshots["daily"]; !kept || snap.Gen != 4 { + t.Fatalf("the refusal did not keep the snapshot: %+v (kept %v)", snap, kept) + } + if meta, found, _ := s.Stat(ctx, rel); !found || meta.Session != deleteIntentWriter(secondBase, hit) { + t.Fatalf("the refusal came before the adoption: the page's tag is %+v, want this run's %q", meta, deleteIntentWriter(secondBase, hit)) + } + }) } } diff --git a/seaweed-block/core/frontend/chunkstore/layout_change_meta_recreated_test.go b/seaweed-block/core/frontend/chunkstore/layout_change_meta_recreated_test.go new file mode 100644 index 0000000000..09278fc5ec --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/layout_change_meta_recreated_test.go @@ -0,0 +1,104 @@ +package chunkstore + +import ( + "bytes" + "context" + "sync" + "testing" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" +) + +// betweenLookupAndUpdate runs before, once, ahead of the first UpdateEntry: +// what other writers do while a stale one is between its lookup and its +// conditional update. +type betweenLookupAndUpdate struct { + Filer + once sync.Once + before func() +} + +func (f *betweenLookupAndUpdate) UpdateEntry(ctx context.Context, dir string, e *filerpb.Entry, expected map[string][]byte) error { + f.once.Do(f.before) + return f.Filer.UpdateEntry(ctx, dir, e, expected) +} + +// Witness of a known store behavior, kept so it stays visible: a stale +// metadata change (a delete-intent page's adoption by an executor that paused +// between its lookup and its update) writes the entry it looked up over an +// object that was deleted and created again with the same tags in between. +// The update is conditional only on the tags, so it passes and puts the +// deleted object's chunk reference on the new entry; on a real filer the new +// entry's chunk is then freed. Snapshot delete publication does not rely on +// this write being refused: it reads each intent page again after adopting it +// (layout TestASnapshotDeleteIsNotPublishedOverAPageWhoseDataWasFreed). When +// metadata changes are fenced against re-created objects, this test flips: +// assert the re-created object's chunk and ErrPrecondition instead. +func TestAStaleMetadataChangeOverwritesARecreatedObject(t *testing.T) { + ctx := context.Background() + f, b := newFakeFiler(), newFakeBlobs() + var id layout.VolumeID + for i := range id { + id[i] = 0x30 + byte(i) + } + others, err := NewLayoutStore(f, b, "/vol", id) + if err != nil { + t.Fatal(err) + } + hooked := &betweenLookupAndUpdate{Filer: f} + stale, err := NewLayoutStore(hooked, b, "/vol", id) + if err != nil { + t.Fatal(err) + } + data := bytes.Repeat([]byte{0x5a}, 4096) + rel := layout.NameChunk(1, data).Path() + dir, name, err := others.object(rel) + if err != nil { + t.Fatal(err) + } + fidOf := func() string { + t.Helper() + e, err := f.LookupEntry(ctx, dir, name) + if err != nil || len(e.Chunks) != 1 { + t.Fatalf("lookup %s: %+v %v", rel, e, err) + } + return e.Chunks[0].FileId + } + + if err := others.Create(ctx, rel, data, "producer-1"); err != nil { + t.Fatal(err) + } + first := fidOf() + meta, found, err := others.Stat(ctx, rel) + if err != nil || !found { + t.Fatalf("stat: %v %v", found, err) + } + var second string + hooked.before = func() { + // While the stale writer is between lookup and update: a cleaner + // marks and deletes the object, and another executor of the same + // operation creates it again with the same producer tag. + if err := others.Mark(ctx, rel, meta, "clean-1"); err != nil { + t.Errorf("mark: %v", err) + } + if err := others.DeleteMarked(ctx, rel, "clean-1"); err != nil { + t.Errorf("delete: %v", err) + } + if err := others.Create(ctx, rel, data, "producer-1"); err != nil { + t.Errorf("re-create: %v", err) + } + second = fidOf() + } + reuseErr := stale.Reuse(ctx, rel, meta, "writer-1") + + if second == "" || second == first { + t.Fatalf("fixture: the object was not re-created with a new chunk (first %s, second %s)", first, second) + } + if reuseErr != nil { + t.Fatalf("the stale update was refused (%v): metadata changes are now fenced, flip this witness", reuseErr) + } + if got := fidOf(); got != first { + t.Fatalf("the stale update left chunk %s, want the deleted object's %s written over the re-created object's %s", got, first, second) + } +} diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 7fef04e4c2..00a70c72d9 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -1496,7 +1496,7 @@ Notes: | `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 | `core/frontend/chunkstore/layout/delete_intent.go` `RunConsumeSnapshotDeleteIntent`; `core/frontend/chunkstore/layout/remove.go` `Cleaner.removePlanned`; `core/frontend/chunkstore/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 | ACTIVE | | `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 | -| `INV-SNAPSHOT-DELETE-ADOPT-002` | After adopting an intent page under its own tag, publication reads the page again and authenticates it; a page whose data changed or vanished between the first read and the adoption refuses the publication, and a new request id writes new pages. | M9 delete intent publication | `delete_intent.go` `RunDeleteSnapshotWithIntent`, `readListPage` | `TestASnapshotDeleteIsNotPublishedOverAPageWhoseDataWasFreed` (`core/frontend/chunkstore/layout/delete_intent_reread_test.go`) | MetaABA r1 `PublishedReadable` (`safe_reread_only`; the run stays refused: `mut_reread_only_page`) | ACTIVE | +| `INV-SNAPSHOT-DELETE-ADOPT-002` | After adopting an intent page under its own tag, publication reads the page again and authenticates it; a page whose data changed or vanished between the first read and the adoption refuses the publication, and a new request id writes new pages. | M9 delete intent publication | `delete_intent.go` `RunDeleteSnapshotWithIntent`, `readListPage` | `TestASnapshotDeleteIsNotPublishedOverAPageWhoseDataWasFreed` (`core/frontend/chunkstore/layout/delete_intent_reread_test.go`); store witness `TestAStaleMetadataChangeOverwritesARecreatedObject` (`core/frontend/chunkstore/layout_change_meta_recreated_test.go`) | MetaABA r1, checked outside the repository: `PublishedReadable` (`safe_reread_only`; the run stays refused: `mut_reread_only_page`) | ACTIVE | The snapshot-delete consumer and list-page retirement above are reachable through holder maintenance and covered by Go assertions. Their ACTIVE status describes that reachability and test coverage, not fresh Linux, composed-operation or release qualification. Cut and upload-intent producers remain deferred; their dormant publication rows are not activated by this consumer slice.