From 7c4d6043c4ae3083644cd197ffeeac67b1a1dfa3 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 29 Nov 2026 19:47:48 -0800 Subject: [PATCH] Clean abandoned conditional HEAD probes on catalog startup --- .../cmd/blockvolume/single_filer_test.go | 12 ++ .../frontend/chunkstore/delete_sites_test.go | 1 + .../frontend/chunkstore/startup_head_probe.go | 86 ++++++++++++- .../chunkstore/startup_head_probe_test.go | 116 ++++++++++++++++++ seaweed-block/docs/design/invariants.md | 2 +- seaweed-block/docs/standalone-deployment.md | 11 +- 6 files changed, 221 insertions(+), 7 deletions(-) diff --git a/seaweed-block/cmd/blockvolume/single_filer_test.go b/seaweed-block/cmd/blockvolume/single_filer_test.go index 61706676e5..ee9ca860d7 100644 --- a/seaweed-block/cmd/blockvolume/single_filer_test.go +++ b/seaweed-block/cmd/blockvolume/single_filer_test.go @@ -42,6 +42,18 @@ func (f *groupFiler) LookupDirectoryEntry(ctx context.Context, r *filerpb.Lookup e, err := f.store.LookupEntry(ctx, r.Directory, r.Name) return &filerpb.LookupDirectoryEntryResponse{Entry: e}, groupFilerError(err) } +func (f *groupFiler) ListEntries(r *filerpb.ListEntriesRequest, stream grpc.ServerStreamingServer[filerpb.ListEntriesResponse]) error { + entries, err := f.store.ListEntries(stream.Context(), r.Directory, r.Prefix, r.StartFromFileName, r.Limit) + if err != nil { + return groupFilerError(err) + } + for _, e := range entries { + if err := stream.Send(&filerpb.ListEntriesResponse{Entry: e}); err != nil { + return err + } + } + return nil +} func (f *groupFiler) DeleteEntry(ctx context.Context, r *filerpb.DeleteEntryRequest) (*filerpb.DeleteEntryResponse, error) { if r.IsRecursive { return nil, status.Error(codes.InvalidArgument, "recursive delete not supported by this fixture") diff --git a/seaweed-block/core/frontend/chunkstore/delete_sites_test.go b/seaweed-block/core/frontend/chunkstore/delete_sites_test.go index 9d8dae6079..3009107683 100644 --- a/seaweed-block/core/frontend/chunkstore/delete_sites_test.go +++ b/seaweed-block/core/frontend/chunkstore/delete_sites_test.go @@ -19,6 +19,7 @@ import ( // master's volume record, never from a name given plus an id read from // that same directory. A new site fails until it is classified here. var deleteSites = map[string]string{ + "core/frontend/chunkstore/startup_head_probe.go BCatalog.cleanStartupProbes -> DeleteEntry": "only exact reserved 32-hex probe directories observed before the full active-probe grace; nonrecursive HEAD and empty directory deletes, no volume directory (TestConditionalHeadNextStartCleansCrashLeftovers)", "core/frontend/chunkstore/startup_head_probe.go BCatalog.checkConditionalHead -> DeleteEntry": "only the disposable HEAD and empty random probe directory after successful exclusive create; no volume directory is used (TestCatalogStartupRequiresWrongGenerationHeadRefusal)", "cmd/sw-block/chunk_verify.go chunkVerify -> VolumeDir": "master-resolved full id and requested name; offline form accepts an explicit directory without discovering an identity", "core/frontend/chunkstore/layout/verify.go verifier.chunks -> VolumeDir": "chunk reference's owner name and full id", diff --git a/seaweed-block/core/frontend/chunkstore/startup_head_probe.go b/seaweed-block/core/frontend/chunkstore/startup_head_probe.go index 08218afd59..445906182b 100644 --- a/seaweed-block/core/frontend/chunkstore/startup_head_probe.go +++ b/seaweed-block/core/frontend/chunkstore/startup_head_probe.go @@ -7,6 +7,7 @@ import ( "fmt" "log" "path" + "strings" "time" "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" @@ -14,7 +15,8 @@ import ( ) // ErrConditionalHead refuses admission when the filer cannot demonstrate the -// conditional HEAD update contract. The probe touches only its fresh directory. +// conditional HEAD update contract. Only reserved disposable probe directories +// are touched; volume directories are excluded. var ErrConditionalHead = errors.New("chunkstore: conditional HEAD startup probe failed") // probeFiler retains the exact synchronous update verdict before LayoutStore @@ -31,14 +33,90 @@ func (f *probeFiler) UpdateEntry(ctx context.Context, dir string, e *filerpb.Ent return err } +const ( + startupProbePrefix = ".startup-head-probe-" + startupProbeTimeout = 10 * time.Second + startupProbeCleanupTimeout = 5 * time.Second +) + +// Only exact reserved directory names qualify. A volume directory always ends +// in -<8 hex>, whereas this suffix is 32 uninterrupted hex digits. +func isStartupProbe(e *filerpb.Entry) bool { + if e == nil || !e.IsDirectory || !strings.HasPrefix(e.Name, startupProbePrefix) { + return false + } + _, err := layout.ParseVolumeID(strings.TrimPrefix(e.Name, startupProbePrefix)) + return err == nil +} + +// Capture names before waiting: another startup may still own an observed +// probe. Wait its entire exchange and cleanup budget, measured locally, before +// sweeping only those names. Newly created probes are never swept by this pass. +// Each RPC is bounded; a growing set of leftovers is not one fixed-time batch. +func (c *BCatalog) cleanStartupProbes(ctx context.Context) error { + var names []string + after := "" + for { + call, cancel := context.WithTimeout(ctx, startupProbeCleanupTimeout) + entries, err := c.f.ListEntries(call, c.base, startupProbePrefix, after, 100) + cancel() + if err != nil { + return fmt.Errorf("list leftover probes: %w", err) + } + for _, e := range entries { + if isStartupProbe(e) { + names = append(names, e.Name) + } + } + if len(entries) < 100 { + break + } + next := entries[len(entries)-1].Name + if next <= after { + return fmt.Errorf("list leftover probes did not advance at %q", after) + } + after = next + } + if len(names) == 0 { + return nil + } + timer := time.NewTimer(startupProbeTimeout + startupProbeCleanupTimeout) + defer timer.Stop() + select { + case <-ctx.Done(): + return ctx.Err() + case <-timer.C: + } + for _, name := range names { + root := path.Join(c.base, name) + call, cancel := context.WithTimeout(ctx, startupProbeCleanupTimeout) + err := c.f.DeleteEntry(call, root, layout.HeadName, nil) + cancel() + if err != nil { + log.Printf("chunkstore: WARNING conditional HEAD probe cleanup failed: leftover=%q error=%v", root, err) + continue + } + call, cancel = context.WithTimeout(ctx, startupProbeCleanupTimeout) + err = c.f.DeleteEntry(call, c.base, name, nil) + cancel() + if err != nil { + log.Printf("chunkstore: WARNING conditional HEAD probe cleanup failed: leftover=%q error=%v", root, err) + } + } + return nil +} + func (c *BCatalog) checkConditionalHead(ctx context.Context) error { - ctx, cancel := context.WithTimeout(ctx, 10*time.Second) + if err := c.cleanStartupProbes(ctx); err != nil { + log.Printf("chunkstore: WARNING conditional HEAD probe leftover sweep failed: base=%q error=%v", c.base, err) + } + ctx, cancel := context.WithTimeout(ctx, startupProbeTimeout) defer cancel() id, err := layout.NewVolumeID() if err != nil { return fmt.Errorf("%w: probe identity: %v", ErrConditionalHead, err) } - root := path.Join(c.base, ".startup-head-probe-"+id.String()) + root := path.Join(c.base, startupProbePrefix+id.String()) wire := &probeFiler{Filer: c.f} st, err := NewLayoutStore(wire, c.b, root, id) if err != nil { @@ -51,7 +129,7 @@ func (c *BCatalog) checkConditionalHead(ctx context.Context) error { // Only a successful exclusive create establishes cleanup ownership. Cleanup // has its own bounded context, even when the exchange's context expires. defer func() { - cleanup, done := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second) + cleanup, done := context.WithTimeout(context.WithoutCancel(ctx), startupProbeCleanupTimeout) defer done() if err := c.f.DeleteEntry(cleanup, root, layout.HeadName, nil); err != nil { log.Printf("chunkstore: WARNING conditional HEAD probe cleanup failed: leftover=%q error=%v", root, err) diff --git a/seaweed-block/core/frontend/chunkstore/startup_head_probe_test.go b/seaweed-block/core/frontend/chunkstore/startup_head_probe_test.go index 3ee81755ad..075d51921b 100644 --- a/seaweed-block/core/frontend/chunkstore/startup_head_probe_test.go +++ b/seaweed-block/core/frontend/chunkstore/startup_head_probe_test.go @@ -9,6 +9,7 @@ import ( "path" "strings" "testing" + "testing/synctest" "time" "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" @@ -69,6 +70,18 @@ func (f *conditionalProbeServer) LookupDirectoryEntry(ctx context.Context, r *fi } return &filerpb.LookupDirectoryEntryResponse{Entry: e}, nil } +func (f *conditionalProbeServer) ListEntries(r *filerpb.ListEntriesRequest, stream grpc.ServerStreamingServer[filerpb.ListEntriesResponse]) error { + entries, err := f.store.ListEntries(stream.Context(), r.Directory, r.Prefix, r.StartFromFileName, r.Limit) + if err != nil { + return err + } + for _, e := range entries { + if err := stream.Send(&filerpb.ListEntriesResponse{Entry: e}); err != nil { + return err + } + } + return nil +} func (f *conditionalProbeServer) DeleteEntry(ctx context.Context, r *filerpb.DeleteEntryRequest) (*filerpb.DeleteEntryResponse, error) { if (f.mode == "cleanup-head-error" && r.Name == "HEAD") || (f.mode == "cleanup-dir-error" && strings.HasPrefix(r.Name, ".startup-head-probe-")) { return nil, status.Error(codes.Unavailable, "injected cleanup failure") @@ -155,3 +168,106 @@ func TestCatalogStartupRequiresWrongGenerationHeadRefusal(t *testing.T) { }) } } + +// A probe abandoned between create and cleanup (or between its two deletes) +// is removed at the next start. A real volume with a near-matching name stays. +func TestConditionalHeadNextStartCleansCrashLeftovers(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + ctx := context.Background() + f, b := newFakeFiler(), newFakeBlobs() + c, err := NewBCatalog(f, b, "/blocks") + if err != nil { + t.Fatal(err) + } + id, err := layout.ParseVolumeID(strings.Repeat("1", 32)) + if err != nil { + t.Fatal(err) + } + abandoned := ".startup-head-probe-" + id.String() + empty := ".startup-head-probe-" + strings.Repeat("2", 32) + for _, name := range []string{abandoned, empty} { + if err := f.CreateEntry(ctx, "/blocks", &filerpb.Entry{Name: name, IsDirectory: true}, true); err != nil { + t.Fatal(err) + } + } + st, err := NewLayoutStore(f, b, path.Join("/blocks", abandoned), id) + if err != nil { + t.Fatal(err) + } + if err := st.UpdateHead(ctx, 0, layout.Unclaimed(id, nil), layout.CauseCreate); err != nil { + t.Fatal(err) + } + // Even a dot-prefixed valid volume name gets the extra '-<8 hex>' + // suffix, which cannot be the probe's uninterrupted 32-hex suffix. + real := VolumeRef{Name: ".startup-head-probe-" + id.String()[:24], ID: id} + if real.Dir() == abandoned { + t.Fatal("probe namespace overlaps a volume directory") + } + if _, err := c.CreateVolume(ctx, real, layout.Geometry{SizeBytes: 4096, BlockSize: 4096, ChunkBytes: 4096}); err != nil { + t.Fatal(err) + } + if err := f.CreateEntry(ctx, "/blocks", &filerpb.Entry{Name: real.Dir(), IsDirectory: true}, true); err != nil { + t.Fatal(err) + } + before, found, err := c.ReadHead(ctx, real) + if err != nil || !found { + t.Fatalf("real volume before: found=%v err=%v", found, err) + } + if err := c.checkConditionalHead(ctx); err != nil { + t.Fatal(err) + } + for _, name := range []string{abandoned, empty} { + if _, err := f.LookupEntry(ctx, "/blocks", name); !errors.Is(err, ErrNotFound) { + t.Fatalf("crash probe directory remains %s: %v", name, err) + } + if _, err := f.LookupEntry(ctx, path.Join("/blocks", name), layout.HeadName); !errors.Is(err, ErrNotFound) { + t.Fatalf("crash probe HEAD remains %s: %v", name, err) + } + } + after, found, err := c.ReadHead(ctx, real) + if err != nil || !found || after.Gen != before.Gen || after.VolumeID != before.VolumeID { + t.Fatalf("real volume changed: %+v %v", after, err) + } + if _, err := c.ReadVolume(ctx, real); err != nil { + t.Fatalf("real VOLUME changed: %v", err) + } + }) +} + +func TestConditionalHeadSweepWaitsAndLeavesNewProbes(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + ctx := context.Background() + f := newFakeFiler() + c, err := NewBCatalog(f, newFakeBlobs(), "/blocks") + if err != nil { + t.Fatal(err) + } + old := startupProbePrefix + strings.Repeat("3", 32) + fresh := startupProbePrefix + strings.Repeat("4", 32) + put := func(name string) { + t.Helper() + if err := f.CreateEntry(ctx, "/blocks", &filerpb.Entry{Name: name, IsDirectory: true}, true); err != nil { + t.Fatal(err) + } + } + put(old) + done := make(chan error, 1) + go func() { done <- c.cleanStartupProbes(ctx) }() + synctest.Wait() + time.Sleep(startupProbeTimeout + startupProbeCleanupTimeout - time.Nanosecond) + if _, err := f.LookupEntry(ctx, "/blocks", old); err != nil { + t.Fatalf("observed probe removed before grace: %v", err) + } + put(fresh) + time.Sleep(time.Nanosecond) + if err := <-done; err != nil { + t.Fatal(err) + } + if _, err := f.LookupEntry(ctx, "/blocks", old); !errors.Is(err, ErrNotFound) { + t.Fatalf("old probe remains: %v", err) + } + if _, err := f.LookupEntry(ctx, "/blocks", fresh); err != nil { + t.Fatalf("new probe removed: %v", err) + } + }) +} diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 648c367133..756baeb9cd 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -831,7 +831,7 @@ Notes: | `INV-WS-STALE-LOCAL-ROOT-001` | An old or rolled-back local root is refused by `layout.Start` before serving; synchronous and deferred attach end without retry and report the typed stale-root error and cure. A fresh root at its own epoch likewise ends with `ErrMissingLocalRoot` and its cure. | M4 Claiming → Refused | `core/frontend/durable/provider_layout.go` `startLayoutRoot`; `core/frontend/durable/provider_chunk.go` `recoverChunk`, `chunkAuthorityWait`; `core/frontend/durable/provider_startup.go` `endChunkStartup` | `TestLayoutProviderRefusesEmptyOwnEpochAndRemountedOldRoot`, `TestFinalLayoutStartRefusalTable` (`core/frontend/durable/provider_layout_test.go`, `provider_layout_start_class_test.go`) | — | ACTIVE | | `INV-WS-ONE-PROCESS-PER-HOST-001` | One host runs at most one live blockvolume per volume: each takes the volume's exclusive host lock before its store opens and holds it until the store closes; a second is refused before it opens anything, whatever its `--durable-root`. | M4 (start) → Attaching, Refused | `core/frontend/durable/provider.go` `DurableProvider.lockVolumeOnHost` | `TestOneLiveProcessPerVolumePerHost`, `TestHostVolumeLockDirectoryCreatedOrRefused`, `TestHostVolumeLockRefusesNonDirectoryLockPath`, `TestHostVolumeLockTakesReadOnlyLockFile` (`core/frontend/durable/one_process_per_volume_test.go`); `TestHostVolumeLockCreatesParent0755AndLocks0700`, `TestHostVolumeLockKeepsExistingDirectoryModes` (`core/frontend/durable/volume_lock_parent_mode_test.go`); `TestVolumeLockDirTestOnlyRefusedUnderSystemd` (`cmd/blockvolume/volume_lock_flag_test.go`) | — | ACTIVE | | `INV-CHUNK-LEASE-REQUIRED-001` | Blockvolume refuses walstore-chunk startup without --workspace-lease before any host or store is opened. The refusal names concurrent acknowledging writers and acknowledged-write loss after a forced move; plain walstore startup is unchanged. | M4 startup → Refused | `cmd/blockvolume/main.go` `parseFlags` | `TestChunkVolumeRequiresWorkspaceLeaseBeforeStart` | — | ACTIVE | -| `INV-WS-CONDITIONAL-HEAD-001` | Catalog startup requires a wrong-generation conditional update of a disposable HEAD to be definitely refused and leave its bytes and generation unchanged. Unknown probe outcomes refuse admission; cleanup failures only warn with the leftover path. No volume HEAD is used. | M4 startup → Refused | `core/frontend/chunkstore/swfs_catalog.go` `DialBCatalog`; `startup_head_probe.go` `checkConditionalHead` | `TestCatalogStartupRequiresWrongGenerationHeadRefusal`, `TestLayoutIdentityWriterAndReaders` | — | ACTIVE | +| `INV-WS-CONDITIONAL-HEAD-001` | Catalog startup requires a wrong-generation conditional update of a disposable HEAD to be definitely refused and leave its bytes and generation unchanged. Unknown probe outcomes refuse admission; cleanup failures only warn with the leftover path. No volume HEAD is used. | M4 startup → Refused | `core/frontend/chunkstore/swfs_catalog.go` `DialBCatalog`; `startup_head_probe.go` `checkConditionalHead` | `TestCatalogStartupRequiresWrongGenerationHeadRefusal`, `TestConditionalHeadNextStartCleansCrashLeftovers`, `TestConditionalHeadSweepWaitsAndLeavesNewProbes`, `TestLayoutIdentityWriterAndReaders` | — | ACTIVE | | `INV-WS-SINGLE-FILER-001` | Startup requires all configured masters to answer and agree on a leader; only that leader listing exactly the target filer and confirming leadership afterward admits. Followers' lists do not decide. Unknown views retry within 60 s. This census does not fence later filer registration. | M4 (startup) → Refused | `core/frontend/chunkstore/single_filer.go` `CheckSingleFiler`; `cmd/blockvolume/chunk_remote.go` `newChunkWiring`; `cmd/sw-block/chunk.go` `refuseUnlessSingleFiler` | `TestSingleFilerCensusUsesTheAgreedLeader`; `TestCheckSingleFilerRefusesAnotherOrSeveralFilers`, `TestCheckSingleFilerFailsClosed`, `TestCheckSingleFilerNeedsEveryMasterToAnswer`, `TestIsTargetComparesScopedAddresses`, `TestCheckSingleFilerPasses` (`core/frontend/chunkstore/single_filer_test.go`), `TestChunkWiringRefusesAMultiFilerGroup` (`cmd/blockvolume/single_filer_test.go`), `TestOpsChunk_WritingCommandsRunTheSingleFilerCheck` (`cmd/sw-block/chunk_start_check_test.go`), `TestOpsChunk_VerifyRunsTheSingleFilerCheck` (`cmd/sw-block/chunk_verify_test.go`) | — | ACTIVE | | `INV-WS-LEASE-REGRANT-001` | Re-grant after expiry keeps the same holder and epoch, with no pending move or revocation, a certain store, and one durable write after the horizon/deadline plus skew barrier. Restart begins a new session and voids the old; ordinary reopen keeps HEAD identity (epoch, holder, claim) unchanged. | M2 Expired → Granted; M9 Start | `core/authority/workspace_lease_view.go` `regrantWorkspaceLease`; `core/authority/workspace.go` `forcedMoveBarrierLocked`; `core/frontend/chunkstore/layout/start.go` `Start` | `TestWorkspaceLeaseExpiredSameHolderRegrantIsDurable`, `TestWorkspaceLeaseRegrantWaitsForFullSkew`, `TestWorkspaceLeaseRegrantDefeatsAlreadyPassedForcedPreflight`, `TestWorkspaceLeaseForcedIssueDefeatsOldHolderRegrant`, `TestWorkspaceLeaseRegrantWaitsForDurabilityAndLatchesFailure` (`core/authority/workspace_regrant_test.go`); `TestWorkspaceLeaseRegrantPreservesLocalLogThroughFirstCut` (`core/authority/workspace_regrant_storage_test.go`); `TestStart_OwnEpochFreshRootRefusedBeforeClaim`, `TestStart_OwnEpochSameRootContinues` (`core/frontend/chunkstore/layout/start_test.go`); `TestClaim_WritesItsClaimID`, `TestRunClaim_VoidsTheOldSession` (`core/frontend/chunkstore/layout/claim_test.go`); `TestLocalReopenClaimsBeforeServing` (`core/frontend/durable/provider_reopen_belt_test.go`) | `WorkspaceRegrant` `NoDualServingInc`, `RegrantNoLoss`, `DiskCoversMemory`; `INV-SNAPK-START-ROOT-001` | ACTIVE | | `INV-WS-LEASE-001` | A host admits frontend I/O and cuts only under an unexpired lease for its exact `{volume, replica, epoch}`; a fenced guard never reopens, even on a late renewal reply. | M4 lease guard: Valid → Fenced | `core/host/volume/workspace_lease.go` `permits`, `Refresh` | `TestWorkspaceLeaseExpiryFencesWithoutTimerAndCannotReopen`, `TestWorkspaceDelayedRenewalCannotUndoExpiry` (`core/host/volume/workspace_lease_test.go`); `TestWorkspaceHostRequiresLeaseBeforeFrontendAndCut` (`core/host/volume/workspace_runtime_test.go`); `TestWorkspacePausedGranteeRefusedAtAttach` (`core/host/master/workspace_paused_grantee_test.go`) | `WorkspaceTakeover` `NoDualServing` | ACTIVE | diff --git a/seaweed-block/docs/standalone-deployment.md b/seaweed-block/docs/standalone-deployment.md index 0538b0f1b9..2bf73f95cc 100644 --- a/seaweed-block/docs/standalone-deployment.md +++ b/seaweed-block/docs/standalone-deployment.md @@ -1031,10 +1031,17 @@ create. The exchange is bounded by 10 seconds plus up to 5 seconds for non-recursive cleanup, in addition to the single-filer census. The service account needs -create/read/update/delete permission under the chunk path. A failed or lost +create/read/list/update/delete permission under the chunk path. A failed or lost create answer may leave the named probe directory for inspection; the error names it. A daemon killed before cleanup can also leave a `.startup-head-probe-` directory; these disposable probe directories are safe -to delete, and the product does not sweep them automatically. This is an +to delete. At the next catalog start, the product lists exact reserved probe +names before creating its own probe. If any exist, it waits the existing +10-second exchange plus 5-second cleanup window before removing only the +observed HEAD entries and empty directories, non-recursively. Newly listed +names with anything other than 32 lower-case nonzero hex digits after the prefix +are not probes; real volume directories end in a separate `-<8 hex>` suffix. +Each sweep RPC has a 5-second bound; a failed sweep logs a warning and a later +start retries. The extra wait occurs only when leftovers were observed. This is an admission check, not an ongoing fence against later filer configuration changes.