fix: require wrong-generation HEAD updates to refuse at startup

This commit is contained in:
pingqiu committed 2026-11-29 16:45:28 -08:00
1 parent 2d6664edb4
commit f3b0a678aa
7 files changed
+111 -15

No files matched your search

@@ -14,16 +14,17 @@ import (
// deleteSites is every non-test function in core/ and cmd/ that deletes a
// filer entry (DeleteEntry) or builds a volume directory name (VolumeDir),
// with what it deletes or where the name comes from. Nothing removes a
// deleted HEAD, a VOLUME or a volume directory, and a volume directory is
// deleted volume HEAD, a VOLUME or a volume directory, and a volume directory is
// named only from a reference (a root's owner name and id) or from the
// 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{
"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",
"core/frontend/chunkstore/layout/verify.go verifier.depHead -> VolumeDir": "HEAD dependent target name and full id",
"core/frontend/chunkstore/layout/verify.go verifier.orphans -> VolumeDir": "HEAD dependent target name and full id",
"core/frontend/chunkstore/layout/verify.go verifier.volumeID -> VolumeDir": "validation only: compare inspected VOLUME name/id with the already selected directory, never choose a different directory",
"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",
"core/frontend/chunkstore/layout/verify.go verifier.depHead -> VolumeDir": "HEAD dependent target name and full id",
"core/frontend/chunkstore/layout/verify.go verifier.orphans -> VolumeDir": "HEAD dependent target name and full id",
"core/frontend/chunkstore/layout/verify.go verifier.volumeID -> VolumeDir": "validation only: compare inspected VOLUME name/id with the already selected directory, never choose a different directory",
"cmd/blockvolume/main.go parseFlags -> VolumeDir": "validated master layout id and volume name; TestBlockvolumeLayoutIdentitySelectsTheLocalRoot",
"core/launcher/k8s_renderer.go durableRoot -> VolumeDir": "persisted workload plan layout id and name; launcher layout identity controls",
@@ -105,6 +106,6 @@ func TestDeleteAndDirectorySites_Enumeration(t *testing.T) {
sort.Strings(added)
sort.Strings(gone)
if len(added) != 0 || len(gone) != 0 {
t.Fatalf("delete or directory-naming sites changed: classify each (it must not remove a HEAD, a VOLUME or a volume directory, and a directory name must come from a reference or the master's record).\nnew: %v\ngone: %v", added, gone)
t.Fatalf("delete or directory-naming sites changed: classify each (it must not remove a volume HEAD, a VOLUME or a volume directory, and a directory name must come from a reference or the master's record).\nnew: %v\ngone: %v", added, gone)
}
}
@@ -26,6 +26,7 @@ import (
var headReaders = map[string]string{
"core/frontend/chunkstore/layout_verify.go verifyHead -> LookupEntry": "absent or unknown generation makes verify incomplete and suppresses MISSING/ORPHAN (TestVerifyLayoutRequiresStableHeadForMissingAndOrphans)",
"core/frontend/chunkstore/layout_verify.go verifyHead -> DecodeLayoutHeadEntry": "invalid inline envelope supplies no generation and cannot confirm findings (TestVerifyLayoutRequiresStableHeadForMissingAndOrphans)",
"core/frontend/chunkstore/startup_head_probe.go checkConditionalHead -> ReadHead": "absent/unreadable/changed disposable HEAD refuses startup; no volume HEAD is read (TestCatalogStartupRequiresWrongGenerationHeadRefusal)",
"cmd/blockvolume/chunk_maintenance.go newChunkMaintenance -> ReadHead": "diagnostic absent HEAD reports headGen0 and headGenError; it neither authorizes nor changes cleaning (TestMaintenanceStatusRealPassAndTimeout/head-absent)",
"core/frontend/chunkstore/layout_remote.go ProbeSnapshots -> ReadHead": "absent or failed reads do not infer snapshot deletion; open local activity skips the read (TestMaintenanceNoticesSnapshotDeleteWithoutNotification, TestLayoutSnapshotProbeSkipsOpenActivityWithoutReadingHEAD)",
"core/frontend/durable/provider_seal_replay.go readLayoutSeal -> ReadHead": "absent, unreadable and foreign layout proof refuse without cached success (TestLayoutPlainDetachReplayAfterRestartNeedsNoLegacyFactory)",
@@ -0,0 +1,62 @@
package chunkstore
import (
"bytes"
"context"
"errors"
"fmt"
"path"
"time"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
)
// ErrConditionalHead refuses admission when the filer cannot demonstrate the
// conditional HEAD update contract. The probe touches only its fresh directory.
var ErrConditionalHead = errors.New("chunkstore: conditional HEAD startup probe failed")
func (c *BCatalog) checkConditionalHead(ctx context.Context) (result error) {
ctx, cancel := context.WithTimeout(ctx, 10*time.Second)
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())
st, err := NewLayoutStore(c.f, c.b, root, id)
if err != nil {
return fmt.Errorf("%w: %v", ErrConditionalHead, err)
}
h := layout.Unclaimed(id, nil)
if err := st.UpdateHead(ctx, 0, h, layout.CauseCreate); err != nil {
return fmt.Errorf("%w: create disposable %s: %v", ErrConditionalHead, root, err)
}
// 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)
defer done()
if err := c.f.DeleteEntry(cleanup, root, layout.HeadName, nil); err != nil {
result = errors.Join(result, fmt.Errorf("%w: cleanup %s/HEAD: %v", ErrConditionalHead, root, err))
return
}
if err := c.f.DeleteEntry(cleanup, path.Dir(root), path.Base(root), nil); err != nil {
result = errors.Join(result, fmt.Errorf("%w: cleanup empty %s: %v", ErrConditionalHead, root, err))
}
}()
// The exclusive create installed generation 1. No other actor knows this
// random directory: expected generation 2 must be refused, not acknowledged.
if err := st.UpdateHead(ctx, 2, h, layout.CauseCreate); !errors.Is(err, layout.ErrPrecondition) {
return fmt.Errorf("%w: wrong-generation update of %s was not definitely refused: %v", ErrConditionalHead, root, err)
}
got, found, err := st.ReadHead(ctx)
if err != nil || !found || got.Gen != 1 {
return fmt.Errorf("%w: confirm unchanged %s: found=%v generation=%d error=%v", ErrConditionalHead, root, found, got.Gen, err)
}
before, _ := h.Encode()
after, err := got.Encode()
if err != nil || !bytes.Equal(before, after) {
return fmt.Errorf("%w: wrong-generation update changed %s", ErrConditionalHead, root)
}
return nil
}
@@ -18,7 +18,7 @@ import (
type conditionalProbeServer struct {
configFiler
store *fakeFiler
broken bool
mode string
updates int
}
@@ -31,10 +31,13 @@ func (f *conditionalProbeServer) CreateEntry(ctx context.Context, r *filerpb.Cre
func (f *conditionalProbeServer) UpdateEntry(ctx context.Context, r *filerpb.UpdateEntryRequest) (*filerpb.UpdateEntryResponse, error) {
f.mu.Lock()
f.updates++
broken := f.broken
mode := f.mode
f.mu.Unlock()
if mode == "transport-error" {
return nil, status.Error(codes.Unavailable, "lost answer")
}
expected := r.ExpectedExtended
if broken {
if mode == "ignores-conditions" || mode == "mutates-then-refuses" {
expected = nil
}
if err := f.store.UpdateEntry(ctx, r.Directory, r.Entry, expected); err != nil {
@@ -43,6 +46,10 @@ func (f *conditionalProbeServer) UpdateEntry(ctx context.Context, r *filerpb.Upd
}
return nil, status.Error(codes.Internal, err.Error())
}
if mode == "mutates-then-refuses" {
return nil, status.Error(codes.FailedPrecondition, "refused after mutation")
}
return &filerpb.UpdateEntryResponse{}, nil
}
func (f *conditionalProbeServer) LookupDirectoryEntry(ctx context.Context, r *filerpb.LookupDirectoryEntryRequest) (*filerpb.LookupDirectoryEntryResponse, error) {
@@ -62,14 +69,14 @@ func (f *conditionalProbeServer) DeleteEntry(ctx context.Context, r *filerpb.Del
return &filerpb.DeleteEntryResponse{}, nil
}
func TestCatalogStartupRequiresWrongGenerationHeadRefusal(t *testing.T) {
for _, broken := range []bool{true, false} {
t.Run(map[bool]string{true: "ignores-conditions", false: "conditional-filer"}[broken], func(t *testing.T) {
for _, mode := range []string{"ignores-conditions", "mutates-then-refuses", "transport-error", "conditional-filer"} {
t.Run(mode, func(t *testing.T) {
srv := grpc.NewServer()
lis, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
f := &conditionalProbeServer{store: newFakeFiler(), broken: broken}
f := &conditionalProbeServer{store: newFakeFiler(), mode: mode}
filerpb.RegisterSeaweedFilerServer(srv, f)
go func() { _ = srv.Serve(lis) }()
t.Cleanup(srv.Stop)
@@ -83,8 +90,8 @@ func TestCatalogStartupRequiresWrongGenerationHeadRefusal(t *testing.T) {
if client != nil {
defer client.Close()
}
if broken {
if err == nil || cat != nil || !strings.Contains(err.Error(), "conditional HEAD") {
if mode != "conditional-filer" {
if !errors.Is(err, ErrConditionalHead) || cat != nil || !strings.Contains(err.Error(), "conditional HEAD") {
t.Fatalf("broken conditional startup: cat=%v err=%v", cat, err)
}
} else if err != nil || cat == nil {
@@ -98,6 +105,9 @@ func TestCatalogStartupRequiresWrongGenerationHeadRefusal(t *testing.T) {
}
f.store.mu.Lock()
defer f.store.mu.Unlock()
if len(f.store.entries) != 1 {
t.Fatalf("store changed: %d entries", len(f.store.entries))
}
for p, e := range f.store.entries {
if p != "/blocks/existing/keep" || string(e.Content) != "untouched" {
t.Fatalf("probe leftover or unrelated change: %s", path.Clean(p))
@@ -18,5 +18,9 @@ func DialBCatalog(ctx context.Context, cfg SWFSConfig) (*BCatalog, *SWFS, error)
_ = client.Close()
return nil, nil, err
}
if err := cat.checkConditionalHead(ctx); err != nil {
_ = client.Close()
return nil, nil, err
}
return cat, client, nil
}
+1
View File
@@ -831,6 +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 outcomes or cleanup failures refuse admission. No volume HEAD is used for the probe. | M4 startup → Refused | `core/frontend/chunkstore/swfs_catalog.go` `DialBCatalog`; `startup_head_probe.go` `checkConditionalHead` | `TestCatalogStartupRequiresWrongGenerationHeadRefusal` | — | 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 |
@@ -1011,3 +1011,20 @@ the existing scheduler's capture, admission, retry and retention steps. It does
not enable an off schedule or change the subsequent daily/weekly slots. An off
or stopped schedule returns `schedule_not_running`. The route shares the other
chunk control routes' opt-in and loopback-only restrictions.
### Conditional HEAD startup check
Blockmaster and blockvolume catalog startup first checks the single-filer
configuration, then probes conditional HEAD updates in a random
`.startup-head-probe-<id>` directory under the configured chunk path. A fresh
inline HEAD at generation 1 must reject an update expecting generation 2 and
remain unchanged. Success, an ambiguous answer, a changed probe or a cleanup
failure refuses startup. No volume HEAD or chunk payload is touched.
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 answer may leave the named probe directory for inspection; the error
names it. This is an admission check, not an ongoing fence against later filer
configuration changes.