diff --git a/seaweed-block/core/frontend/chunkstore/head_readers_test.go b/seaweed-block/core/frontend/chunkstore/head_readers_test.go index 8df4870c86..0f2e071676 100644 --- a/seaweed-block/core/frontend/chunkstore/head_readers_test.go +++ b/seaweed-block/core/frontend/chunkstore/head_readers_test.go @@ -24,6 +24,7 @@ import ( // pins it. "GAP" marks a reader that takes an absent HEAD for an empty // one; a change that treats an absent HEAD as unknown flips those probes. var headReaders = map[string]string{ + "core/frontend/durable/provider_chunk.go maintenanceSnapshots -> ReadHead": "absent or failed reads do not infer snapshot deletion or ask for cleaning (TestMaintenanceNoticesSnapshotDeleteWithoutNotification)", "core/frontend/durable/provider_seal_replay.go readLayoutSeal -> ReadHead": "absent, unreadable and foreign layout proof refuse without cached success (TestLayoutPlainDetachReplayAfterRestartNeedsNoLegacyFactory)", "core/frontend/durable/provider_layout.go settleLayoutStop -> ReadHead": "absent refuses unknown stop outcome, never resumes (probe TestLayoutStopAbortMustConfirmItsOutcome)", "core/frontend/durable/provider_layout.go startLayoutRoot -> ReadHead": "the diagnostic re-read after Start refusal cannot turn an absent HEAD into a claim; Start already refused it (probe TestLayoutStoreMissingHEADRefusesStart)", diff --git a/seaweed-block/core/frontend/durable/maintenance_lineage_test.go b/seaweed-block/core/frontend/durable/maintenance_lineage_test.go index ca73eb8122..d407495d57 100644 --- a/seaweed-block/core/frontend/durable/maintenance_lineage_test.go +++ b/seaweed-block/core/frontend/durable/maintenance_lineage_test.go @@ -13,7 +13,8 @@ import ( type maintenanceStubLayer struct{ storage.ChunkLayer } -func (maintenanceStubLayer) Fenced() bool { return false } +func (maintenanceStubLayer) Fenced() bool { return false } +func (maintenanceStubLayer) Stats() storage.ChunkLayerStats { return storage.ChunkLayerStats{} } func TestMaintenanceRejectsForeignLineageBeforeAdmission(t *testing.T) { for _, field := range []string{"epoch", "replica", "endpoint", "handle", "layer"} { t.Run(field, func(t *testing.T) { diff --git a/seaweed-block/core/frontend/durable/maintenance_probe_test.go b/seaweed-block/core/frontend/durable/maintenance_probe_test.go new file mode 100644 index 0000000000..b687184b60 --- /dev/null +++ b/seaweed-block/core/frontend/durable/maintenance_probe_test.go @@ -0,0 +1,139 @@ +package durable + +import ( + "context" + "errors" + "testing" + "testing/synctest" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" +) + +type maintenanceProbeStore struct { + layout.StartStore + head layout.Head + found bool + err error + reads int +} + +func TestMaintenanceSnapshotProbeKeepsBusyRetryAndDirtyStartGate(t *testing.T) { + for _, dirty := range []bool{false, true} { + t.Run(map[bool]string{false: "busy", true: "dirty-start"}[dirty], func(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + st := &maintenanceProbeStore{found: true, head: layout.Head{Snapshots: map[string]layout.Snapshot{"a": {}}}} + layer := &firstAttemptLayer{} + passes := 0 + p := &DurableProvider{cfg: ProviderConfig{ + ChunkMaintenanceInterval: time.Hour, + ChunkLayoutHeadFor: func(string) (layout.StartStore, error) { return st, nil }, + ChunkMaintenance: func(context.Context, string) error { + passes++ + if passes == 1 { + return layout.ErrBusy + } + return nil + }, + }} + var start *maintenanceStart + if dirty { + start = &maintenanceStart{deadline: time.Now().Add(time.Hour)} + } + ctx, cancel := context.WithCancel(context.Background()) + done := make(chan struct{}) + go func() { + defer close(done) + p.chunkMaintenanceLoop(ctx, "v1", layer, func() bool { return true }, nil, start) + }() + defer func() { cancel(); <-done }() + synctest.Wait() + delete(st.head.Snapshots, "a") + time.Sleep(30 * time.Second) + synctest.Wait() + if dirty { + if passes != 0 { + t.Fatal("snapshot probe bypassed first store attempt") + } + layer.calls.Add(1) + time.Sleep(chunkSchedulePoll) + synctest.Wait() + } + if passes != 1 { + t.Fatalf("first pass=%d", passes) + } + time.Sleep(30 * time.Second) + synctest.Wait() + if passes != 2 { + t.Fatalf("busy retry=%d; waited for ordinary interval", passes) + } + }) + }) + } +} + +func (s *maintenanceProbeStore) ReadHead(context.Context) (layout.Head, bool, error) { + s.reads++ + return s.head, s.found, s.err +} + +func TestMaintenanceNoticesSnapshotDeleteWithoutNotification(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + st := &maintenanceProbeStore{found: true, head: layout.Head{Snapshots: map[string]layout.Snapshot{"a": {}, "b": {}}}} + passes := 0 + p := &DurableProvider{cfg: ProviderConfig{ + ChunkMaintenanceInterval: time.Hour, + ChunkLayoutHeadFor: func(string) (layout.StartStore, error) { return st, nil }, + ChunkMaintenance: func(context.Context, string) error { passes++; return nil }, + }} + ctx, cancel := context.WithCancel(context.Background()) + done := make(chan struct{}) + go func() { + defer close(done) + p.chunkMaintenanceLoop(ctx, "v1", &progressLoopLayer{}, func() bool { return true }, nil, nil) + }() + defer func() { cancel(); <-done }() + synctest.Wait() + if st.reads != 1 || passes != 0 { + t.Fatalf("baseline: reads=%d passes=%d", st.reads, passes) + } + delete(st.head.Snapshots, "a") + st.err = errors.New("filer unavailable") + time.Sleep(30 * time.Second) + synctest.Wait() + if passes != 0 { + t.Fatal("failed read inferred a deletion") + } + st.err = nil + st.found = false + time.Sleep(30 * time.Second) + synctest.Wait() + if passes != 0 { + t.Fatal("absent HEAD inferred a deletion") + } + st.found = true + time.Sleep(30 * time.Second) + synctest.Wait() + if passes != 1 || st.reads != 4 { + t.Fatalf("delete: reads=%d passes=%d", st.reads, passes) + } + time.Sleep(30 * time.Second) + synctest.Wait() + if passes != 1 || st.reads != 5 { + t.Fatalf("unchanged: reads=%d passes=%d", st.reads, passes) + } + st.head.Snapshots["c"] = layout.Snapshot{} + time.Sleep(30 * time.Second) + synctest.Wait() + if passes != 1 { + t.Fatal("growing snapshot set triggered cleaning") + } + delete(st.head.Snapshots, "c") + st.head.Snapshots["d"] = layout.Snapshot{} // equal count still contains a deletion + time.Sleep(30 * time.Second) + synctest.Wait() + if passes != 2 { + t.Fatal("new snapshot's deletion was not noticed") + } + }) +} diff --git a/seaweed-block/core/frontend/durable/provider_chunk.go b/seaweed-block/core/frontend/durable/provider_chunk.go index 8f472ad354..c7c918a23e 100644 --- a/seaweed-block/core/frontend/durable/provider_chunk.go +++ b/seaweed-block/core/frontend/durable/provider_chunk.go @@ -1042,6 +1042,30 @@ func (p *DurableProvider) maintenanceCurrent(volumeID string, h *volHandle, laye // (a cut session open: the cleaning never runs during one) is tried again. var maintenanceKickRetry = 30 * time.Second // a var only so tests can shorten it +// maintenanceSnapshotProbeInterval costs one HEAD read per attached volume per +// 30 seconds (about 7 reads/s at 200 volumes). This is a scheduling hint only; +// the existing cleaning session still requires an idle, matching HEAD. +const maintenanceSnapshotProbeInterval = 30 * time.Second + +func (p *DurableProvider) maintenanceSnapshots(ctx context.Context, volumeID string) (map[string]struct{}, error) { + st, err := p.cfg.ChunkLayoutHeadFor(volumeID) + if err != nil { + return nil, err + } + h, found, err := st.ReadHead(ctx) + if err != nil { + return nil, err + } + if !found { + return nil, layout.ErrHeadAbsent + } + names := make(map[string]struct{}, len(h.Snapshots)) + for name := range h.Snapshots { + names[name] = struct{}{} + } + return names, nil +} + // KickMaintenance asks the volume's maintenance loop for one pass now, as // after a snapshot delete. It reports whether a running loop was there to // ask (a stopped or ended loop is not); kicks coalesce, and the pass is the @@ -1085,12 +1109,71 @@ func (p *DurableProvider) chunkMaintenanceLoop(ctx context.Context, volumeID str } timer := time.NewTimer(time.Until(due)) defer timer.Stop() + var probe <-chan time.Time + var seen, observed map[string]struct{} + readSnapshots := func() { + if ctx.Err() != nil || layer.Fenced() || !current() { + return + } + timeout := p.cfg.ChunkMaintenanceTimeout + if timeout <= 0 { + timeout = time.Minute + } + _ = boundedPass(ctx, layer, current, timeout, func(readCtx context.Context) error { + names, err := p.maintenanceSnapshots(readCtx, volumeID) + if err == nil { + observed = names + } + return err + }) + } + if p.cfg.ChunkLayoutHeadFor != nil { + tick := time.NewTicker(maintenanceSnapshotProbeInterval) + defer tick.Stop() + probe = tick.C + readSnapshots() // establish a baseline without asking for a pass + seen = observed + } kicked := false for { select { case <-ctx.Done(): return case <-timer.C: + case <-probe: + if ctx.Err() != nil || layer.Fenced() || !current() { + return + } + observed = nil + readSnapshots() + if observed == nil { + continue + } // unknown is never an empty set + missing := false + for name := range seen { + if _, ok := observed[name]; !ok { + missing = true + break + } + } + if seen == nil { + seen = make(map[string]struct{}) + } + // Remember additions too: deleting one before the next ordinary pass + // must still be noticed. Keep missing names pending until a pass ends. + for name := range observed { + seen[name] = struct{}{} + } + if !missing { + continue + } + kicked = true + if !timer.Stop() { + select { + case <-timer.C: + default: + } + } case <-kick: kicked = true if !timer.Stop() { @@ -1130,6 +1213,9 @@ func (p *DurableProvider) chunkMaintenanceLoop(ctx context.Context, volumeID str err := boundedPass(ctx, layer, current, timeout, func(passCtx context.Context) error { return p.cfg.ChunkMaintenance(passCtx, volumeID) }) + if err == nil && observed != nil { + seen = observed + } if err != nil && ctx.Err() == nil { log.Printf("durable: maintenance volume=%s: %v", volumeID, err) } diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 026355c163..9ad5f49960 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -543,9 +543,7 @@ stateDiagram-v2 | any (Start) | idle at epoch e, claim id k | Start only: at HEAD's epoch it continues on the root carrying HEAD's claim id at or above HEAD's position, else refuses; above, a fresh root or the continuing lineage claims, validated against the HEAD the claim updates | start.go `Start`; claim.go `RunClaim` | `INV-SNAPK-START-ROOT-001`, `INV-SNAPK-START-LINEAGE-001`, `INV-SNAPK-START-POSITION-001`, `INV-SNAPK-START-ACTIVITY-001` | | idle | clean(c) | holder at HEAD's epoch (epoch, server and claim id); activity idle (clean(c) again is a replay) | clean.go `Head.BeginClean` | `INV-SNAPK-CLEAN-EXCL-001` | | clean(c) | idle | holder at HEAD's epoch (epoch, server and claim id); activity clean(c); over idle it succeeds without a write | clean.go `Head.EndClean` | `INV-SNAPK-CLEAN-EXCL-001` | -| clean(c) | clean(c), names removed | holder at HEAD's epoch (epoch, server and claim id) with clean(c) open (HEAD read once, after BeginClean); a name is deleted only if no root in HEAD (current or snapshot) names it in this volume's pool; each removal is a mark conditional on the plan's metadata, then a delete conditional on that mark | remove.go `RemoveUnreachable` | `INV-CLEAN-METADATA-001` | Cleaning preserves Current and snapshot roots and their segments. Dependents keep their snapshot in HEAD. Unnamed roots go before segments and chunks; reuse defeats conditional removal. | M9 clean | `core/frontend/chunkstore/layout/remove.go`; `core/frontend/chunkstore/clean_b.go` | `TestCleanerMetadataRetainsCurrentSnapshotAndDependent`, `TestCleanerMetadataReuseDefeatsLateMarkAndDelete`, `TestCleanerRecreatesRemovedRootBeforeRenamingIt` (`core/frontend/chunkstore/layout/clean_metadata_test.go`); `TestCleaningInterruptsAfterMetadataBeforeChunks` (`core/frontend/chunkstore/clean_cursor_test.go`) | CommitReach2 CPlan, CView, LandMark, LandDel | ACTIVE | -| `INV-CLEAN-CURSOR-001` | A bounded pass resumes at its phase, shard and last completed name, wraps after the final shard, and revalidates HEAD after each parallel tag plan. Reachability uses a conservative initial root set only within one session. | M9 clean (liveness) | `core/frontend/chunkstore/clean_b.go`; `core/frontend/chunkstore/layout/remove.go` | `TestCleaningCursorResumesAfterTimeoutAndWraps` (`core/frontend/chunkstore/clean_cursor_test.go`); `TestCleanerReachableOncePerShardAndRechecksHead`, `TestCleanerPlansTagsInBoundedParallelBeforeHead` (`core/frontend/chunkstore/layout/clean_scale_test.go`) | CommitReach2 CView | ACTIVE | -| `INV-SNAPK-REMOVE-MARK-001` | +| clean(c) | clean(c), names removed | holder at HEAD's epoch, server and claim id with clean(c) open; candidate tags precede each HEAD validation; unreachable roots, then segments, then chunks; mark conditional on the planned tag, delete conditional on its own mark | remove.go `Cleaner.removePlanned` | `INV-SNAPK-REMOVE-MARK-001`, `INV-CLEAN-METADATA-001`, `INV-CLEAN-CURSOR-001` | | idle (live or detached) | deleting | the master reserved the volume for delete (no line granted after), then no line holds a live lease, checked between the HEAD read and the update; no open activity, no snapshot with dependents; deleting again is a replay | delete.go `Head.MarkDeleting`, `RunMarkDeleting` (`DeleteAuthority`) | `INV-SNAPK-DELETE-ORDER-001` | | absent | deleted (tombstone) | the operator's remove-dependent, for a restore target without HEAD (never created, or a restore died between its two creates); one exclusive create, so a later HEAD create of the restore fails; a HEAD appearing first refuses | delete.go `OperatorReleaseDependent` (`TargetStore.CreateDeletedHead`) | `INV-SNAPK-TOMBSTONE-001`, `INV-SNAPK-HEAD-WRITE-001` | | source: any live | source: target released | by the target's volume id, from every snapshot: from DeleteVolume once the target's HEAD is deleting, or from the operator's command once the target is deleted, of another id, no longer naming the source, or tombstoned; an absent target writes nothing | delete.go `Head.ReleaseDependent`, `RunReleaseDependent`, `OperatorReleaseDependent` | `INV-SNAPK-RELEASE-001`, `INV-SNAPK-RELEASE-CALLERS-001`, `INV-SNAPK-RELEASE-OPERATOR-001` | @@ -1090,6 +1088,8 @@ Notes: | `INV-SNAPK-CLEAN-EXCL-001` | A cleaning and a snapshot exclude each other through HEAD's one activity field, so no name is removed while a snapshot is open; a claim voids an open cleaning. | M9 idle → clean → idle | `core/frontend/chunkstore/layout` `clean.go` `Head.BeginClean`, `Head.EndClean` | `TestBeginClean_Closure`, `TestEndClean_Closure`, `TestEndClean_IdleMeansNoActivityRemains`, `TestClean_ExcludesSnapshot`, `TestRunBeginClean_InterruptAtEveryStep`, `TestRunEndClean_InterruptAtEveryStep` | — (the snapshot kernel model is not in this repository) | ACTIVE | | `INV-CLEAN-HOLDER-PASS-001` | The holder's periodic cleaning runs as the identity Start established: Begin refuses any other holder, claim or epoch; a pass with no identity, or whose retention failed, removes nothing; every opened cleaning is closed, also on error. | M9 idle → clean → idle (holder pass) | `core/frontend/chunkstore/clean_b.go` `BCatalog.Clean`; `cmd/blockvolume/chunk_maintenance.go` `newChunkMaintenance` | `TestBCatalog_CleanIsHolderOnly`, `TestBCatalog_CleanClosesOnError`, `TestBCatalog_CleanRemovesOnlyUnreachable`, `TestBCatalog_CleanWaitsForAnOpenSnapshot`, `TestBCatalog_CleanAfterOverwriteAndSnapshotDelete` (`core/frontend/chunkstore/clean_b_test.go`); `TestMaintenanceCleansOnlyAsTheHolder`, `TestMaintenanceRetentionFailureNeverStartsCleaning` (`cmd/blockvolume/chunk_maintenance_test.go`) | — | ACTIVE | | `INV-SNAPK-READ-MISSING-001` | A read resolves root, segment, chunk; an index the root does not name is zeros; a root, segment or chunk the root reaches but the store lacks is ErrMissing, never zeros; bytes that do not hash to their name are ErrCorrupt; a foreign chunk is read from its owner's pool. | Content-named layout (read path, no state transition) | `core/frontend/chunkstore/layout` `read.go` `Reader.Open`, `Image.Segment`, `Image.Chunk` | `TestRead_AbsentIndexIsZeros`, `TestRead_ForeignChunkFromSourcePool`, `TestRead_MissingObjectIsAnErrorNeverZeros`, `TestRead_FetchFailureAndCorruption`, `TestRead_SegmentOfAnotherShardRefused` | — (the snapshot kernel model is not in this repository) | ACTIVE | +| `INV-CLEAN-METADATA-001` | Cleaning preserves Current and snapshot roots and their segments. Dependents keep their snapshot in HEAD. Unnamed roots go before segments and chunks; reuse defeats conditional removal. | M9 clean | `core/frontend/chunkstore/layout/remove.go`; `core/frontend/chunkstore/clean_b.go` | `TestCleanerMetadataRetainsCurrentSnapshotAndDependent`, `TestCleanerMetadataReuseDefeatsLateMarkAndDelete`, `TestCleanerRecreatesRemovedRootBeforeRenamingIt` (`core/frontend/chunkstore/layout/clean_metadata_test.go`); `TestCleaningInterruptsAfterMetadataBeforeChunks` (`core/frontend/chunkstore/clean_cursor_test.go`) | CommitReach2 CPlan, CView, LandMark, LandDel | ACTIVE | +| `INV-CLEAN-CURSOR-001` | A bounded pass resumes at its phase, shard and last completed name, wraps after the final shard, and revalidates HEAD after each parallel tag plan. Reachability uses a conservative initial root set only within one session. | M9 clean (liveness) | `core/frontend/chunkstore/clean_b.go`; `core/frontend/chunkstore/layout/remove.go` | `TestCleaningCursorResumesAfterTimeoutAndWraps` (`core/frontend/chunkstore/clean_cursor_test.go`); `TestCleanerReachableOncePerShardAndRechecksHead`, `TestCleanerPlansTagsInBoundedParallelBeforeHead` (`core/frontend/chunkstore/layout/clean_scale_test.go`) | CommitReach2 CView | ACTIVE | | `INV-SNAPK-REMOVE-MARK-001` | A content-named object is removed only inside the holder's own cleaning, when no root in HEAD names it: tags read first, HEAD read and validated after, then a mark conditional on the tag and a delete conditional on the mark. | M9 clean → clean (RemoveUnreachable) | `core/frontend/chunkstore/layout` `remove.go` `Cleaner.removePlanned` | `TestRemoveUnreachable_RemovesOnlyWhatNoRootNames`, `TestCleaningPass_InterruptAtEveryStep`, `TestHolderFunctions_RefuseAStaleHolder` | — (the snapshot kernel model is not in this repository) | ACTIVE | | `INV-SNAPK-REMOVE-STOP-001` | A reuse of an object after the plan, or after the mark, makes the remover's mark or delete fail its condition, however late it lands; an unreadable root stops the pass before any write; an open snapshot refuses it. | M9 clean → clean (RemoveUnreachable) | `core/frontend/chunkstore/layout` `remove.go` `Cleaner.removePlanned` | `TestRemoveUnreachable_ASuccessorAfterTheHeadViewDefeatsTheMark`, `TestRemoveUnreachable_ASuccessorBeforeTheHeadViewStopsThePass`, `TestRemoveUnreachable_AReuseAfterThePlanDefeatsTheMark`, `TestRemoveUnreachable_AReuseDefeatsALateMarkOrDelete`, `TestRemoveUnreachable_NothingRemovedOnAPartialView`, `TestRemoveUnreachable_RefusedOutsideItsCleaning` | — (the snapshot kernel model is not in this repository) | ACTIVE | | `INV-SNAPK-REMOVE-CONVERGE-001` | A name a cleaning marked and did not delete (the remover died in between) is planned again by the next cleaning: the re-mark replaces the old mark, so the dead remover's late delete fails, and every unreachable name goes once a cleaning completes. | M9 clean → clean | `core/frontend/chunkstore/layout` `remove.go` `Cleaner.removePlanned` | `TestRemoveUnreachable_ReclaimsAnAbandonedMark`, `TestCleaningPass_InterruptAtEveryStep`, `TestLayoutStoreCleaningReclaimsAnAbandonedMark` | — (the snapshot kernel model is not in this repository) | ACTIVE | diff --git a/seaweed-block/docs/standalone-deployment.md b/seaweed-block/docs/standalone-deployment.md index 23c16af3ae..f26d199a29 100644 --- a/seaweed-block/docs/standalone-deployment.md +++ b/seaweed-block/docs/standalone-deployment.md @@ -802,6 +802,13 @@ A restore makes a new volume from a snapshot. The new volume reads every chunk i A holder's cleaning removes unreferenced roots first, then segments, then chunk objects. Current and every snapshot root remain reachable; a restore dependent prevents its source snapshot from being deleted, including by retention. +The holder's maintenance loop probes HEAD every 30 seconds and asks for an early +pass when a previously observed snapshot name disappears, including after a +master-resolved snapshot delete. There is no notification channel or lease-loop +work. This adds one HEAD read per volume per 30 seconds (about 7 reads/s for 200 +volumes), plus a baseline read when maintenance starts. A failed or absent HEAD +read never means the snapshot set is empty. Space returns over several bounded +passes as the cleaning cursor advances; a probe does not bypass an active cut. Each object is marked conditionally on its planned tag and deleted conditionally on that mark. An object reused by a successor defeats those late writes.