diff --git a/seaweed-block/core/frontend/chunkstore/layout_commit_check_budget_test.go b/seaweed-block/core/frontend/chunkstore/layout_commit_check_budget_test.go index e5e5f59ddf..2b1c049a75 100644 --- a/seaweed-block/core/frontend/chunkstore/layout_commit_check_budget_test.go +++ b/seaweed-block/core/frontend/chunkstore/layout_commit_check_budget_test.go @@ -3,8 +3,6 @@ package chunkstore import ( "context" "errors" - "fmt" - "os" "path/filepath" "strings" "sync/atomic" @@ -193,36 +191,6 @@ func TestBeginCleanBetweenTheCheckAndTheUpdateIsBusy(t *testing.T) { // lhStore is the HEAD store w's remote commits through. func lhStore(w *c1Remote) (layout.HeadStore, error) { return w.LayoutRemote.st, nil } -// Only LayoutRemote.CASHead may tell RunCommit that the objects were -// checked, and only for the (session, root) CheckCommit passed: a new site -// that sets ObjectsChecked fails here until it is reviewed and listed. -func TestObjectsCheckedIsSetOnlyByCASHead(t *testing.T) { - var sites []string - for _, dir := range []string{".", "layout"} { - files, err := filepath.Glob(filepath.Join(dir, "*.go")) - if err != nil { - t.Fatal(err) - } - for _, f := range files { - if strings.HasSuffix(f, "_test.go") { - continue - } - b, err := os.ReadFile(f) - if err != nil { - t.Fatal(err) - } - for i, line := range strings.Split(string(b), "\n") { - if strings.Contains(line, "ObjectsChecked =") || strings.Contains(line, "ObjectsChecked:") { - sites = append(sites, fmt.Sprintf("%s:%d", filepath.ToSlash(f), i+1)) - } - } - } - } - if len(sites) != 1 || !strings.HasPrefix(sites[0], "layout_remote.go:") { - t.Fatalf("ObjectsChecked is set at %v; want exactly one site, in LayoutRemote.CASHead", sites) - } -} - // A pre-check that finds a chunk missing (here one uploaded chunk is gone // from the filer) ends the cut as a refusal: the CAS that follows answers it // from HEAD and looks up no chunk, and HEAD keeps its root. diff --git a/seaweed-block/core/frontend/chunkstore/layout_commit_check_guards_test.go b/seaweed-block/core/frontend/chunkstore/layout_commit_check_guards_test.go new file mode 100644 index 0000000000..601402ecbd --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/layout_commit_check_guards_test.go @@ -0,0 +1,228 @@ +package chunkstore + +import ( + "context" + "fmt" + "go/ast" + "go/parser" + "go/token" + "io/fs" + "os" + "path/filepath" + "sort" + "strings" + "sync/atomic" + "testing" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// objectsCheckedWriters returns every place in src that writes +// ObjectsChecked (an assignment to a field of that name, or a keyed +// composite-literal element), as "file (Receiver).Method" or "file func". +func objectsCheckedWriters(t *testing.T, file, src string) []string { + t.Helper() + f, err := parser.ParseFile(token.NewFileSet(), file, src, 0) + if err != nil { + t.Fatalf("parse %s: %v", file, err) + } + var sites []string + for _, d := range f.Decls { + fn, ok := d.(*ast.FuncDecl) + if !ok || fn.Body == nil { + continue + } + owner := fn.Name.Name + if fn.Recv != nil && len(fn.Recv.List) == 1 { + typ := fn.Recv.List[0].Type + if star, ok := typ.(*ast.StarExpr); ok { + typ = star.X + } + if id, ok := typ.(*ast.Ident); ok { + owner = "(" + id.Name + ")." + fn.Name.Name + } + } + ast.Inspect(fn.Body, func(n ast.Node) bool { + switch x := n.(type) { + case *ast.AssignStmt: + for _, lhs := range x.Lhs { + if sel, ok := lhs.(*ast.SelectorExpr); ok && sel.Sel.Name == "ObjectsChecked" { + sites = append(sites, file+" "+owner) + } + } + case *ast.KeyValueExpr: + if id, ok := x.Key.(*ast.Ident); ok && id.Name == "ObjectsChecked" { + sites = append(sites, file+" "+owner) + } + } + return true + }) + } + return sites +} + +// Only LayoutRemote.CASHead may tell RunCommit that the objects were +// checked (and only for the session and root CheckCommit passed). The +// census parses every production Go file of the module and attributes each +// write to its receiver and method; the controls show it finds a write in +// another method, a keyed literal and a multiple assignment. +func TestObjectsCheckedIsWrittenOnlyByCASHead(t *testing.T) { + root, err := filepath.Abs(filepath.Join("..", "..", "..")) + if err != nil { + t.Fatal(err) + } + var sites []string + err = filepath.WalkDir(root, func(p string, d fs.DirEntry, err error) error { + if err != nil { + return err + } + if d.IsDir() { + if name := d.Name(); name == ".git" || name == "testdata" || name == "vendor" { + return filepath.SkipDir + } + return nil + } + if !strings.HasSuffix(p, ".go") || strings.HasSuffix(p, "_test.go") { + return nil + } + b, err := os.ReadFile(p) + if err != nil { + return err + } + if !strings.Contains(string(b), "ObjectsChecked") { + return nil + } + rel, _ := filepath.Rel(root, p) + sites = append(sites, objectsCheckedWriters(t, filepath.ToSlash(rel), string(b))...) + return nil + }) + if err != nil { + t.Fatal(err) + } + sort.Strings(sites) + want := []string{"core/frontend/chunkstore/layout_remote.go (LayoutRemote).CASHead"} + if fmt.Sprint(sites) != fmt.Sprint(want) { + t.Fatalf("ObjectsChecked is written at %v; want only %v", sites, want) + } + + for name, c := range map[string]struct { + src string + want string + }{ + "another LayoutRemote method": { + "package chunkstore\nfunc (l *LayoutRemote) Other(req *CommitRequest) { req.ObjectsChecked = true }\n", + "x.go (LayoutRemote).Other", + }, + "a keyed literal in another package": { + "package other\nfunc build() { _ = layout.CommitRequest{Session: \"s\", ObjectsChecked: true} }\n", + "x.go build", + }, + "a multiple assignment": { + "package chunkstore\nfunc (l *LayoutRemote) CASHead2(req *CommitRequest) { var n int; req.ObjectsChecked, n = true, 1; _ = n }\n", + "x.go (LayoutRemote).CASHead2", + }, + } { + if got := objectsCheckedWriters(t, "x.go", c.src); len(got) != 1 || got[0] != c.want { + t.Errorf("control %q: census found %v, want [%s]", name, got, c.want) + } + } +} + +// A check passed in one session does not cover the same root in another: +// after an abort and a new session, the CAS of the same image does the +// lookups. +func TestCASAfterAnAbortAndANewSessionAtTheSameRootDoesTheLookups(t *testing.T) { + var checkedIn string + _, w, _ := c1Cut(t, func(w *c1Remote) func(context.Context, storage.ChunkHeadVersion, storage.ChunkHead) error { + return func(ctx context.Context, e storage.ChunkHeadVersion, n storage.ChunkHead) error { + if err := w.LayoutRemote.CheckCommit(ctx, e, n); err != nil { + return err + } + w.LayoutRemote.mu.Lock() + checkedIn = w.LayoutRemote.checked.session + w.LayoutRemote.mu.Unlock() + w.LayoutRemote.Abort() // the next call drops the session; CASHead opens another + return nil + } + }) + if checkedIn == "" { + t.Fatal("the pre-check recorded no session") + } + if n := w.casGot.Load(); n == 0 { + t.Fatal("CAS in a new session looked up no chunk: a check of another session was reused") + } +} + +// CommitPendingSnapshot never has a passed check: naming the current image +// (no new chunks) still looks up its segments and its root. +func TestCommitPendingSnapshotLooksUpTheRootAndSegments(t *testing.T) { + lh, w, err := c1Cut(t, nil) + if err != nil { + t.Fatal(err) + } + var segRoot atomic.Int64 + lh.ff.afterLookup = func(p string) { + if strings.Contains(p, "/seg/") || strings.Contains(p, "/root/") { + segRoot.Add(1) + } + } + w.LayoutRemote.SetSnapshot("s1", layout.SnapshotMeta{}) + if err := w.LayoutRemote.CommitPendingSnapshot(context.Background()); err != nil { + t.Fatal(err) + } + if segRoot.Load() == 0 { + t.Fatal("CommitPendingSnapshot looked up no segment or root") + } + if _, ok := lh.head().Snapshots["s1"]; !ok { + t.Fatal("snapshot s1 not in HEAD") + } +} + +// The metadata-conflict retry inside CASHead (HEAD's generation moved with +// its image and session unchanged, as by an operator's snapshot-table +// write): without a passed check the retry looks up the chunks again; with +// one for the same pair it may reuse it. +func TestMetadataRetryLooksUpOnlyWithoutAPassedCheck(t *testing.T) { + for _, c := range []struct { + name string + check bool + lookups bool + }{ + {"no passed check", false, true}, + {"passed check of the same pair", true, false}, + } { + t.Run(c.name, func(t *testing.T) { + var retried atomic.Bool + var atRetry atomic.Int64 + var ff *fakeFiler + _, w, err := c1Cut(t, func(w *c1Remote) func(context.Context, storage.ChunkHeadVersion, storage.ChunkHead) error { + ff = w.ff + ff.failUpdate = func(p string) error { + if strings.HasSuffix(p, "/HEAD") && w.inCAS.Load() && !retried.Load() { + retried.Store(true) + atRetry.Store(w.casGot.Load()) + e := ff.entries[p] // under ff.mu: an operator write that moves only the generation + gen := string(e.Extended[layoutGen]) + e.Extended[layoutGen] = []byte(gen + "0") + } + return nil + } + if c.check { + return nil // the real pre-check + } + return func(context.Context, storage.ChunkHeadVersion, storage.ChunkHead) error { return nil } + }) + if err != nil { + t.Fatal(err) + } + if !retried.Load() { + t.Fatal("no metadata retry happened") + } + afterRetry := w.casGot.Load() - atRetry.Load() + if got := afterRetry > 0; got != c.lookups { + t.Fatalf("retry looked up %d chunks; want lookups=%v", afterRetry, c.lookups) + } + }) + } +} diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index fcf01f7bd5..7ac18c11c3 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -1078,7 +1078,7 @@ Notes: | `INV-SNAPK-HEAD-CODEC-001` | HEAD is canonical JSON with at most 100 snapshots 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`, `TestObjectsCheckedIsSetOnlyByCASHead`, `TestAPreCheckThatFindsAChunkMissingEndsWithNoLookupInTheCAS` (`core/frontend/chunkstore/layout_commit_check_budget_test.go`); through the provider's wrapped remote: `TestProviderCutCommitsWhenItsObjectCheckOutlastsTheHeadUpdate`, `TestProviderWrappedRemoteKeepsTheLayoutRemotesOptionalInterfaces` (`core/frontend/durable/commit_check_budget_test.go`) | — (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`) | — (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`; host `chunkControl.Snapshot`, `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 |