diff --git a/seaweed-block/core/frontend/durable/provider.go b/seaweed-block/core/frontend/durable/provider.go index 96e4536584..486a8167cd 100644 --- a/seaweed-block/core/frontend/durable/provider.go +++ b/seaweed-block/core/frontend/durable/provider.go @@ -180,6 +180,9 @@ type DurableProvider struct { // volume's handle and layer are resolved. testAfterChunkResolve func() + // testBeforeChunkFreshRetire holds the real post-presence/pre-marker boundary. + testBeforeChunkFreshRetire func() error + // testWALStoreFactory selects a dark store only in provider caller controls. // No production option, flag or environment variable installs it. testWALStoreFactory func(path string, create bool) (*storage.WALStore, error) diff --git a/seaweed-block/core/frontend/durable/provider_chunk.go b/seaweed-block/core/frontend/durable/provider_chunk.go index 268b74398c..326fe60b27 100644 --- a/seaweed-block/core/frontend/durable/provider_chunk.go +++ b/seaweed-block/core/frontend/durable/provider_chunk.go @@ -231,14 +231,30 @@ func (p *DurableProvider) attachChunk(ctx context.Context, volumeID string, h *v } p.mu.Unlock() } + // The owner commit is serialized with a later BASE begin. The callback + // does marker I/O only: no store/layer reentry while installMu is held. + commit := func() error { + if h.fresh { + return removeChunkFreshMarker(h.path) + } + return nil + } if h.fresh { - // The attach persisted the absence of every HEAD chunk; only now - // may a restart treat the local volume as authoritative. - if err := removeChunkFreshMarker(h.path); err != nil { + if hook := p.testBeforeChunkFreshRetire; hook != nil { + if err := hook(); err != nil { + return err + } + } + } + if ws, ok := h.storage.(*storage.WALStore); ok { + if err := ws.CommitChunkAttachV3(commit); err != nil { return err } - h.fresh = false + } else if err := commit(); err != nil { + return err } + h.fresh = false + return nil } diff --git a/seaweed-block/core/frontend/durable/provider_format_v3_fresh_crash_test.go b/seaweed-block/core/frontend/durable/provider_format_v3_fresh_crash_test.go new file mode 100644 index 0000000000..6ecd153931 --- /dev/null +++ b/seaweed-block/core/frontend/durable/provider_format_v3_fresh_crash_test.go @@ -0,0 +1,201 @@ +//go:build swblock_format_v3_test + +package durable + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "os" + "os/exec" + "path/filepath" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/storage" +) + +type freshCrashImage struct { + Head storage.ChunkHead + Objects map[string][]byte +} + +func freshCrashRemote(t *testing.T, path string) *storage.MemChunkRemote { + t.Helper() + raw, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + var img freshCrashImage + if err = json.Unmarshal(raw, &img); err != nil { + t.Fatal(err) + } + remote := storage.NewMemChunkRemote() + ctx := context.Background() + for key, data := range img.Objects { + if err = remote.Put(ctx, key, data); err != nil { + t.Fatal(err) + } + } + for gen := uint64(0); gen < img.Head.Gen; gen++ { + current, e := remote.GetHead(ctx) + if e != nil { + t.Fatal(e) + } + if _, e = remote.CASHead(ctx, storage.ChunkHeadVersion{Gen: current.Gen, Epoch: current.Epoch}, img.Head); e != nil { + t.Fatal(e) + } + } + return remote +} + +// The child exits after presence is durable but before the fresh marker is +// removed. No Close or provider cleanup runs on the successful crash path. +func TestDurableProviderV3_FreshMarkerCrashKeepsCompletedBASE(t *testing.T) { + freshMarkerCrashKeepsCompletedBASE(t, "attach") +} + +func TestDurableProviderV3_FreshMarkerCompletionCrashKeepsCompletedBASE(t *testing.T) { + freshMarkerCrashKeepsCompletedBASE(t, "complete") +} + +func freshMarkerCrashKeepsCompletedBASE(t *testing.T, mode string) { + t.Helper() + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + if root := os.Getenv("SWBLOCK_V3_FRESH_CRASH_ROOT"); root != "" { + remote := freshCrashRemote(t, filepath.Join(root, "remote.json")) + p := mappedProviderV3(t, root, remote) + st, err := p.EnsureStorage("v1") + if err != nil { + t.Fatal(err) + } + ws := st.(*storage.WALStore) + if _, err = ws.Recover(); err != nil { + t.Fatal(err) + } + var h storage.InstallHandle + install := func() { + var id [16]byte + id[0] = 23 + h, err = storage.BeginInstall(ws, 7, id) + if err != nil { + t.Fatal(err) + } + data := bytes.Repeat([]byte{0x78}, 4096) + if err = h.WriteBase(5, data); err != nil { + t.Fatal(err) + } + if err = h.WriteBase(9, make([]byte, 4096)); err != nil { + t.Fatal(err) + } + if err = h.ApplyInstallEntry(5, data, 8); err != nil { + t.Fatal(err) + } + if err = h.MarkBaseComplete(); err != nil { + t.Fatal(err) + } + if _, err = ws.Sync(); err != nil { + t.Fatal(err) + } + if err = storage.FlushMappedWALStoreV3Test(ws); err != nil { + t.Fatal(err) + } + } + mode = os.Getenv("SWBLOCK_V3_FRESH_CRASH_MODE") + if mode != "complete" { + install() + } + p.testBeforeChunkFreshRetire = func() error { + if mode == "complete" { + install() + } + if _, err := os.Stat(chunkFreshMarker(p.volumePath("v1"))); err != nil { + t.Fatal(err) + } + if err := h.ApplyInstallEntry(5, bytes.Repeat([]byte{0x79}, 4096), 9); err != nil { + t.Fatal(err) + } + if _, err := ws.Sync(); err != nil { + t.Fatal(err) + } + fmt.Println("FRESH_CRASH_READY presence_saved=true marker_present=true ack=9 no_Close=true") + os.Exit(0) + return nil + } + if _, err = p.RecoverVolume(ctx, "v1"); err != nil { + t.Fatal(err) + } + t.Fatal("crash boundary not reached") + } + root := t.TempDir() + remote := storage.NewMemChunkRemote() + source := mappedProviderV3(t, t.TempDir(), remote) + if _, err := source.EnsureStorage("v1"); err != nil { + t.Fatal(err) + } + if _, err := source.RecoverVolume(ctx, "v1"); err != nil { + t.Fatal(err) + } + for _, lba := range []int64{5, 9} { + if n, err := source.Backend("v1").Write(ctx, lba*4096, bytes.Repeat([]byte{0x11}, 4096)); err != nil || n != 4096 { + t.Fatal(n, err) + } + } + if err := source.Backend("v1").Sync(ctx); err != nil { + t.Fatal(err) + } + if _, err := source.CaptureVolume(ctx, "v1"); err != nil { + t.Fatal(err) + } + if err := source.Close(); err != nil { + t.Fatal(err) + } + head, err := remote.GetHead(ctx) + if err != nil { + t.Fatal(err) + } + img := freshCrashImage{Head: head, Objects: map[string][]byte{}} + for _, ref := range head.Chunks { + data, e := remote.Get(ctx, ref.Key) + if e != nil { + t.Fatal(e) + } + img.Objects[ref.Key] = data + } + raw, err := json.Marshal(img) + if err != nil { + t.Fatal(err) + } + if err = os.WriteFile(filepath.Join(root, "remote.json"), raw, 0600); err != nil { + t.Fatal(err) + } + cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestDurableProviderV3_FreshMarkerCrashKeepsCompletedBASE$", "-test.v") + cmd.WaitDelay = 2 * time.Second + cmd.Env = append(os.Environ(), "SWBLOCK_V3_FRESH_CRASH_ROOT="+root, "SWBLOCK_V3_FRESH_CRASH_MODE="+mode) + out, err := cmd.CombinedOutput() + t.Logf("%s", out) + if err != nil { + t.Fatal(err) + } + if !bytes.Contains(out, []byte("FRESH_CRASH_READY presence_saved=true marker_present=true ack=9 no_Close=true")) { + t.Fatal("child missed crash boundary") + } + p := mappedProviderV3(t, root, freshCrashRemote(t, filepath.Join(root, "remote.json"))) + if _, err = os.Stat(chunkFreshMarker(p.volumePath("v1"))); err != nil { + t.Fatal("crash marker missing", err) + } + if _, err = p.EnsureStorage("v1"); err != nil { + t.Fatal(err) + } + if _, err = p.RecoverVolume(ctx, "v1"); err != nil { + t.Fatalf("post-presence/pre-marker crash lost completed BASE recovery: %v", err) + } + for lba, want := range map[int64][]byte{5: bytes.Repeat([]byte{0x79}, 4096), 9: make([]byte, 4096)} { + got := make([]byte, 4096) + if n, err := p.Backend("v1").Read(ctx, lba*4096, got); err != nil || n != 4096 || !bytes.Equal(got, want) { + t.Fatalf("crash BASE bytes lba=%d n=%d err=%v equal=%v", lba, n, err, bytes.Equal(got, want)) + } + } +} diff --git a/seaweed-block/core/storage/chunk_base_v3.go b/seaweed-block/core/storage/chunk_base_v3.go index 671ca37347..c9a7aa2a6f 100644 --- a/seaweed-block/core/storage/chunk_base_v3.go +++ b/seaweed-block/core/storage/chunk_base_v3.go @@ -60,7 +60,7 @@ func (l *chunkLayerImpl) holdBaseTransitionV3() (func(), error) { // installed publication only after all lower locks were released. presenceDurable := l.presenceVer == l.savedPresVer && len(l.absent) == 0 && len(l.localBlocks) == 0 l.stMu.Unlock() - if d.BaseState == BaseInstalled && presenceDurable { + if d.BaseState == BaseInstalled && presenceDurable && l.s.OwnerChunkAttachDurableV3() { l.s.AllowBaseRetirementV3() } l.capMu.Unlock() diff --git a/seaweed-block/core/storage/chunk_base_v3_test.go b/seaweed-block/core/storage/chunk_base_v3_test.go index 07ac3461c6..853c5aae41 100644 --- a/seaweed-block/core/storage/chunk_base_v3_test.go +++ b/seaweed-block/core/storage/chunk_base_v3_test.go @@ -194,6 +194,10 @@ func TestChunkLayerV3_BASEDrainJoinsClose(t *testing.T) { func TestChunkLayerV3_BASEPresenceBarrierFailureKeepsInstalling(t *testing.T) { s, f, l := mappedBASELayerV3(t) s.DeferBaseRetirementV3() + // Model an already committed provider owner before a later BASE. + if err := s.CommitChunkAttachV3(func() error { return nil }); err != nil { + t.Fatal(err) + } if _, e := s.Write(5, blk(0x11)); e != nil { t.Fatal(e) } diff --git a/seaweed-block/core/storage/chunk_layer.go b/seaweed-block/core/storage/chunk_layer.go index 9d86d4b287..a09501d28f 100644 --- a/seaweed-block/core/storage/chunk_layer.go +++ b/seaweed-block/core/storage/chunk_layer.go @@ -294,9 +294,6 @@ func attachChunkLayerImpl(s *WALStore, remote chunkRemote, cfg chunkLayerConfig) l.cancel() return nil, err } - if localBase { - s.AllowBaseRetirementV3() - } // local presence is durable above if l.hashMode { l.startReconcile() } diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 37958bab7a..3302bfc12c 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -463,4 +463,4 @@ Format v3 row 4 remains dark. Its typed scan result preserves trusted records, a - `INV-WAL-V3-CHUNK-BASE-001` (ACTIVE for dark mapped v3): begin/complete first take `installMu` exclusive, then the attached layer's whole-cut `capMu` drain, then existing capture/lifecycle/leader/store/descriptor/file-sync admission. The drain is registered with Close; no lower store lock is held while it waits. A pending unknown HEAD CAS refuses begin until settled. A newly published layer invalidates an outer hooks snapshot before descriptor mutation. Unsupported attached layers still refuse. No capture path takes installMu and no checkpoint callback takes capMu. - The release runs after lower locks, before installMu release. It derives the in-memory guard from the actual descriptor on success or failure, invalidates staging/reconciliation generations and keeps dirty coverage conservative. Installing capture has an early typed refusal. Presence becomes local before the existing completion barrier can publish installed; a failure retains installing. Completed BASE attach treats local bytes (including ZERO) as authoritative, persists presence, and captures through the owned UNKNOWN/max-LSN map without a legacy bitmap. A fresh provider marker does not authorize seeding an older HEAD over completed local BASE; the read-only installed-BASE query is revalidated by attachment admission. -- Controls: `TestChunkLayerV3_BASEIncompleteCaptureGuard`, `TestChunkLayerV3_BASEBeginDrainsWholeCut`, `TestChunkLayerV3_BASEBeginRefusesUnsettledCAS`, `TestChunkLayerV3_BASEDrainJoinsClose`, `TestChunkLayerV3_BASEPresenceBarrierFailureKeepsInstalling`, and the three actual provider controls in `provider_format_v3_base_test.go`. The unsupported-layer refusal remains in `TestBaseInstallV3BeginRefusesWithAnUnsupportedAttachedChunkLayer`. BASE descriptor states remain unchanged. Chunk-managed providers opt into deferred retirement immediately after create/open, before Recover. Installed local presence must be durable before attach or the outer completion release allows retirement; the next ordinary publication still checks the existing retirement coverage conditions. The opt-in is re-established on reopen, and unmanaged/unmapped stores retain ordinary retirement. A seed-only checkpoint is not local-image evidence. Controls `TestDurableProviderV3_DefersBASERetirementUntilLocalPresence` and `TestDurableProviderV3_SeedOnlyCheckpointStillRestoresHEAD` distinguish these cases; the presence-failure control also requires the gate remain deferred until successful retry. The external format model does not prove the chunk publication drain; the deterministic caller controls cover that seam. +- Controls: `TestChunkLayerV3_BASEIncompleteCaptureGuard`, `TestChunkLayerV3_BASEBeginDrainsWholeCut`, `TestChunkLayerV3_BASEBeginRefusesUnsettledCAS`, `TestChunkLayerV3_BASEDrainJoinsClose`, `TestChunkLayerV3_BASEPresenceBarrierFailureKeepsInstalling`, and the three actual provider controls in `provider_format_v3_base_test.go`. The unsupported-layer refusal remains in `TestBaseInstallV3BeginRefusesWithAnUnsupportedAttachedChunkLayer`. BASE descriptor states remain unchanged. Chunk-managed providers opt into deferred retirement immediately after create/open, before Recover. Both installed local presence and the provider durable attach point are required before retirement. The provider removes its fresh marker and fsyncs its directory under the store installMu-exclusive commit, then records per-open owner readiness; the callback never re-enters the store. Layer attach alone never allows retirement. Later completed transitions require owner readiness plus saved full presence before allowing; the next ordinary publication still checks existing retirement coverage. Actual subprocess controls crash after presence but before marker removal (both pre-existing installed BASE and attached completion), retaining the installed discriminator and recovering exact local data. The opt-in is re-established on reopen, and unmanaged/unmapped stores retain ordinary retirement. A seed-only checkpoint is not local-image evidence. Controls `TestDurableProviderV3_DefersBASERetirementUntilLocalPresence` and `TestDurableProviderV3_SeedOnlyCheckpointStillRestoresHEAD` distinguish these cases; the presence-failure control also requires the gate remain deferred until successful retry. The external format model does not prove the chunk publication drain; the deterministic caller controls cover that seam.