diff --git a/seaweed-block/core/frontend/chunkstore/layout/adopt_test.go b/seaweed-block/core/frontend/chunkstore/layout/adopt_test.go new file mode 100644 index 0000000000..6cdd8283ea --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/layout/adopt_test.go @@ -0,0 +1,130 @@ +package layout + +import ( + "context" + "errors" + "testing" +) + +// adoptObjects is one entry whose metadata a test controls; each Reuse +// is counted and may be made to lose its race (the entry changes first). +type adoptObjects struct { + meta ObjectMeta + found bool + statErr error + reuses int + // beforeReuse, if set, runs before each Reuse's condition is checked: + // a change it makes is what the Reuse finds. + beforeReuse func(s *adoptObjects) +} + +func (s *adoptObjects) Stat(ctx context.Context, rel string) (ObjectMeta, bool, error) { + if err := ctx.Err(); err != nil { + return ObjectMeta{}, false, err + } + return s.meta, s.found, s.statErr +} + +func (s *adoptObjects) Reuse(ctx context.Context, rel string, expect ObjectMeta, session string) error { + s.reuses++ + if s.beforeReuse != nil { + s.beforeReuse(s) + } + if !s.found || s.meta != expect { + return ErrPrecondition + } + s.meta.Session, s.meta.Mark = session, "" + return nil +} + +func (s *adoptObjects) Create(context.Context, string, []byte, string) error { return ErrExists } +func (s *adoptObjects) Mark(context.Context, string, ObjectMeta, string) error { + return ErrPrecondition +} +func (s *adoptObjects) DeleteMarked(context.Context, string, string) error { return nil } +func (s *adoptObjects) DeleteOfVolume(context.Context, string, VolumeID) error { + return nil +} + +var ( + adoptVol = VolumeID{0x11} + otherVol = VolumeID{0x22} + adoptRel = "pool/0/0-x" + adoptOther = "s-earlier" + adoptNow = "s-now" +) + +// Another volume's entry is never adopted and never re-stamped, even when it +// already names the committing session. +func TestAnotherVolumesEntryIsNeverAdopted(t *testing.T) { + for _, session := range []string{adoptOther, adoptNow} { + s := &adoptObjects{found: true, meta: ObjectMeta{Session: session, Volume: otherVol}} + ok, err := ownedOrAdopted(context.Background(), s, adoptRel, adoptNow, adoptVol) + if ok || err != nil || s.reuses != 0 { + t.Fatalf("another volume's entry stamped %q: owned=%t err=%v reuses=%d; want not owned, no error, no Reuse", session, ok, err, s.reuses) + } + } +} + +// A Reuse that loses its race reads again; the next round adopts the entry +// as it now is and clears the latest mark. +func TestAnAdoptionThatLosesItsRaceReadsAgainAndClearsTheLatestMark(t *testing.T) { + s := &adoptObjects{found: true, meta: ObjectMeta{Session: adoptOther, Volume: adoptVol}} + first := true + s.beforeReuse = func(s *adoptObjects) { + if first { // a cleaning marks the entry between the Stat and the Reuse + first = false + s.meta.Mark = "clean-late" + } + } + ok, err := ownedOrAdopted(context.Background(), s, adoptRel, adoptNow, adoptVol) + if !ok || err != nil { + t.Fatalf("adoption after a lost race: owned=%t err=%v; want owned", ok, err) + } + if s.reuses != 2 || s.meta.Session != adoptNow || s.meta.Mark != "" { + t.Fatalf("after the retry: reuses=%d meta=%+v; want 2 Reuses, the entry stamped %q and unmarked", s.reuses, s.meta, adoptNow) + } +} + +// An entry deleted between the Stat and the Reuse is not owned: the commit +// refuses it (the cut starts over) instead of naming an absent object. +func TestAnEntryDeletedDuringTheAdoptionIsNotOwned(t *testing.T) { + s := &adoptObjects{found: true, meta: ObjectMeta{Session: adoptOther, Mark: "clean", Volume: adoptVol}} + s.beforeReuse = func(s *adoptObjects) { s.found = false } // the cleaning's delete wins + ok, err := ownedOrAdopted(context.Background(), s, adoptRel, adoptNow, adoptVol) + if ok || err != nil { + t.Fatalf("an entry deleted during the adoption: owned=%t err=%v; want not owned, no error", ok, err) + } +} + +// Conflicts that never end stop after the bounded rounds with an error. +func TestAnAdoptionThatKeepsLosingStopsAfterItsRounds(t *testing.T) { + s := &adoptObjects{found: true, meta: ObjectMeta{Session: adoptOther, Volume: adoptVol}} + n := 0 + s.beforeReuse = func(s *adoptObjects) { n++; s.meta.Mark = "m" + string(rune('a'+n)) } + ok, err := ownedOrAdopted(context.Background(), s, adoptRel, adoptNow, adoptVol) + if ok || err == nil || s.reuses != maxEnsureRounds { + t.Fatalf("endless conflicts: owned=%t err=%v reuses=%d; want an error after %d Reuses", ok, err, s.reuses, maxEnsureRounds) + } +} + +// A cancelled check returns its error and adopts nothing. +func TestACancelledAdoptionAdoptsNothing(t *testing.T) { + s := &adoptObjects{found: true, meta: ObjectMeta{Session: adoptOther, Volume: adoptVol}} + ctx, cancel := context.WithCancel(context.Background()) + cancel() + err := allOwnedBySession(ctx, s, []string{adoptRel}, adoptNow, adoptVol, true) + if !errors.Is(err, context.Canceled) || s.reuses != 0 || s.meta.Session != adoptOther { + t.Fatalf("a cancelled check: err=%v reuses=%d meta=%+v; want context.Canceled, nothing adopted", err, s.reuses, s.meta) + } +} + +// The HEAD step's own lookups never adopt: an entry of another session is +// not prepared there, as before. +func TestTheHeadStepsLookupsDoNotAdopt(t *testing.T) { + s := &adoptObjects{found: true, meta: ObjectMeta{Session: adoptOther, Volume: adoptVol}} + err := allOwnedBySession(context.Background(), s, []string{adoptRel}, adoptNow, adoptVol, false) + if !errors.Is(err, ErrNotPrepared) || s.reuses != 0 { + t.Fatalf("lookups without adoption: err=%v reuses=%d; want ErrNotPrepared and no Reuse", err, s.reuses) + } +} diff --git a/seaweed-block/core/frontend/chunkstore/layout/commit.go b/seaweed-block/core/frontend/chunkstore/layout/commit.go index 829c58abe4..d202b3783d 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/commit.go +++ b/seaweed-block/core/frontend/chunkstore/layout/commit.go @@ -263,7 +263,7 @@ func RunCommit(ctx context.Context, st HeadStore, os ObjectStore, vol string, me return Head{}, err } return runTransition(ctx, st, cause, func(h Head) (Head, bool, error) { - return commitChecked(ctx, h, os, vol, me, req, plan, !req.ObjectsChecked) + return commitChecked(ctx, h, os, vol, me, req, plan, !req.ObjectsChecked, false) }) } @@ -284,20 +284,30 @@ func (req CommitRequest) planned(vol string, lookups bool) (CommitPlan, error) { // its last upload, with the caller's budget rather than the HEAD update's: // no cleaning can begin while the session is open, so what it found holds // until that session's commit. A commit already applied passes. +// +// It adopts what an earlier session of this volume wrote: an object present +// under its name, of h's volume, but stamped by another session or marked, +// is re-stamped to req.Session by one conditional update (as EnsureObject +// reuses an object it finds), so a cut whose upload outlived its session +// (a request that ran out of time and aborted it) commits it without +// sending it again. The name is the content's hash and an entry exists only +// once complete, so the bytes are the ones the commit names. An object of +// another volume, or absent, is refused as before. func CheckCommitObjects(ctx context.Context, h Head, os ObjectStore, vol string, me HolderID, req CommitRequest) error { plan, err := req.planned(vol, true) if err != nil { return err } - _, _, err = commitChecked(ctx, h, os, vol, me, req, plan, true) + _, _, err = commitChecked(ctx, h, os, vol, me, req, plan, true, true) return err } // commitChecked is the commit of req against h after its checks; lookups // says whether the object lookups run. Apart from those lookups, its work // does not grow with the chunk count: everything computed from the request -// alone is in plan. -func commitChecked(ctx context.Context, h Head, os ObjectStore, vol string, me HolderID, req CommitRequest, plan CommitPlan, lookups bool) (Head, bool, error) { +// alone is in plan. adopt re-stamps this volume's objects written by another +// session (CheckCommitObjects only; never inside the HEAD step). +func commitChecked(ctx context.Context, h Head, os ObjectStore, vol string, me HolderID, req CommitRequest, plan CommitPlan, lookups, adopt bool) (Head, bool, error) { if next, changed, err := h.Commit(me, req.Session, plan.root, req.Position, req.Snapshot, req.Meta, req.State); err != nil || !changed { return next, changed, err // refused, or already applied: no lookups } @@ -321,7 +331,7 @@ func commitChecked(ctx context.Context, h Head, os ObjectStore, vol string, me H // volume. Every production commit is checked first (fixed-limits // table, the unchecked-commit row, and its caller guard); a new // caller must check first too. - if err := allOwnedBySession(ctx, os, plan.rels, req.Session); err != nil { + if err := allOwnedBySession(ctx, os, plan.rels, req.Session, h.VolumeID, adopt); err != nil { return Head{}, false, err } } @@ -335,14 +345,16 @@ func commitChecked(ctx context.Context, h Head, os ObjectStore, vol string, me H const commitVerifyParallel = 32 // allOwnedBySession checks that every rel exists, is written by session and -// is unmarked, with at most commitVerifyParallel lookups in flight. It is +// is unmarked (with adopt, after re-stamping one of volume written by +// another session or marked: ownedOrAdopted), with at most +// commitVerifyParallel lookups in flight. It is // all-or-nothing, like a serial check: the first failing rel in rels order // decides the error (a lookup error before a "not prepared"), so the result // does not depend on which lookup finished first. Once any lookup fails no // new one starts: lookups start in rels order, so every rel before a failure // has already started and is waited for, and the first failure in order is // still the one reported. -func allOwnedBySession(ctx context.Context, os ObjectStore, rels []string, session string) error { +func allOwnedBySession(ctx context.Context, os ObjectStore, rels []string, session string, volume VolumeID, adopt bool) error { type outcome struct { done bool ok bool @@ -362,7 +374,13 @@ func allOwnedBySession(ctx context.Context, os ObjectStore, rels []string, sessi go func(i int, rel string) { defer wg.Done() defer func() { <-sem }() - ok, err := ownedBySession(ctx, os, rel, session) + var ok bool + var err error + if adopt { + ok, err = ownedOrAdopted(ctx, os, rel, session, volume) + } else { + ok, err = ownedBySession(ctx, os, rel, session) + } got[i] = outcome{done: true, ok: ok, err: err} if err != nil || !ok { failed.Store(true) diff --git a/seaweed-block/core/frontend/chunkstore/layout/objects.go b/seaweed-block/core/frontend/chunkstore/layout/objects.go index 78bf421f70..1ccc321d2f 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/objects.go +++ b/seaweed-block/core/frontend/chunkstore/layout/objects.go @@ -125,6 +125,36 @@ func PrepareRoot(ctx context.Context, os ObjectStore, root Root, segs map[SegNam // ownedBySession reports whether rel exists, carries session as its writer // and is unmarked: an object a commit of that session may name. +// ownedOrAdopted is ownedBySession that first adopts rel when it is an +// object of volume written by another session, or marked: it re-stamps it to +// session (Reuse, conditional on the metadata it read; a lost race reads +// again), which also clears a cleaning's mark, so the cleaning's conditional +// delete then removes nothing. An absent rel, or one of another volume, is +// not owned. +func ownedOrAdopted(ctx context.Context, os ObjectStore, rel, session string, volume VolumeID) (bool, error) { + for round := 0; round < maxEnsureRounds; round++ { + meta, found, err := os.Stat(ctx, rel) + if err != nil { + return false, err + } + switch { + case !found, meta.Volume != volume: + return false, nil // absent, or another volume's: never ours + case meta.Session == session && meta.Mark == "": + return true, nil + } + err = os.Reuse(ctx, rel, meta, session) + if errors.Is(err, ErrPrecondition) { + continue + } + if err != nil { + return false, err + } + return true, nil + } + return false, fmt.Errorf("layout: %s kept moving under %d attempts", rel, maxEnsureRounds) +} + func ownedBySession(ctx context.Context, os ObjectStore, rel, session string) (bool, error) { meta, found, err := os.Stat(ctx, rel) if err != nil { diff --git a/seaweed-block/core/frontend/chunkstore/layout_adopt_own_objects_test.go b/seaweed-block/core/frontend/chunkstore/layout_adopt_own_objects_test.go new file mode 100644 index 0000000000..67722f6929 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/layout_adopt_own_objects_test.go @@ -0,0 +1,236 @@ +package chunkstore + +import ( + "context" + "errors" + "path" + "path/filepath" + "strings" + "sync/atomic" + "testing" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// timeoutOnceRemote is the holder's layout remote whose first commit check +// runs out of time, as a request whose budget ended after its uploads. +type timeoutOnceRemote struct { + *LayoutRemote + failed atomic.Bool +} + +func (r *timeoutOnceRemote) CheckCommit(ctx context.Context, e storage.ChunkHeadVersion, n storage.ChunkHead) error { + if r.failed.CompareAndSwap(false, true) { + return context.DeadlineExceeded + } + return r.LayoutRemote.CheckCommit(ctx, e, n) +} + +// A cut whose request ran out of time after its uploads, and whose session +// that request's settlement then aborted, is completed by the next request: +// it reuses the staged uploads (written in the aborted session) and its +// commit adopts them into the new session, without sending them again. +func TestARerunAfterATimedOutRequestCommitsTheUploadsOfItsAbortedSession(t *testing.T) { + ctx := context.Background() + lh := newLayoutHost(t) + s, err := storage.CreateWALStoreWithOptions(filepath.Join(lh.dir, "a"), lrBlocks, 4096, storage.WALStoreOptions{ChunkBlocks: lrChunkBlocks}) + if err != nil { + t.Fatal(err) + } + if _, err := s.Recover(); err != nil { + t.Fatal(err) + } + inner, err := NewLayoutRemote(lh.cat, lh.v, lh.me) + if err != nil { + t.Fatal(err) + } + r := &timeoutOnceRemote{LayoutRemote: inner} + l, err := storage.AttachChunkLayer(s, r, storage.ChunkLayerConfig{ChunkBlocks: lrChunkBlocks, Epoch: lh.me.Epoch, Holder: lh.me.Holder, FreshFromHead: true}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = l.Close(); _ = s.Close() }) + writeSync(t, s, map[uint32][]byte{0: block(7), lrChunkBlocks: block(8)}) + if _, err := l.Cut(ctx); !errors.Is(err, context.DeadlineExceeded) { + t.Fatalf("setup: the first request did not run out of time after its uploads: %v", err) + } + // The request's settlement aborts its session on HEAD; the engine keeps + // what it staged. + if outcome, err := inner.AbortOpenSession(ctx); err != nil || outcome != "aborted" { + t.Fatalf("setup: settling the timed-out request: %q, %v", outcome, err) + } + blobs := lh.cat.b.(*fakeBlobs) + putsBefore, _, _ := blobs.counts() + res, err := l.Cut(ctx) + if err != nil { + t.Fatalf("the rerun after a timed-out request: %v; want its commit to adopt the aborted session's uploads", err) + } + if res.H == 0 || len(res.Head.Chunks) != 2 { + t.Fatalf("the rerun published %+v; want chunks 0 and 1 at the written position", res) + } + // Nothing unchanged is staged or uploaded again: the rerun commits + // the two chunks the timed-out request staged. + if st := res.Stats; st.UploadedChunks != 0 || st.StagedChunks != 0 || st.StagedChunksUsed != 2 { + t.Fatalf("the rerun uploaded %d and staged %d chunks, used %d staged; want 0, 0 and 2", st.UploadedChunks, st.StagedChunks, st.StagedChunksUsed) + } + h := lh.head() + if h.Current == nil || h.Position != res.H { + t.Fatalf("HEAD after the rerun: %+v", h) + } + // The rerun sends its root and segment; chunk 0 is not sent again. + if putsAfter, _, _ := blobs.counts(); putsAfter-putsBefore != 2 { + t.Fatalf("the rerun sent %d objects; want 2 (its root and segment), chunks 0 and 1 adopted, not sent again", putsAfter-putsBefore) + } + lh.readBack("reader", map[uint32][]byte{0: block(7), lrChunkBlocks: block(8)}) +} + +// timedOutCut runs a holder whose first request uploads chunk 0 and runs out +// of time, then settles that request (its session aborted on HEAD, the +// engine notified). It returns the layer, ready for the rerun, and the +// chunk's entry path and relative name. +func timedOutCut(t *testing.T, lh *layoutHost) (storage.ChunkLayer, *LayoutRemote, *LayoutStore, string, string) { + t.Helper() + ctx := context.Background() + s, err := storage.CreateWALStoreWithOptions(filepath.Join(lh.dir, "a"), lrBlocks, 4096, storage.WALStoreOptions{ChunkBlocks: lrChunkBlocks}) + if err != nil { + t.Fatal(err) + } + if _, err := s.Recover(); err != nil { + t.Fatal(err) + } + inner, err := NewLayoutRemote(lh.cat, lh.v, lh.me) + if err != nil { + t.Fatal(err) + } + l, err := storage.AttachChunkLayer(s, &timeoutOnceRemote{LayoutRemote: inner}, storage.ChunkLayerConfig{ChunkBlocks: lrChunkBlocks, Epoch: lh.me.Epoch, Holder: lh.me.Holder, FreshFromHead: true}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = l.Close(); _ = s.Close() }) + writeSync(t, s, map[uint32][]byte{0: block(7)}) + if _, err := l.Cut(ctx); !errors.Is(err, context.DeadlineExceeded) { + t.Fatalf("setup: the first request did not run out of time after its uploads: %v", err) + } + if outcome, err := inner.AbortOpenSession(ctx); err != nil || outcome != "aborted" { + t.Fatalf("setup: settling the timed-out request: %q, %v", outcome, err) + } + st, err := lh.cat.Store(lh.v) + if err != nil { + t.Fatal(err) + } + lh.ff.mu.Lock() + defer lh.ff.mu.Unlock() + for p := range lh.ff.entries { + if i := strings.Index(p, "/pool/0/"); i >= 0 { + return l, inner, st, p, p[i+1:] + } + } + t.Fatal("setup: chunk 0 was not uploaded") + return nil, nil, nil, "", "" +} + +// An object at the chunk's name stamped as another volume's is never +// adopted: the rerun's commit is refused as before, and the entry keeps its +// writer and mark. +func TestTheRerunsCommitDoesNotAdoptAnotherVolumesObject(t *testing.T) { + ctx := context.Background() + lh := newLayoutHost(t) + l, _, _, path, _ := timedOutCut(t, lh) + lh.ff.mu.Lock() + ext := lh.ff.entries[path].Extended + ext[layoutVolume] = []byte(layout.VolumeID{0xEE}.String()) + session, mark := string(ext[layoutSession]), string(ext[layoutMark]) + lh.ff.mu.Unlock() + if _, err := l.Cut(ctx); err == nil { + t.Fatal("the rerun committed over another volume's object; want it refused") + } + lh.ff.mu.Lock() + ext = lh.ff.entries[path].Extended + gotSession, gotMark := string(ext[layoutSession]), string(ext[layoutMark]) + lh.ff.mu.Unlock() + if gotSession != session || gotMark != mark { + t.Fatalf("another volume's object was re-stamped: session %q mark %q, was %q %q", gotSession, gotMark, session, mark) + } + if h := lh.head(); h.Current != nil { + t.Fatalf("HEAD names a root after the refused rerun: %+v", h) + } +} + +// A cleaning that marked the object before the rerun loses the race: the +// adoption clears its mark, so the cleaning's delete, conditional on that +// mark, removes nothing, and the committed image still reads back. +func TestACleaningRacingTheAdoptionKeepsTheObject(t *testing.T) { + ctx := context.Background() + lh := newLayoutHost(t) + l, r, st, _, rel := timedOutCut(t, lh) + meta, found, err := st.Stat(ctx, rel) + if err != nil || !found { + t.Fatalf("setup: chunk 0's entry: %+v %t %v", meta, found, err) + } + const mark = "clean-race" + if err := st.Mark(ctx, rel, meta, mark); err != nil { + t.Fatal(err) + } + if _, err := l.Cut(ctx); err != nil { + t.Fatalf("the rerun over a marked object of this volume: %v; want it adopted", err) + } + // The cleaning's delete is conditional on the entry as it marked it: + // after the adoption it is refused and removes nothing. + if err := st.DeleteMarked(ctx, rel, mark); !errors.Is(err, layout.ErrPrecondition) { + t.Fatalf("the cleaning's delete after the adoption: %v; want refused (precondition)", err) + } + if got, found, err := st.Stat(ctx, rel); err != nil || !found || got.Mark != "" { + t.Fatalf("after the cleaning's delete: %+v found=%t %v; want the adopted object kept, unmarked", got, found, err) + } + // A cleaning pass on the production store never marks an object the + // committed root names: the adopted chunk stays, unmarked. + if err := lh.cat.f.CreateEntry(ctx, path.Join(lh.cat.base, lh.v.Dir(), layout.PoolDir), &filerpb.Entry{Name: "0", IsDirectory: true}, false); err != nil { + t.Fatal(err) + } + if err := r.Clean(ctx, func(ctx context.Context, me layout.HolderID, session string) error { + _, err := lh.cat.RemoveUnreachableAll(ctx, lh.v, me, session) + return err + }); err != nil { + t.Fatalf("clean: %v", err) + } + if got, found, err := st.Stat(ctx, rel); err != nil || !found || got.Mark != "" { + t.Fatalf("after a cleaning pass: %+v found=%t %v; want the root-named chunk kept, unmarked", got, found, err) + } + lh.readBack("reader", map[uint32][]byte{0: block(7)}) +} + +// Between two requests of one cut HEAD is idle, and the holder's cleaning +// could remove an upload no root names yet. While an upload awaits its +// commit the cleaning is refused busy; once the cut commits it runs, and +// the committed chunk stays. +func TestTheCleaningWaitsForAnUploadNotYetCommitted(t *testing.T) { + ctx := context.Background() + lh := newLayoutHost(t) + l, r, st, _, rel := timedOutCut(t, lh) + if err := lh.cat.f.CreateEntry(ctx, path.Join(lh.cat.base, lh.v.Dir(), layout.PoolDir), &filerpb.Entry{Name: "0", IsDirectory: true}, false); err != nil { + t.Fatal(err) + } + clean := func() error { + return r.Clean(ctx, func(ctx context.Context, me layout.HolderID, session string) error { + _, err := lh.cat.RemoveUnreachableAll(ctx, lh.v, me, session) + return err + }) + } + if err := clean(); !errors.Is(err, layout.ErrBusy) { + t.Fatalf("a cleaning while an upload awaits its commit: %v; want refused busy", err) + } + if _, found, err := st.Stat(ctx, rel); err != nil || !found { + t.Fatalf("the staged upload after the refused cleaning: found=%t %v", found, err) + } + if _, err := l.Cut(ctx); err != nil { + t.Fatalf("the rerun: %v", err) + } + if err := clean(); err != nil { + t.Fatalf("a cleaning after the commit: %v", err) + } + if got, found, err := st.Stat(ctx, rel); err != nil || !found || got.Mark != "" { + t.Fatalf("the committed chunk after the cleaning: %+v found=%t %v", got, found, err) + } +} diff --git a/seaweed-block/core/frontend/chunkstore/layout_remote.go b/seaweed-block/core/frontend/chunkstore/layout_remote.go index 06d8a097c5..84d703c6ed 100644 --- a/seaweed-block/core/frontend/chunkstore/layout_remote.go +++ b/seaweed-block/core/frontend/chunkstore/layout_remote.go @@ -59,6 +59,9 @@ type LayoutRemote struct { // abandoned is set by the engine when a cut ends without a commit // (Abort): the next call drops the session and the pending name. abandoned atomic.Bool + // dropped is set by the engine's Abort: it dropped its staged uploads, + // so none of them waits for a commit any more (uncommitted). + dropped atomic.Bool // checked is the commit whose object check passed (CheckCommit), in // that open session: the expected version and next HEAD it was asked // for, and its prepared request (manifests, root and segments written, @@ -82,6 +85,10 @@ type LayoutRemote struct { cleanCancel context.CancelFunc cleanDone chan struct{} lastCommit layout.Head + // uncommitted: an upload since the last cut's commit. The cleaning waits + // for that commit: between two requests of one long cut HEAD is idle, and + // a staged upload no root names yet must stay for the commit to adopt. + uncommitted bool } type pendingSnapshot struct { @@ -202,23 +209,30 @@ func (l *LayoutRemote) openSessionLocked(ctx context.Context) error { if l.session != "" { return nil } + _, err := l.beginSessionLocked(ctx) + return err +} + +// beginSessionLocked opens a new session (no session is open) and returns +// the HEAD its begin wrote. +func (l *LayoutRemote) beginSessionLocked(ctx context.Context) (layout.Head, error) { if err := l.stopCleaningLocked(ctx); err != nil { - return err + return layout.Head{}, err } if _, err := l.rollBackLocked(ctx); err != nil { - return err + return layout.Head{}, err } var b [16]byte if _, err := rand.Read(b[:]); err != nil { - return err + return layout.Head{}, err } s := "s-" + hex.EncodeToString(b[:]) h, err := layout.RunBegin(ctx, l.st, l.me, s) if err != nil { - return layoutRemoteErr(err) + return layout.Head{}, layoutRemoteErr(err) } l.session, l.ownGen = s, h.Gen - return nil + return h, nil } // rollBackLocked rolls back a session of this holder that HEAD shows open @@ -282,10 +296,14 @@ func (l *LayoutRemote) PutPaced(ctx context.Context, key string, data []byte, be return err } session := l.session + // An upload of this session starts: the cleaning waits for the commit + // that names it (or the engine dropping it), even if the session ends + // during the send. + l.uncommitted = true l.mu.Unlock() // Pacing and payload I/O do not serialize the upload workers or HEAD // reads. Keep this upload's session even if it ends during the send: - // commit checks reject objects belonging to that ended session. + // the next commit adopts an object of an ended session of this volume. return layoutRemoteErr(layout.EnsureObjectPaced(ctx, l.st, ref.Chunk.Path(), data, session, beforeSend)) } @@ -471,8 +489,13 @@ func (l *LayoutRemote) prepareCommitLocked(ctx context.Context, expected storage if err != nil { return layout.Head{}, layout.CommitRequest{}, false, err } - if err := l.openSessionLocked(ctx); err != nil { - return layout.Head{}, layout.CommitRequest{}, false, err + if l.session == "" { + // No upload of this cut opened its session (every chunk was staged + // in an earlier one, which a timed-out request aborted): open it + // here and check the commit against the HEAD the begin wrote. + if h, err = l.beginSessionLocked(ctx); err != nil { + return layout.Head{}, layout.CommitRequest{}, false, err + } } if err := l.writeRootLocked(ctx, nextM); err != nil { return layout.Head{}, layout.CommitRequest{}, false, err @@ -666,7 +689,7 @@ func (l *LayoutRemote) CASHead(ctx context.Context, expected storage.ChunkHeadVe // which also re-derives this session from HEAD (syncSessionLocked). return 0, layoutRemoteErr(err) } - l.session, l.pending, l.lastCommit = "", nil, got + l.session, l.pending, l.lastCommit, l.uncommitted = "", nil, got, false l.ownGen, l.visible, l.seen = got.Gen, got.Gen, imageOf(got) l.clearCheckedLocked() // the session is closed: its check covers nothing more return got.Gen, nil @@ -906,7 +929,9 @@ func (l *LayoutRemote) LastCommit() layout.Head { func (l *LayoutRemote) Clean(ctx context.Context, run func(ctx context.Context, me layout.HolderID, session string) error) error { l.mu.Lock() l.takeAbandonLocked() - if l.session != "" || l.cleaning != "" { + // An upload not yet named by a commit (a cut over several requests, + // HEAD idle between them) holds the cleaning until that commit. + if l.session != "" || l.cleaning != "" || l.uncommitted { l.mu.Unlock() return layout.ErrBusy } @@ -994,18 +1019,25 @@ func imageOf(h layout.Head) imageTuple { return t } -// Abort is the engine's notice that a cut ended without a commit. It -// never blocks: the next call drops the session (HEAD's read then rolls -// it back) and the pending snapshot name, which never rides onto a later -// cut. -func (l *LayoutRemote) Abort() { l.abandoned.Store(true) } +// Abort is the engine's notice that a cut ended without a commit and its +// staged uploads are dropped. It never blocks: the next call drops the +// session (HEAD's read then rolls it back) and the pending snapshot name, +// which never rides onto a later cut, and releases the cleaning's hold on +// those uploads. +func (l *LayoutRemote) Abort() { + l.dropped.Store(true) + l.abandoned.Store(true) +} func (l *LayoutRemote) takeAbandonLocked() { if l.abandoned.Swap(false) { - // Uploads the engine staged in the dropped session are caught by the - // commit (not prepared), which forces the view then. + // Uploads the engine staged in the dropped session are adopted by + // the next commit (CheckCommitObjects) while the engine keeps them. l.session, l.pending = "", nil } + if l.dropped.Swap(false) { + l.uncommitted = false // the engine dropped what it staged: nothing waits for a commit + } } // stopCleaningLocked cancels this process's open cleaning and waits for diff --git a/seaweed-block/core/frontend/chunkstore/layout_remote_owngen_census_test.go b/seaweed-block/core/frontend/chunkstore/layout_remote_owngen_census_test.go index 42f1a09c01..fd66acae8d 100644 --- a/seaweed-block/core/frontend/chunkstore/layout_remote_owngen_census_test.go +++ b/seaweed-block/core/frontend/chunkstore/layout_remote_owngen_census_test.go @@ -61,7 +61,7 @@ func TestLayoutRemoteOwnWritesCensus(t *testing.T) { // abort of a dead session or end of a dead cleaning. "Clean seen=no", "Clean seen=no", - "openSessionLocked seen=no", + "beginSessionLocked seen=no", "rollBackLocked seen=no", "rollBackLocked seen=no", // Not an own write: the view following a write by anyone else diff --git a/seaweed-block/core/frontend/chunkstore/layout_stop_session_test.go b/seaweed-block/core/frontend/chunkstore/layout_stop_session_test.go index f726ff44a4..ef079028ac 100644 --- a/seaweed-block/core/frontend/chunkstore/layout_stop_session_test.go +++ b/seaweed-block/core/frontend/chunkstore/layout_stop_session_test.go @@ -32,9 +32,11 @@ func TestLayoutRemoteSessionFieldSites(t *testing.T) { // the checked session, isCheckedLocked matches a call against it (for // prepareCommitLocked's reuse of its preparation and CheckCommit's // immediate return), and clearCheckedLocked forgets it. + // beginSessionLocked opens a session (openSessionLocked when none is + // open; prepareCommitLocked when no upload opened the cut's session). // ProbeSnapshots skips open activity // (TestLayoutSnapshotProbeSkipsOpenActivityWithoutReadingHEAD). - if !reflect.DeepEqual(fields, map[string]int{"openSessionLocked": 2, "rollBackLocked": 1, "Begin": 1, "PutPaced": 1, "CASHead": 2, "CheckCommit": 1, "clearCheckedLocked": 1, "isCheckedLocked": 3, "prepareCommitLocked": 1, "CommitPendingSnapshot": 2, "writeRootLocked": 1, "Clean": 1, "syncSessionLocked": 3, "takeAbandonLocked": 1, "ProbeSnapshots": 1}) { + if !reflect.DeepEqual(fields, map[string]int{"openSessionLocked": 1, "beginSessionLocked": 1, "rollBackLocked": 1, "Begin": 1, "PutPaced": 1, "CASHead": 2, "CheckCommit": 1, "clearCheckedLocked": 1, "isCheckedLocked": 3, "prepareCommitLocked": 2, "CommitPendingSnapshot": 2, "writeRootLocked": 1, "Clean": 1, "syncSessionLocked": 3, "takeAbandonLocked": 1, "ProbeSnapshots": 1}) { t.Fatal("session field sites changed; enumerate and probe them", fields) } } diff --git a/seaweed-block/core/frontend/durable/provider_chunk.go b/seaweed-block/core/frontend/durable/provider_chunk.go index 3234a08a4c..902c741296 100644 --- a/seaweed-block/core/frontend/durable/provider_chunk.go +++ b/seaweed-block/core/frontend/durable/provider_chunk.go @@ -1881,6 +1881,13 @@ const ( // periodic cuts restart, the stop is lifted, and the volume serves again. // Only then is resumed (if set) called. The caller holds h.attachMu. func (p *DurableProvider) resumeAfterDetach(volumeID string, h *volHandle, layer storage.ChunkLayer, cause error, resumed func()) error { + if h.layoutHead != nil { + // The layout stop settlement aborted the detach's session and found + // HEAD live at this holder's claim: the detach is reported aborted, + // so the layer must not propose it again later (its next proposal + // adopts what the detach uploaded, and a stale detach would land). + layer.ForgetAbortedDetach() + } p.mu.Lock() closed := p.closed || h.chunk != layer if !closed { diff --git a/seaweed-block/core/frontend/durable/provider_chunk_detach_rerun_test.go b/seaweed-block/core/frontend/durable/provider_chunk_detach_rerun_test.go new file mode 100644 index 0000000000..de4de46374 --- /dev/null +++ b/seaweed-block/core/frontend/durable/provider_chunk_detach_rerun_test.go @@ -0,0 +1,38 @@ +package durable_test + +import ( + "context" + "errors" + "testing" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" + "github.com/seaweedfs/seaweed-block/core/frontend/durable" +) + +// A detach whose CAS reply was lost settles as aborted (its session aborted +// on HEAD) and the volume serves again. The next detach request then +// completes on the same holder: the aborted detach is never proposed again, +// and the new one commits what the first uploaded without sending it again. +func TestADetachAfterAnAbortedDetachCompletesWithoutSendingItsChunksAgain(t *testing.T) { + remote, p, _ := detachFixture(t) + remote.set(func(r *faultRemote) { r.casMode = "lost" }) + if _, _, err := p.DetachVolume(context.Background(), "v1"); !errors.Is(err, durable.ErrDetachAborted) { + t.Fatalf("setup: detach with a lost, unapplied CAS: %v; want ErrDetachAborted", err) + } + before := remote.fixture.Blobs.Puts() + r, _, err := p.DetachVolume(context.Background(), "v1") + if err != nil { + t.Fatalf("the detach after an aborted one: %v", err) + } + if head := layoutHead(t, remote.fixture); head.State != layout.StateDetached { + t.Fatalf("HEAD after the second detach: %q; want detached", head.State) + } + if !bytesEqual(layoutHeadBlock(t, remote.fixture, 2), block(2)) { + t.Fatal("the second detach lost the block the first one uploaded") + } + // Its root and segment are new objects; the chunk is not sent again. + if sent := remote.fixture.Blobs.Puts() - before; sent > 2 { + t.Fatalf("the second detach sent %d objects; want at most its root and segment (2)", sent) + } + _ = r +} diff --git a/seaweed-block/core/frontend/durable/provider_seal_progress_test.go b/seaweed-block/core/frontend/durable/provider_seal_progress_test.go index 15c28f723b..a4fd6b58df 100644 --- a/seaweed-block/core/frontend/durable/provider_seal_progress_test.go +++ b/seaweed-block/core/frontend/durable/provider_seal_progress_test.go @@ -122,26 +122,24 @@ func TestPlainSealDeadlineRetryUploadsOnlyRemainingChunks(t *testing.T) { t.Fatalf("first attempt progress: calls=%d successful=%d bytes=%d", remote.calls, len(remote.keys), remote.bytes) } firstKeys := append([]string(nil), remote.keys...) - if _, _, err := p.DetachVolumePlain(parent, "v1"); !errors.Is(err, durable.ErrDetachAborted) || !errors.Is(err, storage.ErrChunkHeadPrecondition) { - t.Fatalf("staged chunks from the ended session were accepted: %v", err) - } + // The retry runs in a new session and commits what the first attempt + // uploaded in its ended one: the commit adopts those objects, so only + // the remaining chunks are put, and the seal completes in one retry. r, last, err := p.DetachVolumePlain(parent, "v1") if err != nil || r.Head.State != storage.ChunkHeadDetached || r.H != last || r.Head.RemoteLSN != last { t.Fatalf("plain seal retry failed: %+v last=%d err=%v", r, last, err) } - if len(remote.keys) != 2*chunks || remote.bytes != 2*chunks*chunkBytes { - t.Fatalf("the refused cut did not restage in its new session: successful=%d bytes=%d", len(remote.keys), remote.bytes) + if len(remote.keys) != chunks || remote.bytes != chunks*chunkBytes { + t.Fatalf("the retry put %d chunks in all (%d bytes); want %d: the first attempt's 2 adopted, only the rest put", len(remote.keys), remote.bytes, chunks) } if len(remote.images) != chunks { - t.Fatalf("restaged image has %d distinct payloads, want %d", len(remote.images), chunks) + t.Fatalf("sealed image has %d distinct payloads, want %d", len(remote.images), chunks) } for _, n := range remote.images { - if n != 2 { - t.Fatalf("unexpected session PUT count %d", n) + if n != 1 { + t.Fatalf("a chunk was put %d times; want once", n) } } - // The kernel requires a Put in the new session, but the content-named - // filer entry is reused by a conditional metadata update, not a blob PUT. c.blobs.Lock() physical := map[[32]byte]int{} for _, raw := range c.blobs.blobs { diff --git a/seaweed-block/core/storage/chunk_layer.go b/seaweed-block/core/storage/chunk_layer.go index a6a7c20143..7ded8bc3d6 100644 --- a/seaweed-block/core/storage/chunk_layer.go +++ b/seaweed-block/core/storage/chunk_layer.go @@ -147,7 +147,10 @@ type chunkLayerImpl struct { // pendingCut is its cut result, installed as the detach result if the // re-read shows it applied. pendingDetach bool - pendingCut chunkCutResult + // pendingAborted says the unresolved detach in pending was settled + // by its caller (ForgetAbortedDetach): it is never proposed again. + pendingAborted bool + pendingCut chunkCutResult // pendingBase is the version the unresolved CAS expected. While HEAD is // still at it, that CAS may still land, so a read alone never settles it. pendingBase chunkHeadVersion @@ -1245,7 +1248,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch l.stMu.Lock() p := copyHead(next) l.pending = &p - l.pendingDetach, l.pendingCut, l.pendingBase = detach, chunkCutResult{H: h, FullHash: all}, expected + l.pendingDetach, l.pendingCut, l.pendingBase, l.pendingAborted = detach, chunkCutResult{H: h, FullHash: all}, expected, false l.stMu.Unlock() // The session stays open: the commit may still land, and the // settlement replays it in the same session (resolvePending). @@ -1379,7 +1382,7 @@ func (l *chunkLayerImpl) SettleDetach(ctx context.Context) (settled detachSettle defer l.stMu.Unlock() cut := l.pendingCut l.pending = nil - l.pendingDetach, l.pendingCut, l.pendingBase = false, chunkCutResult{}, chunkHeadVersion{} + l.pendingDetach, l.pendingCut, l.pendingBase, l.pendingAborted = false, chunkCutResult{}, chunkHeadVersion{}, false switch { case sameProposal(cur, *pending): l.noteSettled(l.head, cur) @@ -1399,6 +1402,24 @@ func (l *chunkLayerImpl) SettleDetach(ctx context.Context) (settled detachSettle } } +// ForgetAbortedDetach records that an unresolved detach proposal was settled +// by its caller: the layout stop settlement aborted the session the detach +// ran in and read HEAD live at this holder's claim, and serving resumed. The +// detach must then never land, but a re-proposal could: the commit adopts +// this volume's objects from an earlier session. The next settlement +// (resolvePending) still reads HEAD and takes it as the base, but proposes +// nothing and keeps what the detach staged, so the next proposal does not +// upload it again. An unresolved ordinary cut is not affected. +func (l *chunkLayerImpl) ForgetAbortedDetach() { + l.capMu.Lock() + defer l.unlockCap() + l.stMu.Lock() + defer l.stMu.Unlock() + if l.pending != nil && l.pendingDetach { + l.pendingAborted = true + } +} + func (l *chunkLayerImpl) storedDetach() (chunkCutResult, bool) { l.stMu.Lock() defer l.stMu.Unlock() @@ -1505,7 +1526,7 @@ func (l *chunkLayerImpl) resolvePending(ctx context.Context) (err error) { } }() l.stMu.Lock() - pending, base := l.pending, l.pendingBase + pending, base, aborted := l.pending, l.pendingBase, l.pendingAborted l.stMu.Unlock() if pending == nil { return nil @@ -1514,7 +1535,7 @@ func (l *chunkLayerImpl) resolvePending(ctx context.Context) (err error) { if err != nil { return fmt.Errorf("storage: capture: earlier CAS outcome still unresolved: %w: %w", errChunkCASOutcomeUnknown, err) } - if !sameProposal(cur, *pending) && !l.publicationOwnerChanged(cur) && cur.Gen == base.Gen && cur.Epoch == base.Epoch { + if !aborted && !sameProposal(cur, *pending) && !l.publicationOwnerChanged(cur) && cur.Gen == base.Gen && cur.Epoch == base.Epoch { // HEAD is still the unresolved CAS's base, so that CAS may still // land. Settle it by issuing the same proposal at the same base: // whichever lands first, HEAD ends at this proposal and the other @@ -1545,13 +1566,16 @@ func (l *chunkLayerImpl) resolvePending(ctx context.Context) (err error) { l.fencePublication(cur) return errChunkLayerFenced } - // Settled: the proposal landed or can never land. - l.discardStaged() // a landed proposal's commit already ended its session + // Settled: the proposal landed or can never land. An aborted detach's + // uploads stay staged for the next proposal, which adopts them. + if !aborted { + l.discardStaged() // a landed proposal's commit already ended its session + } l.stMu.Lock() defer l.stMu.Unlock() l.pending = nil wasDetach, cut := l.pendingDetach, l.pendingCut - l.pendingDetach, l.pendingCut, l.pendingBase = false, chunkCutResult{}, chunkHeadVersion{} + l.pendingDetach, l.pendingCut, l.pendingBase, l.pendingAborted = false, chunkCutResult{}, chunkHeadVersion{}, false switch { case sameProposal(cur, *pending): l.noteSettled(l.head, cur) diff --git a/seaweed-block/core/storage/chunk_seam.go b/seaweed-block/core/storage/chunk_seam.go index f64aa396fc..3dba8a708b 100644 --- a/seaweed-block/core/storage/chunk_seam.go +++ b/seaweed-block/core/storage/chunk_seam.go @@ -579,6 +579,11 @@ type chunkLayer interface { // error wrapping errChunkCASOutcomeUnknown leaves it undecided: stay // stopped. It never resumes on top of a possibly detached HEAD. SettleDetach(ctx context.Context) (detachSettlement, chunkCutResult, error) + // ForgetAbortedDetach records that the caller settled an unresolved + // detach as aborted another way (its session aborted, HEAD live at this + // holder's claim, serving resumed): it is never proposed again. Required, + // not optional: without it a re-proposal of that detach could land. + ForgetAbortedDetach() // MakeRemoteDurable is the durability point for snapshot, detach and // migrate: a Capture whose H >= t. Only a nil return makes t remote // durable; it requires the local Sync to cover t first, and fails diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 80e1ed18d8..fb1607fbee 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -398,6 +398,7 @@ stateDiagram-v2 | Stage | native remaining bytes above half the COW side cap trigger logical-read pre-copy straight to remote; repeat only while the remainder shrinks; legacy fixtures retain the chunk-count bound; the holder session begins before its first upload | `core/storage/chunk_layer.go` `stage` | `INV-CUT-INTENT-FIRST-001`, `INV-CUT-STAGED-REUSE-001`, `INV-CUT-PAYLOAD-BOUNDED-001`, `INV-CUT-READ-LOGICAL-001` | | Plain detach | plain=true acquires exclusive idle frontend admission (closed handles allowed), then StopIO and caller-bounded seal. Busy requests mutate nothing; publication and settlement retain authority/HEAD checks. | `provider_chunk.go` `DetachVolumePlain`; `storage_adapter.go` `stopPlainDetachIfIdle`; `chunk_control.go` `handleChunkDetach` | `INV-CUT-PLAIN-DETACH-001`, `INV-WS-HEAD-BELT-001` | | Plain seal replay | a fresh B HEAD must be detached with the local claim id, exact epoch and holder; idle admission remains closed, authority is checked across the read, and no CAS occurs. A same-epoch detached restart may read the proof without an attached runtime; cache alone never answers success. | `provider_seal_replay.go` `replayPlainSeal`, `readLayoutSeal` | `INV-WS-SEAL-REPLAY-001` | +| `INV-WS-DETACH-ABORTED-001` | A detach the layout stop settlement reports aborted (its session aborted, HEAD live at this holder's claim, serving resumed) is never proposed again: the next settlement reads HEAD and proposes nothing, and keeps what the detach staged for the next proposal. | detach settlement → serving | `core/frontend/durable/provider_chunk.go` `resumeAfterDetach`; `core/storage/chunk_layer.go` `ForgetAbortedDetach`, `resolvePending` | `TestWALStoreChunk_LostDetachCASNotAppliedIsCancelledAndResumes`, `TestWALStoreChunk_DetachFreezeIsBoundedThenResumes`, `TestWALStoreChunk_DelayedDetachCASCannotLandAfterTheCancel` (`core/frontend/durable/provider_chunk_detach_abort_test.go`); `TestADetachAfterAnAbortedDetachCompletesWithoutSendingItsChunksAgain` (`core/frontend/durable/provider_chunk_detach_rerun_test.go`) | — | ACTIVE | | Pre-copy admission | (Not reachable in this release; see the note below.) opt-in: close frontend admission and drain registered operations for at most 100 ms before taking the store barrier; rejected attempts clear the pause and grant every waiter FIFO admission under one lock hold before ordinary uploads; each waiter rechecks the ordinary gate without waiting for another I/O to finish | `precopy_admission.go` `BeginPrecopyPause`; `chunk_precopy.go` `PrecopyDetachWithAdmission` | `INV-CUT-PRECOPY-001` | | Quiesce | the capture barrier (`captureMu`) is held exclusively, then `Sync` fixes H; `Recover` and writes hold the barrier shared | `core/storage/chunk_layer.go` `captureLocked`; `core/storage/walstore.go` `WALStore.Recover`, `WALStore.Write` | `INV-CUT-QUIESCED-001`, `INV-CUT-RECOVER-BARRIER-001` | | Pre-copy detach | (Not reachable in this release; see the note below.) at most five rolling attempts within a cooperative 60 s context; authoritative candidates and measured costs admit the final cut after the bounded drain; a known estimate may use the declared five-second freeze ceiling when it is at least 90% of the previous comparable known estimate or on the final physical round; frozen commands wait up to the five-second cutover budget and receive FIFO admission grants together after a safe abort, without serializing on I/O completion; each queue bound starts at the command arrival | `chunk_precopy.go`; `precopy_admission.go`; `DurableProvider.DetachVolume` | `INV-CUT-PRECOPY-001` | @@ -428,7 +429,9 @@ B stores snapshots, restore dependencies and the active session in HEAD. The tra | Operation | Guard and outcome | Enforced in | Protects | |---|---|---|---| | Begin uploads | Open or replay the holder's session before the first object upload; a failed Begin uploads nothing. | `core/frontend/chunkstore/layout_remote.go` `Begin`; `core/storage/chunk_cut_payload.go` `streamCutPayloads` | `INV-CUT-INTENT-FIRST-001` | -| Commit snapshot | Verify the complete root and objects written in this session before the conditional HEAD update installs the image and optional snapshot name, then ends the session. | `core/frontend/chunkstore/layout/commit.go` `RunCommit` | `INV-SNAPK-COMMIT-REACH-001` | +| Commit snapshot | Verify the complete root and objects written in this session, or adopted from an earlier session of this volume (re-stamped, mark cleared), before the conditional HEAD update installs the image and optional snapshot name, then ends the session. | `core/frontend/chunkstore/layout/commit.go` `RunCommit` | `INV-SNAPK-COMMIT-REACH-001` | +| `INV-SNAPK-COMMIT-ADOPT-001` | The check before a commit's HEAD update adopts an object of this volume present under its name but written by another session, or marked: one conditional update re-stamps it and clears the mark. An object of another volume, or absent, is refused. | M9 snap → idle (Commit) | `core/frontend/chunkstore/layout` `objects.go` `ownedOrAdopted`, `commit.go` `CheckCommitObjects` (not the HEAD step's lookups); `layout_remote.go` `prepareCommitLocked` opens a session no upload opened and checks against the HEAD its begin wrote | `TestARerunAfterATimedOutRequestCommitsTheUploadsOfItsAbortedSession`, `TestTheRerunsCommitDoesNotAdoptAnotherVolumesObject`, `TestACleaningRacingTheAdoptionKeepsTheObject` (`core/frontend/chunkstore/layout_adopt_own_objects_test.go`); `TestAnotherVolumesEntryIsNeverAdopted`, `TestAnAdoptionThatLosesItsRaceReadsAgainAndClearsTheLatestMark`, `TestAnEntryDeletedDuringTheAdoptionIsNotOwned`, `TestAnAdoptionThatKeepsLosingStopsAfterItsRounds`, `TestACancelledAdoptionAdoptsNothing`, `TestTheHeadStepsLookupsDoNotAdopt` (`core/frontend/chunkstore/layout/adopt_test.go`) | — (the staged-session model is not in this repository) | ACTIVE | +| `INV-SNAPK-CLEAN-HOLD-001` | The holder's cleaning is refused (busy) while an upload of this process awaits a commit: a cut over several requests, HEAD idle between them, keeps what it staged for its commit to adopt. That commit, or the engine dropping its staged uploads (Abort), releases it. | M9 idle → clean (Begin) | `core/frontend/chunkstore/layout_remote.go` `Clean`, `PutPaced`, `CASHead`, `Abort` (`uncommitted`) | `TestTheCleaningWaitsForAnUploadNotYetCommitted` (`core/frontend/chunkstore/layout_adopt_own_objects_test.go`); `TestLayoutStalledSessionYieldAllowsCleaning` (`core/frontend/chunkstore/layout_stalled_discard_test.go`) | — | ACTIVE | | Abort or settle | Keep reusable uploads in their session; retain an unresolved proposal for settlement. Dropped work aborts the open session; a landed commit has already ended it. | `core/storage/chunk_layer.go` `discardStaged`, `captureLocked`, `Close`; `core/frontend/chunkstore/layout_remote.go` `AbortOpenSession` | `INV-CUT-INTENT-CLOSE-001`, `INV-WS-CAS-UNKNOWN-001` | | Restore | Record the target as a source dependent before creating its root and unclaimed HEAD; owner-qualified references resolve in the source pool. | `core/frontend/chunkstore/catalog_b.go` `BCatalog.Restore`; `core/frontend/chunkstore/layout/create.go` | `INV-SNAPK-COMMIT-REACH-001` | | Remove snapshot | Remove the name through a conditional HEAD transition; its objects remain governed by the roots and dependents still recorded. | `core/frontend/chunkstore/catalog_b.go` `DeleteSnapshot`; `core/frontend/chunkstore/layout/snapshots.go` | `INV-SNAPK-HEAD-WRITE-001` | @@ -1125,7 +1128,7 @@ Notes: | `INV-SNAPK-HEAD-CODEC-001` | HEAD is canonical JSON with at most 10 snapshots (`MaxSnapshots`) and sorted unique dependents; unknown fields, non-canonical bytes and names that are not valid UTF-8 are refused at encode and decode, and the next HEAD is checked before it is written. | M9 every transition | `core/frontend/chunkstore/layout` `head.go` `Head.check`, `Head.Encode`, `DecodeHead` | `TestHead_GoldenEncodingRoundTrip`, `TestHead_Refusals`, `TestHead_RefusesInvalidUTF8` | — (the snapshot kernel model is not in this repository) | ACTIVE | | `INV-SNAPK-BEGIN-001` | Begin opens snap(s) only for the holder at HEAD's epoch and only from idle; a re-run of the open session writes nothing; killed at its write and re-run, it ends in snap(s) at one generation step. | M9 idle → snap | `core/frontend/chunkstore/layout` `head.go` `Head.Begin`, `RunBegin` | `TestBegin_Closure`, `TestRunBegin_InterruptAtEveryStep` | — (the snapshot kernel model is not in this repository) | ACTIVE | | `INV-SNAPK-ABORT-001` | Abort closes the holder's own snap(s) and changes nothing else; after its own crash a holder rolls the open session back before beginning another; over idle Abort writes nothing and its success never says whether the work was committed. | M9 snap → idle (Abort) | `core/frontend/chunkstore/layout` `head.go` `Head.Abort`, `RunAbort`; `core/frontend/durable/provider_layout.go` `settleLayoutStop` | `TestLayoutStopAbortMustConfirmItsOutcome`, `TestLayoutRemote_AbortOpenSessionDoesNotWaitForAHeldCommit`, `TestLayoutRemote_AbortOpenSessionFencesAForeignHead`, `TestLayoutRemoteSessionFieldSites`, `TestAbort_Closure`, `TestAbort_IdleMeansNoActivityRemains`, `TestAbort_RollBackAfterOwnCrash`, `TestRunAbort_InterruptAtEveryStep` | — (the snapshot kernel model is not in this repository) | ACTIVE | -| `INV-SNAPK-COMMIT-REACH-001` | A commit never names an object that is not written: before its one HEAD update it finds present the own chunks new against HEAD's current root (that root rebuilt from the previous manifest, an empty image included), every segment and the root; unchanged and foreign chunks are not looked up. | M9 snap → idle (Commit) | `core/frontend/chunkstore/layout` `commit.go` `RunCommit`, `CheckCommitObjects`, `Head.Commit`; the lookups run with the cut's budget before the bounded HEAD update (`layout_remote.go` `LayoutRemote.CheckCommit`, called by `core/storage/chunk_layer.go`), and the CAS skips them only for the (session, root) checked | `TestCommit_Closure`, `TestRunCommit_LooksUpOnlyWhatIsNew`, `TestRunCommit_RefusesUnwrittenObjects`, `TestRunCommit_StaleBaseAndLookupFailure`, `TestRunCommit_AfterAnEmptyPublishedRoot`, `TestRunCommit_InterruptAtEveryStep`; its verification is bounded parallel and stays all-or-nothing: `TestCommitVerifiesManyNewChunksWithinTheBudget`, `TestADetachingCommitOfManyNewChunksCompletesWithinTheBudget`, `TestCommitRefusesWhenOneOfManyNewChunksIsNotPrepared`, `TestCommitLookupsNeverExceedTheCap`, `TestACancelledCommitStopsJoinsAndWritesNothing`, `TestTheEarliestFailureByPositionDecidesTheError` (`commit_verify_scale_test.go`, `commit_verify_controls_test.go`); outside the 2 s update: `TestCutCommitsWhenItsObjectCheckOutlastsTheHeadUpdate`, `TestCASSkipsTheLookupsCheckedForItsSessionAndRoot`, `TestCASWithNoPassedCheckDoesTheLookups`, `TestCASAfterACheckOfAnotherRootDoesTheLookups`, `TestBeginCleanBetweenTheCheckAndTheUpdateIsBusy`, `TestAPreCheckThatFindsAChunkMissingEndsWithNoLookupInTheCAS` (`core/frontend/chunkstore/layout_commit_check_budget_test.go`); `TestObjectsCheckedIsWrittenOnlyByCASHead`, `TestCASAfterAnAbortAndANewSessionAtTheSameRootDoesTheLookups`, `TestCommitPendingSnapshotLooksUpTheRootAndSegments`, `TestMetadataRetryLooksUpOnlyWithoutAPassedCheck` (`core/frontend/chunkstore/layout_commit_check_guards_test.go`); through the provider's wrapped remote: `TestProviderCutCommitsWhenItsObjectCheckOutlastsTheHeadUpdate`, `TestProviderWrappedRemoteKeepsTheLayoutRemotesOptionalInterfaces` (`core/frontend/durable/commit_check_budget_test.go`); `TestLayoutRemoteUploadFinishedAfterSessionEndCannotCommit` (`core/frontend/chunkstore/layout_upload_concurrency_test.go`) | — (the snapshot kernel model is not in this repository) | ACTIVE | +| `INV-SNAPK-COMMIT-REACH-001` | A commit never names an unwritten object: before its HEAD update it finds present, written by its session or adopted from an earlier one of this volume, the own chunks new against HEAD's current root, every segment and the root; unchanged and foreign chunks are not looked up. | M9 snap → idle (Commit) | `core/frontend/chunkstore/layout` `commit.go` `RunCommit`, `CheckCommitObjects`, `Head.Commit`; the lookups run with the cut's budget before the bounded HEAD update (`layout_remote.go` `LayoutRemote.CheckCommit`, called by `core/storage/chunk_layer.go`), and the CAS skips them only for the (session, root) checked | `TestCommit_Closure`, `TestRunCommit_LooksUpOnlyWhatIsNew`, `TestRunCommit_RefusesUnwrittenObjects`, `TestRunCommit_StaleBaseAndLookupFailure`, `TestRunCommit_AfterAnEmptyPublishedRoot`, `TestRunCommit_InterruptAtEveryStep`; its verification is bounded parallel and stays all-or-nothing: `TestCommitVerifiesManyNewChunksWithinTheBudget`, `TestADetachingCommitOfManyNewChunksCompletesWithinTheBudget`, `TestCommitRefusesWhenOneOfManyNewChunksIsNotPrepared`, `TestCommitLookupsNeverExceedTheCap`, `TestACancelledCommitStopsJoinsAndWritesNothing`, `TestTheEarliestFailureByPositionDecidesTheError` (`commit_verify_scale_test.go`, `commit_verify_controls_test.go`); outside the 2 s update: `TestCutCommitsWhenItsObjectCheckOutlastsTheHeadUpdate`, `TestCASSkipsTheLookupsCheckedForItsSessionAndRoot`, `TestCASWithNoPassedCheckDoesTheLookups`, `TestCASAfterACheckOfAnotherRootDoesTheLookups`, `TestBeginCleanBetweenTheCheckAndTheUpdateIsBusy`, `TestAPreCheckThatFindsAChunkMissingEndsWithNoLookupInTheCAS` (`core/frontend/chunkstore/layout_commit_check_budget_test.go`); `TestObjectsCheckedIsWrittenOnlyByCASHead`, `TestCASAfterAnAbortAndANewSessionAtTheSameRootDoesTheLookups`, `TestCommitPendingSnapshotLooksUpTheRootAndSegments`, `TestMetadataRetryLooksUpOnlyWithoutAPassedCheck` (`core/frontend/chunkstore/layout_commit_check_guards_test.go`); through the provider's wrapped remote: `TestProviderCutCommitsWhenItsObjectCheckOutlastsTheHeadUpdate`, `TestProviderWrappedRemoteKeepsTheLayoutRemotesOptionalInterfaces` (`core/frontend/durable/commit_check_budget_test.go`); `TestLayoutRemoteUploadFinishedAfterSessionEndCannotCommit` (`core/frontend/chunkstore/layout_upload_concurrency_test.go`) | — (the snapshot kernel model is not in this repository) | ACTIVE | | `INV-SNAPK-SNAPSHOT-META-001` | Snapshot retention metadata (creation time, class, expiry and at most four bounded labels) is written by the commit that creates the snapshot name and never changed by a replay. | M9 snap -> idle (named Commit) | `core/frontend/chunkstore/layout/head.go` `SnapshotMeta`, codec; `commit.go` `Head.Commit`, `RunCommit`; `core/host/volume/chunk_control.go` `chunkControl.Snapshot`, `chunkControl.ListSnapshots` | `TestSnapshotMeta_WrittenOnceByTheCommit`, `TestHead_BoundsRefused`, `TestGuard_SafetyIgnoresSnapshotMeta`; `TestChunkControlPassesRetentionFactsToTheNamedCommit`, `TestChunkControlUsesTheBoundLayoutIdentity` | Retention facts affect policy only; the safety guard forbids their use in reachability/removal. Actual provider and scheduled capture integration remain cutover work; no live-path claim. | ACTIVE | | `INV-SNAPK-DETACHED-001` | A detached HEAD remains closed to its same-epoch holder; only a higher-epoch Claim returns it to live. | M9 snap → detached → higher-epoch idle | `core/frontend/chunkstore/layout` `commit.go`, `head.go`, `claim.go`, `start.go` | `TestLayoutStopAbortMustConfirmItsOutcome`, `TestWorkspaceLayoutDetachedProof`, `TestCommitDetached_ProofAndLostReply`, `TestDetachedHEAD_RefusesEveryHolderTransition`, `TestDetachedHEAD_NewGrantStillWaitsForTheOldLease` | Caller write-barrier and synced-position join, master clean-proof reader and composed model review remain cutover gates. | ACTIVE | | `INV-SNAPK-TXN-INTERRUPT-001` | A snapshot transaction killed at any of its writes (Begin, each object, Commit), before the write or after it applied with its reply lost, never leaves HEAD reaching a missing object, and the restarted holder (roll back, new session, base recomputed from HEAD) ends at the committed image. | M9 idle → snap → idle | `core/frontend/chunkstore/layout` `head.go`, `commit.go` (the transitions above) | `TestSnapshotSession_InterruptAtEveryStep`, `TestReachableMissing_Controls`, `TestAbort_AfterCommitLeavesTheCommit` | — (the snapshot kernel model is not in this repository) | ACTIVE |