From 665f1f7563a42c656be406258aa8241f700641fe Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 24 Nov 2026 07:56:39 -0800 Subject: [PATCH 01/19] test: a failed directory fsync must fail every authority store write (red) Co-Authored-By: Claude Opus 5.5 --- .../authority_store_dir_fsync_test.go | 36 +++++++++++++++++++ .../core/authority/authority_store_file.go | 16 +++++++++ 2 files changed, 52 insertions(+) create mode 100644 seaweed-block/core/authority/authority_store_dir_fsync_test.go diff --git a/seaweed-block/core/authority/authority_store_dir_fsync_test.go b/seaweed-block/core/authority/authority_store_dir_fsync_test.go new file mode 100644 index 0000000000..f3ebb22629 --- /dev/null +++ b/seaweed-block/core/authority/authority_store_dir_fsync_test.go @@ -0,0 +1,36 @@ +package authority + +import ( + "errors" + "strings" + "testing" +) + +// A record's rename is durable only after the directory fsync: a Put whose +// directory fsync fails must fail (fail closed), for every record, not only +// for workspace (lease) records. Otherwise the caller believes a write that +// a crash can undo. +func TestPutFailsWhenTheDirectoryFsyncFails(t *testing.T) { + for _, c := range []struct { + name string + rec DurableRecord + }{ + {"assignment record", DurableRecord{VolumeID: "v1", ReplicaID: "r1", Epoch: 1, EndpointVersion: 1, DataAddr: "d", CtrlAddr: "c", WriteSeq: 1}}, + {"workspace record", DurableRecord{VolumeID: "v2", ReplicaID: "r1", Epoch: 1, EndpointVersion: 1, DataAddr: "d", CtrlAddr: "c", WriteSeq: 1, + Workspace: &WorkspaceState{Lease: &WorkspaceLease{ReplicaID: "r1", Epoch: 1}}}}, + } { + t.Run(c.name, func(t *testing.T) { + s, err := NewFileAuthorityStore(t.TempDir()) + if err != nil { + t.Fatal(err) + } + defer s.Close() + SetDirSyncFaultForTest(func() error { return errors.New("injected directory fsync failure") }) + defer SetDirSyncFaultForTest(nil) + err = s.Put(c.rec) + if err == nil || !strings.Contains(err.Error(), "injected directory fsync failure") { + t.Fatalf("Put with a failed directory fsync: %v; want it to fail", err) + } + }) + } +} diff --git a/seaweed-block/core/authority/authority_store_file.go b/seaweed-block/core/authority/authority_store_file.go index e27dff65f2..b099f6385e 100644 --- a/seaweed-block/core/authority/authority_store_file.go +++ b/seaweed-block/core/authority/authority_store_file.go @@ -26,6 +26,19 @@ func SetPutAfterRenameFaultForTest(hook func(DurableRecord) error) { putAfterRenameFault.Store(&hook) } +// dirSyncFault, when set, replaces the directory fsync after the rename in +// every FileAuthorityStore.Put. Tests only. +var dirSyncFault atomic.Pointer[func() error] + +// SetDirSyncFaultForTest installs (nil clears) that fault. +func SetDirSyncFaultForTest(fault func() error) { + if fault == nil { + dirSyncFault.Store(nil) + return + } + dirSyncFault.Store(&fault) +} + // ============================================================ // P14 S5 — File-Per-Volume Authority Store // @@ -217,6 +230,9 @@ func (s *FileAuthorityStore) Put(record DurableRecord) error { // supported; skip silently. if d, derr := os.Open(s.dir); derr == nil { syncErr := d.Sync() + if f := dirSyncFault.Load(); f != nil { + syncErr = (*f)() + } closeErr := d.Close() if record.Workspace != nil { if syncErr != nil { From 6537dde7329e7362cbad0195466fe0bb6138cccd Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 24 Nov 2026 08:01:37 -0800 Subject: [PATCH 02/19] fix: a failed directory fsync fails every authority store write The directory fsync after the rename was best-effort for every record but a workspace lease: its error was ignored, so a write a crash could undo was reported as written. It now fails closed for every record. Windows, which cannot fsync a directory, skips it as before. Co-Authored-By: Claude Opus 5.5 --- .../core/authority/authority_store_file.go | 42 ++++++++++--------- 1 file changed, 23 insertions(+), 19 deletions(-) diff --git a/seaweed-block/core/authority/authority_store_file.go b/seaweed-block/core/authority/authority_store_file.go index b099f6385e..e4430d092c 100644 --- a/seaweed-block/core/authority/authority_store_file.go +++ b/seaweed-block/core/authority/authority_store_file.go @@ -4,6 +4,7 @@ import ( "fmt" "os" "path/filepath" + "runtime" "strings" "sync" "sync/atomic" @@ -225,25 +226,28 @@ func (s *FileAuthorityStore) Put(record DurableRecord) error { } } - // Best-effort fsync the directory so the rename is durable. - // On Windows, opening directories as files for fsync is not - // supported; skip silently. - if d, derr := os.Open(s.dir); derr == nil { - syncErr := d.Sync() - if f := dirSyncFault.Load(); f != nil { - syncErr = (*f)() - } - closeErr := d.Close() - if record.Workspace != nil { - if syncErr != nil { - return fmt.Errorf("authority_store: workspace directory fsync: %w", syncErr) - } - if closeErr != nil { - return fmt.Errorf("authority_store: workspace directory close: %w", closeErr) - } - } - } else if record.Workspace != nil { - return fmt.Errorf("authority_store: workspace directory open: %w", derr) + // Fsync the directory so the rename is durable. Every record fails + // closed: a write whose rename a crash can undo is not reported as + // written (an authority record, like a workspace lease, is believed + // by its caller). Windows cannot fsync a directory (NTFS journals the + // rename itself); the product runs on Linux. + if runtime.GOOS == "windows" && dirSyncFault.Load() == nil { + return nil + } + d, derr := os.Open(s.dir) + if derr != nil { + return fmt.Errorf("authority_store: directory open: %w", derr) + } + syncErr := d.Sync() + if f := dirSyncFault.Load(); f != nil { + syncErr = (*f)() + } + closeErr := d.Close() + if syncErr != nil { + return fmt.Errorf("authority_store: directory fsync: %w", syncErr) + } + if closeErr != nil { + return fmt.Errorf("authority_store: directory close: %w", closeErr) } return nil } From b07d7cde4558195b51f46c0a0edee74fb7006dae Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 24 Nov 2026 08:07:50 -0800 Subject: [PATCH 03/19] docs: INV-AUTH-PERSIST-BEFORE-PUBLISH-001 names the directory fsync and its test Co-Authored-By: Claude Opus 5.5 --- seaweed-block/docs/design/invariants.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index ace443cffe..f5dd829f92 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -674,7 +674,7 @@ Notes: |---|---|---|---|---|---|---| | `INV-AUTH-HOLDER-IDENTITY-001` | A primary holder is the pair (server id, replica id): every site that decides holdership (adopting a fact, lease first grant, renew, re-grant, HEAD claim, superseded exit) compares both; a missing server id is refused, never guessed. | AUTHORITY: PRIMARY holdership (supporting replicas are not holders) | `core/host/volume/host.go` `applyFact`, `IsSuperseded`, `recordOtherLine`; `assignment_holder.go` `assignmentNamesSelf`, `observeForeignHolder`, `refusePrimaryAssignment`; `host.go` `IsSuperseded`; `core/host/master/services.go` `SubscribeAssignments`; `workspace_service.go` `holderMatches`, `RenewWorkspaceLease`, `AckWorkspaceRevoked`; `cmd/blockvolume/chunk_remote.go` `chunkHolder`; `core/storage/chunk_restore.go` `ClaimChunkHead`; superseded exit covered by #409; `core/host/master/workspace_binding.go` `workspaceLineOwner`, `workspaceSourceHost`; `core/authority/assignment_owner.go` `captureAssignmentOwner`; `core/host/master/services.go` `assignmentFact`; `core/host/master/server_host_identity.go` `refuseServerIDFromOtherHost` (from `ReportHeartbeat`), `refuseWorkspaceHolderHost` (from `holderMatches` and, for a workspace volume, `SubscribeAssignments`), `holderSlotFact` (from `QueryVolumeStatus` and `observationVolume`/`observationReplicas`); `core/csi/master_backend.go` `primaryOwnedFrontends` (a CSI target only from a usable primary frontend); `core/authority/snapshot_builder.go` `expectOwnerForLine` (a moved line's replica facts and endpoint refreshes only from its owner, #425) | `TestAssignmentHolderIdentityRestartedOldProcess`, `TestAssignmentHolderIdentityMatchingServerStillAdopts`, `TestAssignmentHolderIdentityFencesPreviouslyHealthySameReplica`, `TestAssignmentHolderIdentityAdoptsAndWarnsCarriedEndpointMismatch`, `TestAssignmentHolderIdentityForeignStreamOrdering`, `TestAssignmentHolderIdentityForcedMoveRefusesEveryDeliveredVersion`, `TestAssignmentHolderIdentitySameEpochCannotChangeServer` (`core/host/volume/assignment_holder_test.go`); `TestWorkspaceLeaseGuardCarriesHolderServerIdentity` (`core/host/volume/workspace_holder_identity_test.go`); `TestWorkspaceLeaseRequiresHolderServerForGrantRenewAndRegrant`, `TestWorkspaceRevocationACKRequiresHolderServer` (`core/host/master/workspace_holder_identity_test.go`); `TestWorkspaceRPCCleanMovePreservesReplicaIdentity` (`core/host/master/workspace_service_test.go`); HEAD claim: `TestChunkHolderIsServerAndReplica` (`cmd/blockvolume/chunk_remote_test.go`), `TestWALStoreChunk_SameReplicaOnAnotherServerIsFenced` (`core/frontend/durable/provider_chunk_holder_test.go`); superseded exit: covered by #409 (server-id/replica-id pair, never replica alone); supporting replicas are not holders; descriptor identity not in this row; `TestWorkspaceLineOwnerIssuedAndHistorical` (`core/host/master/workspace_line_owner_test.go`), `TestWorkspaceRenewalRPCDuringHeldSameVolumeReservation` (`core/host/master/workspace_lease_horizon_test.go`); `TestAssignmentFactKeepsCapturedMoveOwnerWithoutReadableJournal` (`core/host/master/assignment_fact_owner_test.go`), `TestAssignmentOwnerReservedAndIssuedCapture` (`core/authority/assignment_owner_test.go`), `TestWorkspaceCrashAfterJournalBeforeEpochResumesSameGrant` (`core/authority/workspace_test.go`); `TestServerIDRefusedFromAHostOtherThanItsRegisteredOne`, `TestWorkspaceHolderRefusedFromAnotherHostAtRenewAckAndStream`, `TestPortalAndPrimaryComeFromTheLineServerNotTheFreshestHeartbeat`, `TestDisplayedPrimaryIsTheIssuedHolderNotThePlacementSlot`, `TestStatusListsNoFrontendWhenThePrimaryEvidenceIsMissing`, `TestCSIPublishesNoTargetWhenThePrimaryFrontendIsMissingOrRejected`, `TestDeletionReservedWorkspaceVolumeKeepsTheStreamHostCheck` (`core/host/master/server_host_identity_test.go`); `TestPublishTargetIsPrimaryOwned` (`core/csi/primary_owned_frontend_test.go`). Host scope: registered advertised-host consistency, not process uniqueness; a workspace holder's server id must be registered (no first-seen binding: host addresses change); non-workspace heartbeats from an unregistered id are not checked. Limits: trusts the network peer address (no NAT or proxy between volume and master in OSS); not authentication; `TestBuildSnapshotTakesTheMovedLinesReplicaFromItsOwner` (`core/authority/line_owner_snapshot_test.go`); `TestProcedureForcedMoveWithTheOldHostReturning` (`cmd/blockvolume/procedure_gate_integration_test.go`, tags subprocess chunkstore_integration: every forced-epoch line carries the new owner's endpoints) | `WorkspaceRegrant` `NoForeignAdoption`, `TargetNotFencedByOwnLine` (round 4 pinned simulations only; exhaustive combo10 pending) | ACTIVE | | `INV-AUTH-EPOCH-MINT-001` | Only the publisher mints epochs; a reassignment takes the per-volume maximum epoch plus one, also after a restart. | M2 Bound → Reassigned | `core/authority/authority.go` `applyWithWorkspaceMove`, `maxPublishedEpochForVolume` | `TestG8_0_Publisher_ReassignAdvancesPerVolumeEpochAcrossReplicaSlots` (`core/authority/g8_0_authority_failover_test.go`); `TestDurableAuthority_PublisherAdvancesFromReloaded` (`core/authority/authority_restart_test.go`); `TestG9F2_AssignmentRequestShapeHasNoEpochOrEndpointVersion` (`core/host/master/authority_request_bridge_test.go`) | `ControlPlane` `UniqueEpoch` | ACTIVE | -| `INV-AUTH-PERSIST-BEFORE-PUBLISH-001` | With an authority store configured, an assignment is written to the store before memory or any subscriber sees it, and a failed write does not publish it: see M2 any → (store write first). | M2 any → (store write first) | `core/authority/authority.go` `applyWithWorkspaceMove` | `TestDurableAuthority_PutFailureRollsBackInMemoryState` (`core/authority/authority_restart_test.go`) | `ControlPlane` `UniqueEpoch` | ACTIVE | +| `INV-AUTH-PERSIST-BEFORE-PUBLISH-001` | With an authority store configured, an assignment is written to the store before memory or any subscriber sees it, and a failed write does not publish it: see M2 any → (store write first). | M2 any → (store write first) | `core/authority/authority.go` `applyWithWorkspaceMove`; `core/authority/authority_store_file.go` `Put` (the directory fsync after the rename fails the write for every record) | `TestDurableAuthority_PutFailureRollsBackInMemoryState` (`core/authority/authority_restart_test.go`); `TestPutFailsWhenTheDirectoryFsyncFails` (`core/authority/authority_store_dir_fsync_test.go`) | `ControlPlane` `UniqueEpoch` | ACTIVE | | `INV-AUTH-MOVE-JOURNAL-001` | A workspace move's epoch is issued only after its journal record is durable, and one move request id gets exactly one epoch, also across restarts. | M2 MoveReserved → MoveIssued | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `MoveWorkspace`, `sameWorkspaceRequest` | `TestWorkspaceMoveCannotIssueEpochWithoutJournal`, `TestWorkspaceCrashAfterJournalBeforeEpochResumesSameGrant` (`core/authority/workspace_test.go`); `TestWorkspaceReplayedIssueStartsGranteeLease` (`core/authority/workspace_unclaimed_grant_test.go`) | `ControlPlane` `Idempotent`, `JournalComplete` | ACTIVE | | `INV-AUTH-UNCERTAIN-001` | A failed authority write for a workspace volume, a lease extension included, latches uncertainty until a restart reloads the store: later authority changes and new or extended grants for that volume are refused. See M2 any (workspace) → Uncertain and Uncertain → Uncertain (move answer). | M2 any (workspace) → Uncertain; Uncertain → Uncertain (move answer) | `core/authority/authority.go` `applyWithWorkspaceMove`; `core/authority/workspace.go` `persistWorkspaceLocked`; `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `extendWorkspaceLease`; `core/authority/workspace.go` `WorkspaceMoveOutcomeError`, `MoveWorkspace`; `core/host/master/workspace_service.go` `MoveWorkspace` | `TestWorkspaceAmbiguousExtensionLatchesUncertainty` (`core/authority/workspace_lease_horizon_test.go`); `TestWorkspaceUncertaintyPrecedesRequestRefusal` (`core/authority/workspace_outcome_uncertain_test.go`), `TestWorkspaceMoveUnknownPrecedesAdmissionRefusals` (`core/host/master/workspace_uncertain_precedence_test.go`), `TestWorkspaceUncertainIssueWriteIsTyped` (`core/authority/workspace_outcome_uncertain_test.go`) | `ControlPlane` `UniqueEpoch`; `WorkspaceMoveOutcome` `NoFalseRefusal`, `CallerEndTyped`, `UncertainReplyClass` | ACTIVE | | `INV-LEASE-VIEW-001` | Whenever the publisher lock is released, each volume's lease view, the renewal path's only input, equals derive(the published authority line, workspace state, uncertainty, store presence). | M2 every workspace transition | `core/authority/workspace_lease_view.go` `deriveLeaseLocked`, `refreshLeaseViewLocked`, `publishIssuedLeaseLocked`, `setLeaseDeadlineLocked`; `core/authority/authority.go` `applyWithWorkspaceMove`, `reloadFromStore`; `core/authority/workspace.go` `persistWorkspaceLocked` | `TestWorkspaceLeaseViewMatchesDeriveAfterEveryWriter`, `TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose` (`core/authority/workspace_lease_horizon_test.go`) | — | ACTIVE | From 7c7d1223de7944956c2226ffbe0a9bdec3da0fd2 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 24 Nov 2026 15:31:49 -0800 Subject: [PATCH 04/19] test: a directory fsync failure after the rename must fail-stop (red) The child process does one Put with an injected directory fsync failure; it must exit ExitDurabilityUnknown with the typed line and never return to its caller. The parent reloads the store: the record or none. Co-Authored-By: Claude Opus 5.5 --- .../authority_store_dir_fsync_test.go | 83 ++++++++++++++----- .../core/authority/authority_store_file.go | 5 ++ 2 files changed, 68 insertions(+), 20 deletions(-) diff --git a/seaweed-block/core/authority/authority_store_dir_fsync_test.go b/seaweed-block/core/authority/authority_store_dir_fsync_test.go index f3ebb22629..4affd1feb0 100644 --- a/seaweed-block/core/authority/authority_store_dir_fsync_test.go +++ b/seaweed-block/core/authority/authority_store_dir_fsync_test.go @@ -2,34 +2,77 @@ package authority import ( "errors" + "fmt" + "os" + "os/exec" "strings" "testing" ) -// A record's rename is durable only after the directory fsync: a Put whose -// directory fsync fails must fail (fail closed), for every record, not only -// for workspace (lease) records. Otherwise the caller believes a write that -// a crash can undo. -func TestPutFailsWhenTheDirectoryFsyncFails(t *testing.T) { - for _, c := range []struct { - name string - rec DurableRecord - }{ - {"assignment record", DurableRecord{VolumeID: "v1", ReplicaID: "r1", Epoch: 1, EndpointVersion: 1, DataAddr: "d", CtrlAddr: "c", WriteSeq: 1}}, - {"workspace record", DurableRecord{VolumeID: "v2", ReplicaID: "r1", Epoch: 1, EndpointVersion: 1, DataAddr: "d", CtrlAddr: "c", WriteSeq: 1, - Workspace: &WorkspaceState{Lease: &WorkspaceLease{ReplicaID: "r1", Epoch: 1}}}}, - } { - t.Run(c.name, func(t *testing.T) { - s, err := NewFileAuthorityStore(t.TempDir()) +const failStopHelperEnv = "SWB_AUTHORITY_FAILSTOP_DIR" + +func failStopRecord(kind string) DurableRecord { + r := DurableRecord{VolumeID: "v1", ReplicaID: "r1", Epoch: 7, EndpointVersion: 1, DataAddr: "d", CtrlAddr: "c", WriteSeq: 1} + if kind == "workspace" { + r.Workspace = &WorkspaceState{Lease: &WorkspaceLease{ReplicaID: "r1", Epoch: 7}} + } + return r +} + +// TestAuthorityStoreFailStopHelper is the child process of +// TestPutFailStopsWhenTheDirectoryFsyncFailsAfterRename: one Put with an +// injected directory fsync failure. Reaching the line after Put means Put +// returned to its caller, which the fail-stop rule forbids. +func TestAuthorityStoreFailStopHelper(t *testing.T) { + dir := os.Getenv(failStopHelperEnv) + if dir == "" { + t.Skip("helper process only") + } + s, err := NewFileAuthorityStore(dir) + if err != nil { + fmt.Println("HELPER-SETUP-FAILED", err) + os.Exit(3) + } + SetDirSyncFaultForTest(func() error { return errors.New("injected directory fsync failure") }) + err = s.Put(failStopRecord(os.Getenv(failStopHelperEnv + "_KIND"))) + fmt.Printf("PUT-RETURNED err=%v\n", err) + os.Exit(0) +} + +// A directory fsync failure after the rename leaves the record's durability +// unknown: blockmaster fail-stops (the conventional answer, PostgreSQL after +// fsyncgate). No caller is ever told "failed" for a record that may survive; +// the restart reloads whatever is on disk. Same rule for every record type. +func TestPutFailStopsWhenTheDirectoryFsyncFailsAfterRename(t *testing.T) { + for _, kind := range []string{"assignment", "workspace"} { + t.Run(kind, func(t *testing.T) { + dir := t.TempDir() + cmd := exec.Command(os.Args[0], "-test.run=^TestAuthorityStoreFailStopHelper$", "-test.count=1") + cmd.Env = append(os.Environ(), failStopHelperEnv+"="+dir, failStopHelperEnv+"_KIND="+kind) + out, err := cmd.CombinedOutput() + var exit *exec.ExitError + if !errors.As(err, &exit) || exit.ExitCode() != ExitDurabilityUnknown { + t.Fatalf("child: err=%v, want exit %d\n%s", err, ExitDurabilityUnknown, out) + } + if strings.Contains(string(out), "PUT-RETURNED") { + t.Fatalf("Put returned to its caller after a failed directory fsync:\n%s", out) + } + if !strings.Contains(string(out), "authority_store: FAIL-STOP: directory fsync after rename") || + !strings.Contains(string(out), "injected directory fsync failure") { + t.Fatalf("missing the typed fail-stop line:\n%s", out) + } + // The restart reloads whatever survived: the new record or none, never an error. + s, err := NewFileAuthorityStore(dir) if err != nil { t.Fatal(err) } defer s.Close() - SetDirSyncFaultForTest(func() error { return errors.New("injected directory fsync failure") }) - defer SetDirSyncFaultForTest(nil) - err = s.Put(c.rec) - if err == nil || !strings.Contains(err.Error(), "injected directory fsync failure") { - t.Fatalf("Put with a failed directory fsync: %v; want it to fail", err) + recs, err := s.Load() + if err != nil { + t.Fatalf("reload after the fail-stop: %v", err) + } + if len(recs) > 1 || (len(recs) == 1 && (recs[0].VolumeID != "v1" || recs[0].Epoch != 7)) { + t.Fatalf("reload after the fail-stop: %+v, want the written record or none", recs) } }) } diff --git a/seaweed-block/core/authority/authority_store_file.go b/seaweed-block/core/authority/authority_store_file.go index e4430d092c..d9c94b67c8 100644 --- a/seaweed-block/core/authority/authority_store_file.go +++ b/seaweed-block/core/authority/authority_store_file.go @@ -31,6 +31,11 @@ func SetPutAfterRenameFaultForTest(hook func(DurableRecord) error) { // every FileAuthorityStore.Put. Tests only. var dirSyncFault atomic.Pointer[func() error] +// ExitDurabilityUnknown is blockmaster's exit code when a record's rename +// may or may not survive a crash (sysexits EX_IOERR). Declared before the +// fail-stop exists so the red test compiles. +const ExitDurabilityUnknown = 74 + // SetDirSyncFaultForTest installs (nil clears) that fault. func SetDirSyncFaultForTest(fault func() error) { if fault == nil { From 6c0e1ad9e0282f6b8bfddf5b666911d5d421f6a0 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 24 Nov 2026 15:34:59 -0800 Subject: [PATCH 05/19] fix: fail-stop when the directory fsync after a rename fails The rename is done, so a failed directory open or fsync leaves the record's durability unknown. Reporting "failed" let a restart reload a write its caller had acted on as failed. blockmaster now exits (ExitDurabilityUnknown = 74, typed line) for every record type; the restart reloads whatever survived. A close error after a good fsync is reported written. Windows keeps its previous behaviour. The fault seam names the step (open, fsync, close). INV-AUTH-PERSIST-BEFORE-PUBLISH-001 rewritten to match. Co-Authored-By: Claude Opus 5.5 --- .../authority_store_dir_fsync_test.go | 58 +++++++++-- .../core/authority/authority_store_file.go | 98 +++++++++++++------ seaweed-block/docs/design/invariants.md | 6 +- 3 files changed, 122 insertions(+), 40 deletions(-) diff --git a/seaweed-block/core/authority/authority_store_dir_fsync_test.go b/seaweed-block/core/authority/authority_store_dir_fsync_test.go index 4affd1feb0..f34cd50981 100644 --- a/seaweed-block/core/authority/authority_store_dir_fsync_test.go +++ b/seaweed-block/core/authority/authority_store_dir_fsync_test.go @@ -5,6 +5,7 @@ import ( "fmt" "os" "os/exec" + "runtime" "strings" "testing" ) @@ -33,22 +34,32 @@ func TestAuthorityStoreFailStopHelper(t *testing.T) { fmt.Println("HELPER-SETUP-FAILED", err) os.Exit(3) } - SetDirSyncFaultForTest(func() error { return errors.New("injected directory fsync failure") }) + step := os.Getenv(failStopHelperEnv + "_STEP") + SetDirFaultForTest(func(at string) error { + if at == step { + return errors.New("injected directory " + step + " failure") + } + return nil + }) err = s.Put(failStopRecord(os.Getenv(failStopHelperEnv + "_KIND"))) fmt.Printf("PUT-RETURNED err=%v\n", err) os.Exit(0) } -// A directory fsync failure after the rename leaves the record's durability -// unknown: blockmaster fail-stops (the conventional answer, PostgreSQL after -// fsyncgate). No caller is ever told "failed" for a record that may survive; -// the restart reloads whatever is on disk. Same rule for every record type. +// A directory open or fsync failure after the rename leaves the record's +// durability unknown: blockmaster fail-stops (the conventional answer, +// PostgreSQL after fsyncgate). No caller is ever told "failed" for a record +// that may survive; the restart reloads whatever is on disk. Same rule for +// every record type. func TestPutFailStopsWhenTheDirectoryFsyncFailsAfterRename(t *testing.T) { - for _, kind := range []string{"assignment", "workspace"} { - t.Run(kind, func(t *testing.T) { + for _, c := range []struct{ kind, step string }{ + {"assignment", "fsync"}, {"workspace", "fsync"}, {"assignment", "open"}, {"workspace", "open"}, + } { + kind, step := c.kind, c.step + t.Run(kind+"/"+step, func(t *testing.T) { dir := t.TempDir() cmd := exec.Command(os.Args[0], "-test.run=^TestAuthorityStoreFailStopHelper$", "-test.count=1") - cmd.Env = append(os.Environ(), failStopHelperEnv+"="+dir, failStopHelperEnv+"_KIND="+kind) + cmd.Env = append(os.Environ(), failStopHelperEnv+"="+dir, failStopHelperEnv+"_KIND="+kind, failStopHelperEnv+"_STEP="+step) out, err := cmd.CombinedOutput() var exit *exec.ExitError if !errors.As(err, &exit) || exit.ExitCode() != ExitDurabilityUnknown { @@ -58,7 +69,7 @@ func TestPutFailStopsWhenTheDirectoryFsyncFailsAfterRename(t *testing.T) { t.Fatalf("Put returned to its caller after a failed directory fsync:\n%s", out) } if !strings.Contains(string(out), "authority_store: FAIL-STOP: directory fsync after rename") || - !strings.Contains(string(out), "injected directory fsync failure") { + !strings.Contains(string(out), "directory "+step+": injected directory "+step+" failure") { t.Fatalf("missing the typed fail-stop line:\n%s", out) } // The restart reloads whatever survived: the new record or none, never an error. @@ -77,3 +88,32 @@ func TestPutFailStopsWhenTheDirectoryFsyncFailsAfterRename(t *testing.T) { }) } } + +// A close error after a successful directory fsync changes nothing on disk: +// the rename is durable, so Put reports the record written (telling the +// caller "failed" would make two truths). +func TestPutReportsWrittenWhenOnlyTheDirectoryCloseFails(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("Windows cannot fsync a directory: the close step follows a fsync that fails there") + } + dir := t.TempDir() + s, err := NewFileAuthorityStore(dir) + if err != nil { + t.Fatal(err) + } + defer s.Close() + SetDirFaultForTest(func(step string) error { + if step == "close" { + return errors.New("injected directory close failure") + } + return nil + }) + defer SetDirFaultForTest(nil) + if err := s.Put(failStopRecord("assignment")); err != nil { + t.Fatalf("Put with only a failed directory close: %v; want written", err) + } + recs, err := s.Load() + if err != nil || len(recs) != 1 || recs[0].Epoch != 7 { + t.Fatalf("after Put: %+v %v; want the written record", recs, err) + } +} diff --git a/seaweed-block/core/authority/authority_store_file.go b/seaweed-block/core/authority/authority_store_file.go index d9c94b67c8..8c5fd96a42 100644 --- a/seaweed-block/core/authority/authority_store_file.go +++ b/seaweed-block/core/authority/authority_store_file.go @@ -27,22 +27,44 @@ func SetPutAfterRenameFaultForTest(hook func(DurableRecord) error) { putAfterRenameFault.Store(&hook) } -// dirSyncFault, when set, replaces the directory fsync after the rename in -// every FileAuthorityStore.Put. Tests only. -var dirSyncFault atomic.Pointer[func() error] +// dirFault, when set, runs at each step of the directory fsync after the +// rename in every FileAuthorityStore.Put ("open", "fsync", "close"); a +// non-nil error replaces that step's result. Tests only. +var dirFault atomic.Pointer[func(step string) error] -// ExitDurabilityUnknown is blockmaster's exit code when a record's rename -// may or may not survive a crash (sysexits EX_IOERR). Declared before the -// fail-stop exists so the red test compiles. +// ExitDurabilityUnknown is the process exit code of the fail-stop after a +// record's rename whose durability is unknown (sysexits EX_IOERR). const ExitDurabilityUnknown = 74 -// SetDirSyncFaultForTest installs (nil clears) that fault. -func SetDirSyncFaultForTest(fault func() error) { +// failStopDurabilityUnknown ends the process: the rename is done but the +// directory fsync that makes it survive a crash failed (or could not run). +// The record may or may not survive, so no caller may be told "failed" +// (it would act on a write a restart reloads) nor "written". The in-flight +// caller sees its connection drop (outcome unknown); the restart reloads +// whatever is on disk (the conventional answer, PostgreSQL after fsyncgate). +func failStopDurabilityUnknown(volumeID, step string, err error) { + fmt.Fprintf(os.Stderr, "authority_store: FAIL-STOP: directory fsync after rename of volume %s: %s: %v (outcome unknown; restart reloads the store)\n", + volumeID, step, err) + os.Exit(ExitDurabilityUnknown) +} + +// SetDirFaultForTest installs (nil clears) that fault. +func SetDirFaultForTest(fault func(step string) error) { if fault == nil { - dirSyncFault.Store(nil) + dirFault.Store(nil) return } - dirSyncFault.Store(&fault) + dirFault.Store(&fault) +} + +// dirStep returns the injected error for step, or err. +func dirStep(step string, err error) error { + if f := dirFault.Load(); f != nil { + if ferr := (*f)(step); ferr != nil { + return ferr + } + } + return err } // ============================================================ @@ -231,28 +253,48 @@ func (s *FileAuthorityStore) Put(record DurableRecord) error { } } - // Fsync the directory so the rename is durable. Every record fails - // closed: a write whose rename a crash can undo is not reported as - // written (an authority record, like a workspace lease, is believed - // by its caller). Windows cannot fsync a directory (NTFS journals the - // rename itself); the product runs on Linux. - if runtime.GOOS == "windows" && dirSyncFault.Load() == nil { - return nil + // Windows cannot fsync a directory (NTFS journals the rename itself); + // its behaviour is unchanged: best effort, except that a workspace + // record keeps its refusal. The product runs on Linux. + if runtime.GOOS == "windows" && dirFault.Load() == nil { + return windowsDirSync(s.dir, record) } + // Fsync the directory so the rename survives a crash. From here on a + // failure cannot be reported: the rename is done, so its outcome is + // unknown and the process fail-stops, for every record type. d, derr := os.Open(s.dir) - if derr != nil { - return fmt.Errorf("authority_store: directory open: %w", derr) + if derr = dirStep("open", derr); derr != nil { + if d != nil { + _ = d.Close() + } + failStopDurabilityUnknown(record.VolumeID, "directory open", derr) } - syncErr := d.Sync() - if f := dirSyncFault.Load(); f != nil { - syncErr = (*f)() + if syncErr := dirStep("fsync", d.Sync()); syncErr != nil { + _ = d.Close() + failStopDurabilityUnknown(record.VolumeID, "directory fsync", syncErr) } - closeErr := d.Close() - if syncErr != nil { - return fmt.Errorf("authority_store: directory fsync: %w", syncErr) - } - if closeErr != nil { - return fmt.Errorf("authority_store: directory close: %w", closeErr) + // A close error after a successful fsync changes nothing on disk: the + // rename is durable, so the write is reported written. + _ = dirStep("close", d.Close()) + return nil +} + +// windowsDirSync is the directory sync as it was before the fail-stop, kept +// for Windows only. +func windowsDirSync(dir string, record DurableRecord) error { + if d, derr := os.Open(dir); derr == nil { + syncErr := d.Sync() + closeErr := d.Close() + if record.Workspace != nil { + if syncErr != nil { + return fmt.Errorf("authority_store: workspace directory fsync: %w", syncErr) + } + if closeErr != nil { + return fmt.Errorf("authority_store: workspace directory close: %w", closeErr) + } + } + } else if record.Workspace != nil { + return fmt.Errorf("authority_store: workspace directory open: %w", derr) } return nil } diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index c08c2fc03f..f494f56987 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -119,7 +119,7 @@ flowchart LR | Unbound | Bound (epoch 1, endpoint version 1) | `IntentBind`; no slot of this volume holds a present line (checked per volume, also after a restart); to move to another slot use `IntentReassign` | `core/authority/authority.go` `applyWithWorkspaceMove`, `boundReplicaForVolume`; `core/authority/controller.go` `decideVolume` (binds only a volume with no line) | `INV-AUTH-ONE-PRIMARY-001`, `INV-AUTH-PERSIST-BEFORE-PUBLISH-001` | | Bound | Bound (endpoint version + 1) | `IntentRefreshEndpoint`; same epoch; a no-op when the addresses are unchanged | `core/authority/authority.go` `applyWithWorkspaceMove` | `INV-AUTH-PERSIST-BEFORE-PUBLISH-001` | | Bound | Reassigned (per-volume maximum epoch + 1) | `IntentReassign`; some earlier publication exists; an enrolled workspace volume changes only through a guarded move | `core/authority/authority.go` `applyWithWorkspaceMove`, `maxPublishedEpochForVolume` | `INV-AUTH-EPOCH-MINT-001`, `INV-AUTH-ONE-PRIMARY-001` | -| any | (store write first) | with an authority store configured, every transition is written to the store before memory changes or subscribers are notified; a failed write publishes nothing, but its durable outcome may be unknown | `core/authority/authority.go` `applyWithWorkspaceMove` | `INV-AUTH-PERSIST-BEFORE-PUBLISH-001` | +| any | (store write first) | with an authority store configured, every transition is written to the store before memory changes or subscribers are notified; a failed write publishes nothing; a write whose outcome is unknown (the directory fsync after the rename failed) fail-stops blockmaster, so no caller is told it failed | `core/authority/authority.go` `applyWithWorkspaceMove` | `INV-AUTH-PERSIST-BEFORE-PUBLISH-001` | | any (workspace) | Uncertain | a failed workspace authority write, including a lease extension; later changes for that volume, and renewals that would issue a new or extended grant, are refused until restart (a Revoking lease still gets its bounded drain reply) | `core/authority/authority.go` `applyWithWorkspaceMove`; `core/authority/workspace.go` `persistWorkspaceLocked`; `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `extendWorkspaceLease` | `INV-AUTH-UNCERTAIN-001` | | Uncertain | Uncertain (move answer) | failed move replies classify uncertainty after local locks release, before any admission refusal; request-context cancellation/deadline remain typed; known successful replay is unchanged | `core/authority/workspace.go` `WorkspaceMoveOutcomeError`; `core/host/master/workspace_service.go` `MoveWorkspace` | `INV-AUTH-UNCERTAIN-001` | | Bound | Deleting | a deletion reservation; the id is never created again | `core/host/master/services.go` `MarkVolumeDeleting` | `INV-VOL-ID-NO-REUSE-001` | @@ -712,7 +712,7 @@ Notes: |---|---|---|---|---|---|---| | `INV-AUTH-HOLDER-IDENTITY-001` | A primary holder is the pair (server id, replica id): every site that decides holdership (adopting a fact, lease first grant, renew, re-grant, HEAD claim, superseded exit) compares both; a missing server id is refused, never guessed. | AUTHORITY: PRIMARY holdership (supporting replicas are not holders) | `core/host/volume/host.go` `applyFact`, `IsSuperseded`, `recordOtherLine`; `assignment_holder.go` `assignmentNamesSelf`, `observeForeignHolder`, `refusePrimaryAssignment`; `host.go` `IsSuperseded`; `core/host/master/services.go` `SubscribeAssignments`; `workspace_service.go` `holderMatches`, `RenewWorkspaceLease`, `AckWorkspaceRevoked`; `cmd/blockvolume/chunk_remote.go` `chunkHolder`; `core/storage/chunk_restore.go` `ClaimChunkHead`; superseded exit covered by #409; `core/host/master/workspace_binding.go` `workspaceLineOwner`, `workspaceSourceHost`; `core/authority/assignment_owner.go` `captureAssignmentOwner`; `core/host/master/services.go` `assignmentFact`; `core/host/master/server_host_identity.go` `refuseServerIDFromOtherHost` (from `ReportHeartbeat`), `refuseWorkspaceHolderHost` (from `holderMatches` and, for a workspace volume, `SubscribeAssignments`), `holderSlotFact` (from `QueryVolumeStatus` and `observationVolume`/`observationReplicas`); `core/csi/master_backend.go` `primaryOwnedFrontends` (a CSI target only from a usable primary frontend); `core/authority/snapshot_builder.go` `expectOwnerForLine` (a moved line's replica facts and endpoint refreshes only from its owner, #425) | `TestAssignmentHolderIdentityRestartedOldProcess`, `TestAssignmentHolderIdentityMatchingServerStillAdopts`, `TestAssignmentHolderIdentityFencesPreviouslyHealthySameReplica`, `TestAssignmentHolderIdentityAdoptsAndWarnsCarriedEndpointMismatch`, `TestAssignmentHolderIdentityForeignStreamOrdering`, `TestAssignmentHolderIdentityForcedMoveRefusesEveryDeliveredVersion`, `TestAssignmentHolderIdentitySameEpochCannotChangeServer` (`core/host/volume/assignment_holder_test.go`); `TestWorkspaceLeaseGuardCarriesHolderServerIdentity` (`core/host/volume/workspace_holder_identity_test.go`); `TestWorkspaceLeaseRequiresHolderServerForGrantRenewAndRegrant`, `TestWorkspaceRevocationACKRequiresHolderServer` (`core/host/master/workspace_holder_identity_test.go`); `TestWorkspaceRPCCleanMovePreservesReplicaIdentity` (`core/host/master/workspace_service_test.go`); HEAD claim: `TestChunkHolderIsServerAndReplica` (`cmd/blockvolume/chunk_remote_test.go`), `TestWALStoreChunk_SameReplicaOnAnotherServerIsFenced` (`core/frontend/durable/provider_chunk_holder_test.go`); superseded exit: covered by #409 (server-id/replica-id pair, never replica alone); supporting replicas are not holders; descriptor identity not in this row; `TestWorkspaceLineOwnerIssuedAndHistorical` (`core/host/master/workspace_line_owner_test.go`), `TestWorkspaceRenewalRPCDuringHeldSameVolumeReservation` (`core/host/master/workspace_lease_horizon_test.go`); `TestAssignmentFactKeepsCapturedMoveOwnerWithoutReadableJournal` (`core/host/master/assignment_fact_owner_test.go`), `TestAssignmentOwnerReservedAndIssuedCapture` (`core/authority/assignment_owner_test.go`), `TestWorkspaceCrashAfterJournalBeforeEpochResumesSameGrant` (`core/authority/workspace_test.go`); `TestServerIDRefusedFromAHostOtherThanItsRegisteredOne`, `TestWorkspaceHolderRefusedFromAnotherHostAtRenewAckAndStream`, `TestPortalAndPrimaryComeFromTheLineServerNotTheFreshestHeartbeat`, `TestDisplayedPrimaryIsTheIssuedHolderNotThePlacementSlot`, `TestStatusListsNoFrontendWhenThePrimaryEvidenceIsMissing`, `TestCSIPublishesNoTargetWhenThePrimaryFrontendIsMissingOrRejected`, `TestDeletionReservedWorkspaceVolumeKeepsTheStreamHostCheck` (`core/host/master/server_host_identity_test.go`); `TestPublishTargetIsPrimaryOwned` (`core/csi/primary_owned_frontend_test.go`). Host scope: registered advertised-host consistency, not process uniqueness; a workspace holder's server id must be registered (no first-seen binding: host addresses change); non-workspace heartbeats from an unregistered id are not checked. Limits: trusts the network peer address (no NAT or proxy between volume and master in OSS); not authentication; `TestBuildSnapshotTakesTheMovedLinesReplicaFromItsOwner` (`core/authority/line_owner_snapshot_test.go`); `TestProcedureForcedMoveWithTheOldHostReturning` (`cmd/blockvolume/procedure_gate_integration_test.go`, tags subprocess chunkstore_integration: every forced-epoch line carries the new owner's endpoints) | `WorkspaceRegrant` `NoForeignAdoption`, `TargetNotFencedByOwnLine` (round 4 pinned simulations only; exhaustive combo10 pending) | ACTIVE | | `INV-AUTH-EPOCH-MINT-001` | Only the publisher mints epochs; a reassignment takes the per-volume maximum epoch plus one, also after a restart. | M2 Bound → Reassigned | `core/authority/authority.go` `applyWithWorkspaceMove`, `maxPublishedEpochForVolume` | `TestG8_0_Publisher_ReassignAdvancesPerVolumeEpochAcrossReplicaSlots` (`core/authority/g8_0_authority_failover_test.go`); `TestDurableAuthority_PublisherAdvancesFromReloaded` (`core/authority/authority_restart_test.go`); `TestG9F2_AssignmentRequestShapeHasNoEpochOrEndpointVersion` (`core/host/master/authority_request_bridge_test.go`) | `ControlPlane` `UniqueEpoch` | ACTIVE | -| `INV-AUTH-PERSIST-BEFORE-PUBLISH-001` | With an authority store configured, an assignment is written to the store before memory or any subscriber sees it, and a failed write does not publish it: see M2 any → (store write first). | M2 any → (store write first) | `core/authority/authority.go` `applyWithWorkspaceMove`; `core/authority/authority_store_file.go` `Put` (the directory fsync after the rename fails the write for every record) | `TestDurableAuthority_PutFailureRollsBackInMemoryState` (`core/authority/authority_restart_test.go`); `TestPutFailsWhenTheDirectoryFsyncFails` (`core/authority/authority_store_dir_fsync_test.go`) | `ControlPlane` `UniqueEpoch` | ACTIVE | +| `INV-AUTH-PERSIST-BEFORE-PUBLISH-001` | With an authority store configured, an assignment is written to the store before memory or any subscriber sees it, a failed write does not publish it, and an unknown outcome (directory fsync after the rename failed) fail-stops blockmaster, never reported as failed: see M2 any → (store write first). | M2 any → (store write first) | `core/authority/authority.go` `applyWithWorkspaceMove`; `core/authority/authority_store_file.go` `Put` (`failStopDurabilityUnknown` after a failed directory open or fsync behind the rename, every record; a close error after a good fsync is reported written; Windows keeps its previous behaviour) | `TestDurableAuthority_PutFailureRollsBackInMemoryState` (`core/authority/authority_restart_test.go`); `TestPutFailStopsWhenTheDirectoryFsyncFailsAfterRename`, `TestPutReportsWrittenWhenOnlyTheDirectoryCloseFails` (`core/authority/authority_store_dir_fsync_test.go`) | `ControlPlane` `UniqueEpoch` | ACTIVE | | `INV-AUTH-MOVE-JOURNAL-001` | A workspace move's epoch is issued only after its journal record is durable, and one move request id gets exactly one epoch, also across restarts. | M2 MoveReserved → MoveIssued | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `MoveWorkspace`, `sameWorkspaceRequest` | `TestWorkspaceMoveCannotIssueEpochWithoutJournal`, `TestWorkspaceCrashAfterJournalBeforeEpochResumesSameGrant` (`core/authority/workspace_test.go`); `TestWorkspaceReplayedIssueStartsGranteeLease` (`core/authority/workspace_unclaimed_grant_test.go`) | `ControlPlane` `Idempotent`, `JournalComplete` | ACTIVE | | `INV-AUTH-UNCERTAIN-001` | A failed authority write for a workspace volume, a lease extension included, latches uncertainty until a restart reloads the store: later authority changes and new or extended grants for that volume are refused. See M2 any (workspace) → Uncertain and Uncertain → Uncertain (move answer). | M2 any (workspace) → Uncertain; Uncertain → Uncertain (move answer) | `core/authority/authority.go` `applyWithWorkspaceMove`; `core/authority/workspace.go` `persistWorkspaceLocked`; `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `extendWorkspaceLease`; `core/authority/workspace.go` `WorkspaceMoveOutcomeError`, `MoveWorkspace`; `core/host/master/workspace_service.go` `MoveWorkspace` | `TestWorkspaceAmbiguousExtensionLatchesUncertainty` (`core/authority/workspace_lease_horizon_test.go`); `TestWorkspaceUncertaintyPrecedesRequestRefusal` (`core/authority/workspace_outcome_uncertain_test.go`), `TestWorkspaceMoveUnknownPrecedesAdmissionRefusals` (`core/host/master/workspace_uncertain_precedence_test.go`), `TestWorkspaceUncertainIssueWriteIsTyped` (`core/authority/workspace_outcome_uncertain_test.go`) | `ControlPlane` `UniqueEpoch`; `WorkspaceMoveOutcome` `NoFalseRefusal`, `CallerEndTyped`, `UncertainReplyClass` | ACTIVE | | `INV-LEASE-VIEW-001` | Whenever the publisher lock is released, each volume's lease view, the renewal path's only input, equals derive(the published authority line, workspace state, uncertainty, store presence). | M2 every workspace transition | `core/authority/workspace_lease_view.go` `deriveLeaseLocked`, `refreshLeaseViewLocked`, `publishIssuedLeaseLocked`, `setLeaseDeadlineLocked`; `core/authority/authority.go` `applyWithWorkspaceMove`, `reloadFromStore`; `core/authority/workspace.go` `persistWorkspaceLocked` | `TestWorkspaceLeaseViewMatchesDeriveAfterEveryWriter`, `TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose` (`core/authority/workspace_lease_horizon_test.go`) | — | ACTIVE | @@ -729,7 +729,7 @@ Notes: Notes: - `INV-LIFECYCLE-STORE-DURABLE-001` open gaps: Store-directory ancestor sync on Open is best-effort: failures are logged and do not block startup; a new directory entry may not survive an immediate crash when an ancestor cannot be synced. Record-file and store-directory sync after a put remain mandatory. `NodeInventoryStore.RemoveNode` does not fsync its directory after deletion, so a removed node can reappear after a crash. A failed put may still be on disk: if directory fsync fails after rename, restart can load the new record. -- `INV-AUTH-PERSIST-BEFORE-PUBLISH-001`: a failed write's durable outcome may be unknown (the record may have landed); for a workspace volume the failure latches uncertainty (`INV-AUTH-UNCERTAIN-001`). The cited test covers the non-workspace in-memory rollback. +- `INV-AUTH-PERSIST-BEFORE-PUBLISH-001`: a failure before the rename leaves the old record and is reported failed (the in-memory rollback test); a directory open or fsync failure after the rename leaves the outcome unknown and fail-stops the process, for every record type, so the restart reloads whatever survived and callers re-read. A workspace volume's uncertainty latch (`INV-AUTH-UNCERTAIN-001`) stays for its other causes. - `INV-AUTH-UNCERTAIN-001`: The cited test asserts the refusal after an unknown-outcome lease extension (rename landed, directory sync failed): the next renewal, a revocation and an endpoint change are all refused. The TLA+ configuration `S5_red_noUncertain` violates `UniqueEpoch` without it. A Revoking lease still gets its bounded drain reply, min(horizon, deadline), never extended: see M2 any (workspace) → Uncertain. A failed move on an uncertain volume is answered as an unknown outcome before any admission refusal, the request's own cancellation or deadline stays typed, and an issued move's replay still returns its stored grant: see M2 Uncertain → Uncertain (move answer). The renewal path reads uncertainty from the lease view (`INV-LEASE-VIEW-001`), not from `persistWorkspaceLocked`. - `INV-WS-LEASE-HORIZON-001`: The forced-barrier argument (a renewal that reads its clock after the barrier has read the deadline is refused) assumes nondecreasing master time. That is an assumption of the current `WorkspaceTakeover` model, whose `Tick` and `SlowTick` actions only advance `now`; it is not a consequence of `time.Now` carrying a monotonic reading, because persisted `UnixNano` deadlines are compared as wall-clock values. The existing deadline check stays alongside the horizon. The model still renews with `exp = deadline = now + TTL`; the horizon/grant split is a pending specification update (Part C rule 2). - `INV-WS-LEASE-HORIZON-001`, `INV-WS-LEASE-HORIZON-MONO-001`: a move issue that replaces the lease with the new holder's (a clean handoff, or a forced move past the barrier) is its ordered successor and ends the scope of these rows. If that issue write is persisted ambiguously (it may have landed while memory has not published it), the volume is uncertain and no further grant at the old epoch is issued (`INV-AUTH-UNCERTAIN-001`), so no disk expiry is claimed for it. From c7900bb57cf3cce26a7a54abcbcd337d6d7305f6 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 24 Nov 2026 15:45:51 -0800 Subject: [PATCH 06/19] layout: remove pool names no root reaches, inside the lease RemoveUnreachable is the cleaning's removal step for one pool shard: for the holder with its own clean(session) open, it deletes each candidate chunk that no root in HEAD (current or any snapshot) names in this volume's pool, and checks its own lease immediately before every delete. HEAD is read once after BeginClean: no commit can add a root while the cleaning is open, and a claim that voids it waits for this lease to end, which the next check sees. An unreadable root or segment stops the pass before any delete; a lapsed lease stops it before the next one; an open snapshot refuses it. The package guard now allows Delete/Remove names only in RemoveUnreachable and requires a lease check before every delete in the same block (controls: no check, check after the delete, one check before the loop). The HEAD reader enumeration classifies its read, and the ledger gains the removal row and the read path's row. Co-Authored-By: Claude Opus 5.5 --- .../frontend/chunkstore/head_readers_test.go | 22 ++ .../frontend/chunkstore/layout/guard_test.go | 123 +++++++- .../core/frontend/chunkstore/layout/remove.go | 105 +++++++ .../frontend/chunkstore/layout/remove_test.go | 269 ++++++++++++++++++ seaweed-block/docs/design/invariants.md | 8 +- 5 files changed, 516 insertions(+), 11 deletions(-) create mode 100644 seaweed-block/core/frontend/chunkstore/layout/remove.go create mode 100644 seaweed-block/core/frontend/chunkstore/layout/remove_test.go diff --git a/seaweed-block/core/frontend/chunkstore/head_readers_test.go b/seaweed-block/core/frontend/chunkstore/head_readers_test.go index 6ebce13b42..434da26d5c 100644 --- a/seaweed-block/core/frontend/chunkstore/head_readers_test.go +++ b/seaweed-block/core/frontend/chunkstore/head_readers_test.go @@ -40,6 +40,7 @@ var headReaders = map[string]string{ "core/frontend/chunkstore/share_guard.go beginShare -> ReadHead": "refuses outcome_unknown: the HEAD to share is no longer current", "core/frontend/chunkstore/usage.go Usage -> ReadHead": "GAP: reports an empty image, no error (probe Usage)", "core/frontend/chunkstore/verify.go readHead -> LookupEntry": "finding ROOT_INVALID (probe Verify)", + "core/frontend/chunkstore/layout/remove.go RemoveUnreachable -> ReadHead": "refuses ErrHeadAbsent and deletes nothing (probe LayoutRemoval)", "core/frontend/chunkstore/layout/head.go runTransition -> ReadHead": "refuses ErrHeadAbsent and writes nothing; no layout transition creates a HEAD (probe LayoutTransition)", "core/frontend/chunkstore/verify.go run -> LookupEntry": "finding ROOT_INVALID (probe Verify)", "core/frontend/chunkstore/volume_delete.go DeleteVolume -> ReadHead": "operator delete writes a deleting HEAD from nothing and completes (probe DeleteVolume)", @@ -264,6 +265,19 @@ func TestHeadReaders_AbsentHeadProbes(t *testing.T) { t.Fatalf("layout transition over an absent HEAD wrote %d times", st.updates) } }) + t.Run("LayoutRemoval", func(t *testing.T) { + r, err := layout.NewReader("/swblock/chunks", "v1", func(context.Context, string) ([]byte, bool, error) { return nil, false, nil }) + if err != nil { + t.Fatal(err) + } + pool := &countingPool{} + if _, err := layout.RemoveUnreachable(ctx, &absentLayoutHead{}, r, pool, okLease{}, layout.HolderID{Epoch: 1, Holder: "h"}, "c", 0, []layout.ChunkName{layout.NameChunk(1, []byte("x"))}); !errors.Is(err, layout.ErrHeadAbsent) { + t.Fatalf("layout removal over an absent HEAD: %v; want ErrHeadAbsent", err) + } + if pool.deletes != 0 { + t.Fatalf("layout removal over an absent HEAD deleted %d objects", pool.deletes) + } + }) t.Run("ForkReplay", func(t *testing.T) { f, b := headReaderForkFixture(t) c, err := NewCatalog(manifestFilerBlobs{f, gcBlobs{b}}, catBase) @@ -297,3 +311,11 @@ func (a *absentLayoutHead) UpdateHead(context.Context, uint64, layout.Head) erro a.updates++ return nil } + +type countingPool struct{ deletes int } + +func (p *countingPool) DeleteObject(context.Context, string) error { p.deletes++; return nil } + +type okLease struct{} + +func (okLease) StillHeld(context.Context) error { return nil } diff --git a/seaweed-block/core/frontend/chunkstore/layout/guard_test.go b/seaweed-block/core/frontend/chunkstore/layout/guard_test.go index c80a292896..626b603de6 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/guard_test.go +++ b/seaweed-block/core/frontend/chunkstore/layout/guard_test.go @@ -123,9 +123,10 @@ func owners(m map[string]bool) []string { // - Lease, claim half: OldLeaseEnded is used only in RunClaim, and // RunClaim, when it is declared, uses it. // - Every declared exported Run function goes through runTransition. -// - Pool: no name starting with Delete or Remove is used yet; the -// removal that comes with cleaning must bring its lease re-check and -// its own row here. +// - Pool: a name starting with Delete or Remove is used only in +// RemoveUnreachable, and there every delete is preceded, in the same +// loop body, by the remover's own lease check (StillHeld); see +// removerOrderFindings. // // These are syntactic checks of this package's own files: they see any // use of these names, but not a store effect reached through a name they @@ -167,13 +168,81 @@ func guardFindings(code map[string]map[string]bool, decl, tests map[string]bool) } for name, by := range code { if strings.HasPrefix(name, "Delete") || strings.HasPrefix(name, "Remove") { - bad = append(bad, strings.Join(owners(by), ", ")+" uses "+name+": a store remover needs its lease re-check and its own guard row") + for _, fn := range owners(by) { + if fn != "RemoveUnreachable" { + bad = append(bad, fn+" uses "+name+": only RemoveUnreachable removes, after its lease re-check") + } + } } } sort.Strings(bad) return bad } +// removerOrderFindings checks the removal half of the time premise in the +// sources: in RemoveUnreachable, every statement that deletes +// (DeleteObject) sits in a block where an earlier statement checks the +// remover's own lease (StillHeld). +func removerOrderFindings(t *testing.T, srcs map[string]string) []string { + t.Helper() + uses := func(n ast.Node, name string) bool { + found := false + ast.Inspect(n, func(n ast.Node) bool { + if sel, ok := n.(*ast.SelectorExpr); ok && sel.Sel.Name == name { + found = true + } + return !found + }) + return found + } + var bad []string + for fname, src := range srcs { + file, err := parser.ParseFile(token.NewFileSet(), fname, src, 0) + if err != nil { + t.Fatal(err) + } + for _, d := range file.Decls { + fn, ok := d.(*ast.FuncDecl) + if !ok || fn.Body == nil || fn.Name.Name != "RemoveUnreachable" { + continue + } + deletes := 0 + ast.Inspect(fn.Body, func(n ast.Node) bool { + blk, ok := n.(*ast.BlockStmt) + if !ok { + return true + } + for i, st := range blk.List { + if _, isBlock := st.(*ast.BlockStmt); isBlock || !uses(st, "DeleteObject") { + continue + } + if _, nested := st.(*ast.RangeStmt); nested { + continue // its body is checked as its own block + } + if _, nested := st.(*ast.ForStmt); nested { + continue + } + deletes++ + checked := false + for _, prev := range blk.List[:i] { + if uses(prev, "StillHeld") { + checked = true + } + } + if !checked { + bad = append(bad, "RemoveUnreachable deletes without a lease check before it in the same block") + } + } + return true + }) + if deletes == 0 { + bad = append(bad, "RemoveUnreachable is declared and has no delete: the scan is broken") + } + } + } + return bad +} + // declared returns the names of the functions the sources declare. func declared(t *testing.T, srcs map[string]string) map[string]bool { t.Helper() @@ -196,7 +265,7 @@ func TestGuard_WritersTransitionsAndRemovers(t *testing.T) { src := packageSources(t, false) code := refs(t, src) tests := declared(t, packageSources(t, true)) - if bad := guardFindings(code, declared(t, src), tests); len(bad) != 0 { + if bad := append(guardFindings(code, declared(t, src), tests), removerOrderFindings(t, src)...); len(bad) != 0 { t.Fatalf("guard: %s", strings.Join(bad, "\n")) } st := reflect.TypeOf((*HeadStore)(nil)).Elem() @@ -229,14 +298,50 @@ func TestGuard_Controls(t *testing.T) { "runTransition alias": {src: `func w(ctx context.Context, st HeadStore) { f := runTransition; _, _ = f(ctx, st, nil) }`, want: "uses runTransition; transitions are exported"}, "untested transition": {src: `func RunZz(ctx context.Context, st HeadStore) (Head, error) { return runTransition(ctx, st, nil) }`, want: "has no TestZz_Closure"}, "lease wait outside claim": {src: `func w(ctx context.Context, l LeaseWait) error { return l.OldLeaseEnded(ctx, 1) }`, want: "only RunClaim claims"}, - "remover": {src: `type p interface{ DeleteObject(context.Context, string) error } -func w(ctx context.Context, x p) error { return x.DeleteObject(ctx, "o") }`, want: "a store remover"}, + "remover outside RemoveUnreachable": {src: `type p interface{ DeleteObject(context.Context, string) error } +func w(ctx context.Context, x p) error { return x.DeleteObject(ctx, "o") }`, want: "only RemoveUnreachable removes"}, + "removal without lease check": {file: "remove.go", src: `type p interface{ DeleteObject(context.Context, string) error } +type l interface{ StillHeld(context.Context) error } +func RemoveUnreachable(ctx context.Context, x p, h l, names []string) error { + for _, n := range names { + if err := x.DeleteObject(ctx, n); err != nil { + return err + } + } + return nil +}`, want: "deletes without a lease check"}, + "lease check after the delete": {file: "remove.go", src: `type p interface{ DeleteObject(context.Context, string) error } +type l interface{ StillHeld(context.Context) error } +func RemoveUnreachable(ctx context.Context, x p, h l, names []string) error { + for _, n := range names { + if err := x.DeleteObject(ctx, n); err != nil { + return err + } + if err := h.StillHeld(ctx); err != nil { + return err + } + } + return nil +}`, want: "deletes without a lease check"}, + "lease check once before the loop": {file: "remove.go", src: `type p interface{ DeleteObject(context.Context, string) error } +type l interface{ StillHeld(context.Context) error } +func RemoveUnreachable(ctx context.Context, x p, h l, names []string) error { + if err := h.StillHeld(ctx); err != nil { + return err + } + for _, n := range names { + if err := x.DeleteObject(ctx, n); err != nil { + return err + } + } + return nil +}`, want: "deletes without a lease check"}, "claim without lease wait": {src: `func RunClaim(ctx context.Context, st HeadStore, lease LeaseWait, me HolderID) (Head, error) { return runTransition(ctx, st, func(h Head) (Head, bool, error) { return h, false, nil }) }`, want: "does not wait for the old lease", file: "claim.go"}, "transition not through runTransition": {src: `func RunZz(ctx context.Context, st HeadStore) (Head, error) { h, _, err := st.ReadHead(ctx); return h, err }`, want: "does not go through runTransition"}, "remover method value": {src: `type p interface{ RemoveName(string) } -func w(x p) { f := x.RemoveName; f("o") }`, want: "a store remover"}, +func w(x p) { f := x.RemoveName; f("o") }`, want: "only RemoveUnreachable removes"}, } { srcs := packageSources(t, false) file := c.file @@ -244,7 +349,7 @@ func w(x p) { f := x.RemoveName; f("o") }`, want: "a store remover"}, file = "zz_control.go" } srcs[file] = "package layout\n\nimport \"context\"\n\nvar _ context.Context\n\n" + c.src + "\n" - bad := guardFindings(refs(t, srcs), declared(t, srcs), tests) + bad := append(guardFindings(refs(t, srcs), declared(t, srcs), tests), removerOrderFindings(t, srcs)...) if !strings.Contains(strings.Join(bad, "\n"), c.want) { t.Errorf("control %q: findings %q; want one containing %q", name, bad, c.want) } diff --git a/seaweed-block/core/frontend/chunkstore/layout/remove.go b/seaweed-block/core/frontend/chunkstore/layout/remove.go new file mode 100644 index 0000000000..b3ce03db59 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/layout/remove.go @@ -0,0 +1,105 @@ +package layout + +import ( + "context" + "errors" + "fmt" + "sort" +) + +// ErrLeaseLost: the remover's own lease is no longer valid; nothing more +// is removed. +var ErrLeaseLost = errors.New("layout: remover's lease is not valid") + +// LeaseHeld is the remover's half of the time premise: it returns nil only +// while the caller's own lease is valid. Remove calls it immediately before +// every delete. +type LeaseHeld interface { + StillHeld(ctx context.Context) error +} + +// Pool deletes one object of the volume by its path relative to the volume +// root; deleting an absent object succeeds. +type Pool interface { + DeleteObject(ctx context.Context, rel string) error +} + +// RemoveUnreachable is transition 7 for one pool shard: for the holder +// with clean(session) open at HEAD's epoch, every candidate chunk of shard +// that no root in HEAD (current and every snapshot) names in this +// volume's pool is deleted, each delete preceded by a check of the +// remover's own lease. HEAD is read once, after BeginClean: while clean is +// open no commit can add a root, and a claim that voids the cleaning waits +// for this lease to end, which the check before every delete sees. It +// returns the names it deleted, in index order. +func RemoveUnreachable(ctx context.Context, st HeadStore, r *Reader, pool Pool, lease LeaseHeld, me HolderID, session string, shard uint64, candidates []ChunkName) ([]ChunkName, error) { + if lease == nil || pool == nil || r == nil { + return nil, errors.New("layout: removal needs a reader, a pool and a lease check") + } + h, found, err := st.ReadHead(ctx) + if err != nil { + return nil, err + } + if !found { + return nil, ErrHeadAbsent + } + if !h.heldBy(me) { + return nil, fmt.Errorf("%w: HEAD epoch %d holder %q", ErrNotHolder, h.Epoch, h.Holder) + } + if h.Activity != (Activity{Kind: ActClean, Session: session}) { + return nil, fmt.Errorf("%w: HEAD has %s(%s), not clean(%s)", ErrNoSession, h.Activity.Kind, h.Activity.Session, session) + } + live, err := reachable(ctx, r, h, shard) + if err != nil { + return nil, err + } + sorted := append([]ChunkName(nil), candidates...) + sort.Slice(sorted, func(a, b int) bool { return sorted[a].Index < sorted[b].Index }) + var removed []ChunkName + for _, c := range sorted { + if Shard(c.Index) != shard || live[c] { + continue + } + if err := lease.StillHeld(ctx); err != nil { + return removed, fmt.Errorf("%w: %v", ErrLeaseLost, err) + } + if err := pool.DeleteObject(ctx, c.Path()); err != nil { + return removed, fmt.Errorf("layout: delete %s: %w", c, err) + } + removed = append(removed, c) + } + return removed, nil +} + +// reachable returns this volume's chunk names in shard that any root in h +// names. A root or segment that cannot be read is an error: nothing is +// removed on a partial view. +func reachable(ctx context.Context, r *Reader, h Head, shard uint64) (map[ChunkName]bool, error) { + roots := map[RootName]bool{} + if h.Current != nil { + roots[*h.Current] = true + } + for _, s := range h.Snapshots { + roots[s.Root] = true + } + live := map[ChunkName]bool{} + for rn := range roots { + img, err := r.Open(ctx, rn) + if err != nil { + return nil, err + } + seg, ok, err := img.Segment(ctx, shard) + if err != nil { + return nil, err + } + if !ok { + continue + } + for _, ref := range seg.Chunks { + if ref.Owner == r.vol { + live[ref.Chunk] = true + } + } + } + return live, nil +} diff --git a/seaweed-block/core/frontend/chunkstore/layout/remove_test.go b/seaweed-block/core/frontend/chunkstore/layout/remove_test.go new file mode 100644 index 0000000000..31a901b9d3 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/layout/remove_test.go @@ -0,0 +1,269 @@ +package layout + +import ( + "context" + "errors" + "fmt" + "path" + "testing" +) + +const removeBase = "/swblock/chunks" // volRoot = removeBase/v1 + +// objPool is a volume's objects for removal tests: Fetch reads them, Pool +// deletes them, with an optional kill point counted over deletes. +type objPool struct { + objs map[string][]byte + deletes []string + killAt int + after bool + dead bool +} + +func (o *objPool) fetch(_ context.Context, p string) ([]byte, bool, error) { + if o.dead { + return nil, false, errKilled + } + b, ok := o.objs[p] + return b, ok, nil +} + +func (o *objPool) DeleteObject(_ context.Context, rel string) error { + if o.dead { + return errKilled + } + o.deletes = append(o.deletes, rel) + kill := len(o.deletes) == o.killAt + if kill && !o.after { + o.dead = true + return errKilled + } + delete(o.objs, path.Join(volRoot, rel)) + if kill { + o.dead = true + return errKilled + } + return nil +} + +type fakeHeld struct { + calls int + lostAt int // the n-th call (1-based) and later fail; 0 = never +} + +func (l *fakeHeld) StillHeld(context.Context) error { + l.calls++ + if l.lostAt > 0 && l.calls >= l.lostAt { + return errors.New("lease lapsed") + } + return nil +} + +// removeFixture: HEAD clean(c1) at epoch 3; the current root names chunks +// 0 and 3, the snapshot "daily" an older image naming chunks 0 and 2 (all +// in shard 0); chunks 5 and 7 are in the pool but no root names them, and +// chunk 10001 (shard 1) is unreferenced too. +func removeFixture(t *testing.T) (*objPool, *Head, []ChunkName, []ChunkName) { + t.Helper() + objs := map[string][]byte{} + cur := manifest(ref("v1", 0, "a"), ref("v1", 3, "b")) + old := manifest(ref("v1", 0, "a"), ref("v1", 2, "c")) + curRoot := writeImage(t, objs, cur, map[uint64][]byte{0: []byte("a"), 3: []byte("b")}) + oldRoot := writeImage(t, objs, old, map[uint64][]byte{0: []byte("a"), 2: []byte("c")}) + var orphans []ChunkName + for i, d := range map[uint64]string{5: "e", 7: "f", 10001: "g"} { + c := NameChunk(i, []byte(d)) + objs[path.Join(volRoot, c.Path())] = []byte(d) + orphans = append(orphans, c) + } + h := &Head{Gen: 7, Epoch: 3, Holder: "srv-a", Activity: Activity{Kind: ActClean, Session: "c1"}, Current: &curRoot, + Snapshots: map[string]Snapshot{"daily": {Root: oldRoot}}} + live := []ChunkName{cur[0].Chunk, cur[3].Chunk, old[2].Chunk} + return &objPool{objs: objs}, h, live, orphans +} + +func removeShard0(t *testing.T, st HeadStore, o *objPool, l LeaseHeld, session string, cands []ChunkName) ([]ChunkName, error) { + t.Helper() + r, err := NewReader(removeBase, "v1", o.fetch) + if err != nil { + t.Fatal(err) + } + return RemoveUnreachable(context.Background(), st, r, o, l, me, session, 0, cands) +} + +func inPool(o *objPool, c ChunkName) bool { _, ok := o.objs[path.Join(volRoot, c.Path())]; return ok } + +// Only names no root in HEAD reaches are removed: the current root's and +// a snapshot's chunks stay, shard 0's orphans go, the shard-1 orphan is +// not touched by a shard-0 pass; the lease is checked before every delete. +func TestRemoveUnreachable_RemovesOnlyWhatNoRootNames(t *testing.T) { + o, h, live, orphans := removeFixture(t) + l := &fakeHeld{} + cands := append(append([]ChunkName(nil), live...), orphans...) + removed, err := removeShard0(t, &memHead{h: h}, o, l, "c1", cands) + if err != nil { + t.Fatal(err) + } + if len(removed) != 2 || removed[0].Index != 5 || removed[1].Index != 7 { + t.Fatalf("removed %v; want chunks 5 and 7", removed) + } + for _, c := range live { + if !inPool(o, c) { + t.Fatalf("reachable chunk %s was removed", c) + } + } + if l.calls != len(o.deletes) { + t.Fatalf("lease checks %d for %d deletes; want one before each", l.calls, len(o.deletes)) + } + if err := reachableMissing(h, o.objs); err != nil { + t.Fatalf("after removal HEAD reaches a missing object: %v", err) + } + for _, c := range orphans { + if c.Index == 10001 && !inPool(o, c) { + t.Fatal("a shard-1 name was removed by a shard-0 pass") + } + } +} + +// No name is removed while a snapshot is open (or without a cleaning, or +// by another holder, or over an absent HEAD). +func TestRemoveUnreachable_RefusedOutsideItsCleaning(t *testing.T) { + for name, tc := range map[string]struct { + edit func(*Head) + want error + }{ + "snapshot open": {func(h *Head) { h.Activity = Activity{Kind: ActSnap, Session: "s1"} }, ErrNoSession}, + "idle": {func(h *Head) { h.Activity = Activity{Kind: ActIdle} }, ErrNoSession}, + "other cleaning": {func(h *Head) { h.Activity = Activity{Kind: ActClean, Session: "c2"} }, ErrNoSession}, + "newer epoch": {func(h *Head) { h.Epoch = 4; h.Holder = "srv-b" }, ErrNotHolder}, + } { + o, h, _, orphans := removeFixture(t) + tc.edit(h) + if _, err := removeShard0(t, &memHead{h: h}, o, &fakeHeld{}, "c1", orphans); !errors.Is(err, tc.want) || len(o.deletes) != 0 { + t.Errorf("%s: %v, %d deletes; want %v and none", name, err, len(o.deletes), tc.want) + } + } + o, _, _, orphans := removeFixture(t) + if _, err := removeShard0(t, &memHead{}, o, &fakeHeld{}, "c1", orphans); !errors.Is(err, ErrHeadAbsent) || len(o.deletes) != 0 { + t.Errorf("absent HEAD: %v, %d deletes", err, len(o.deletes)) + } +} + +// A lease that lapses mid-pass stops the removal before the next delete. +func TestRemoveUnreachable_StopsWhenTheLeaseLapses(t *testing.T) { + o, h, _, orphans := removeFixture(t) + removed, err := removeShard0(t, &memHead{h: h}, o, &fakeHeld{lostAt: 2}, "c1", orphans) + if !errors.Is(err, ErrLeaseLost) || len(removed) != 1 || len(o.deletes) != 1 { + t.Fatalf("lease lapsing before the second delete: removed %v, %v; want one delete then ErrLeaseLost", removed, err) + } +} + +// A root or segment HEAD names that cannot be read stops the pass before +// any delete: nothing is removed on a partial view. +func TestRemoveUnreachable_NothingRemovedOnAPartialView(t *testing.T) { + o, h, _, orphans := removeFixture(t) + delete(o.objs, path.Join(volRoot, h.Snapshots["daily"].Root.Path())) + if _, err := removeShard0(t, &memHead{h: h}, o, &fakeHeld{}, "c1", orphans); !errors.Is(err, ErrMissing) || len(o.deletes) != 0 { + t.Fatalf("unreadable snapshot root: %v, %d deletes; want ErrMissing and none", err, len(o.deletes)) + } +} + +// cleaningPass is the whole cleaning operation as the holder runs it after +// a (re)start: a cleaning of its own left open is ended first, then +// BeginClean, the removal of shard 0, EndClean. +func cleaningPass(st *memVolume, o *objPool, session string, cands []ChunkName) error { + ctx := context.Background() + h, found, err := st.ReadHead(ctx) + if err != nil { + return err + } + if !found { + return ErrHeadAbsent + } + if h.Activity.Kind == ActClean && h.heldBy(me) { + if _, err := RunEndClean(ctx, st, me, h.Activity.Session); err != nil { + return err + } + } + if _, err := RunBeginClean(ctx, st, me, session); err != nil { + return err + } + r, err := NewReader(removeBase, "v1", o.fetch) + if err != nil { + return err + } + if _, err := RemoveUnreachable(ctx, st, r, o, &fakeHeld{}, me, session, 0, cands); err != nil { + return err + } + _, err = RunEndClean(ctx, st, me, session) + return err +} + +// Interrupt at every step of the cleaning operation: killed at each of its +// writes (BeginClean, every delete, EndClean), before the write applies +// and after it applied with its reply lost; at no point does HEAD reach a +// missing object, and the restarted holder ends idle with every orphan of +// shard 0 removed and every reachable object present. +func TestCleaningPass_InterruptAtEveryStep(t *testing.T) { + fresh := func() (*memVolume, *objPool, []ChunkName, []ChunkName) { + o, h, live, orphans := removeFixture(t) + h.Activity = Activity{Kind: ActIdle} + return &memVolume{head: &memHead{h: h}, objects: o.objs}, o, live, orphans + } + v, o, live, orphans := fresh() + cands := append(append([]ChunkName(nil), live...), orphans...) + if err := cleaningPass(v, o, "c1", cands); err != nil { + t.Fatal(err) + } + steps := len(v.writes) + len(o.deletes) + if steps != 4 { + t.Fatalf("the cleaning made %d writes; want 4 (BeginClean, two deletes, EndClean)", steps) + } + // Kill points: HEAD writes are counted by memVolume, deletes by objPool; + // step k is the k-th write of either kind in run order. + order := []string{"head", "delete", "delete", "head"} + for k := range order { + for _, after := range []bool{false, true} { + t.Run(fmt.Sprintf("step%d %s/after=%t", k+1, order[k], after), func(t *testing.T) { + v, o, live, orphans := fresh() + nth := 0 + for _, kind := range order[:k+1] { + if kind == order[k] { + nth++ + } + } + if order[k] == "head" { + v.killAt, v.after = nth, after + } else { + o.killAt, o.after = nth, after + } + if err := cleaningPass(v, o, "c1", cands); !errors.Is(err, errKilled) { + t.Fatalf("killed run: %v", err) + } + if err := reachableMissing(v.head.h, o.objs); err != nil { + t.Fatalf("after the kill HEAD reaches a missing object: %v", err) + } + v.dead, v.killAt, o.dead, o.killAt = false, 0, false, 0 + if err := cleaningPass(v, o, "c2", cands); err != nil { + t.Fatalf("re-run: %v", err) + } + if v.head.h.Activity.Kind != ActIdle { + t.Fatalf("activity after the re-run: %+v", v.head.h.Activity) + } + for _, c := range orphans { + if c.Index != 10001 && inPool(o, c) { + t.Fatalf("orphan %s still present", c) + } + } + for _, c := range live { + if !inPool(o, c) { + t.Fatalf("reachable %s removed", c) + } + } + if err := reachableMissing(v.head.h, o.objs); err != nil { + t.Fatal(err) + } + }) + } + } +} diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 51797cc33e..6e900f4cf6 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -530,6 +530,7 @@ stateDiagram-v2 clean --> idle: Claim(e), c void idle --> clean: BeginClean(c) clean --> idle: EndClean(c) + clean --> clean: RemoveUnreachable(shard) ``` | From | To | Guard | Enforced in | Protects | @@ -540,10 +541,11 @@ stateDiagram-v2 | any | idle at epoch e | e above HEAD's epoch (the same epoch and server is a replay); every older holder's lease has ended, checked after the read and before the update | claim.go `Head.Claim`, `RunClaim` (`LeaseWait.OldLeaseEnded`) | `INV-SNAPK-CLAIM-LEASE-001` | | idle | clean(c) | holder at HEAD's epoch; 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; 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 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; the remover's own lease is checked before every delete | remove.go `RemoveUnreachable` (`LeaseHeld.StillHeld`) | `INV-SNAPK-REMOVE-LEASE-001` | ## Part B. Invariant ledger -337 rows: 266 ACTIVE, 67 STUB, 4 ARCHIVED; 15 kept from the internal ledger, 322 new. +339 rows: 268 ACTIVE, 67 STUB, 4 ARCHIVED; 15 kept from the internal ledger, 324 new. The "Machine / transition" column refers to Part A. Notes under a table record what a row does not cover and, for kept rows, what was narrowed from the internal ledger. @@ -1083,7 +1085,7 @@ Notes: | ID | Statement | Machine / transition | Enforced in | Test | TLA+ property | Status | |---|---|---|---|---|---|---| | `INV-SNAPK-NAME-CANONICAL-001` | A chunk is named by its index and the SHA-256 of its bytes under `pool//`; a segment and a root are named by the SHA-256 of their canonical encoding, and decoding refuses any bytes the encoder would not write, so an object has one encoding and one name. | Content-named layout (no state transition) | `core/frontend/chunkstore/layout` `layout.go` `ParseChunkName`, `DecodeSegment`, `DecodeRoot` | `TestParseChunkName_RoundTripAndRefusals`, `TestDecodeSegment_RefusesNonCanonical`, `TestRoot_Refusals`, `TestBuild_ShardsAndIncrementalReuse` | — (the snapshot kernel model is not in this repository) | ACTIVE | -| `INV-SNAPK-HEAD-WRITE-001` | HEAD changes only by one conditional update on its generation through `runTransition`; no path in the package creates a HEAD, and an absent HEAD is refused. A source scan refuses any other use of `UpdateHead`, a transition without its closure and interrupt tests, and any store remover. | M9 every transition | `core/frontend/chunkstore/layout` `head.go` `runTransition`; `HeadStore` (read and conditional update only) | `TestGuard_WritersTransitionsAndRemovers`, `TestGuard_Controls`, `TestRunBegin` | — (the snapshot kernel model is not in this repository) | ACTIVE | +| `INV-SNAPK-HEAD-WRITE-001` | HEAD changes only by one conditional update on its generation through `runTransition`; no path in the package creates a HEAD, and an absent HEAD is refused. A source scan refuses any other use of `UpdateHead`, a transition without its closure and interrupt tests, and any store remover other than the lease-checked RemoveUnreachable. | M9 every transition | `core/frontend/chunkstore/layout` `head.go` `runTransition`; `HeadStore` (read and conditional update only) | `TestGuard_WritersTransitionsAndRemovers`, `TestGuard_Controls`, `TestRunBegin` | — (the snapshot kernel model is not in this repository) | ACTIVE | | `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` | `TestAbort_Closure`, `TestAbort_IdleMeansNoActivityRemains`, `TestAbort_RollBackAfterOwnCrash`, `TestRunAbort_InterruptAtEveryStep` | — (the snapshot kernel model is not in this repository) | ACTIVE | @@ -1091,6 +1093,8 @@ Notes: | `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 | | `INV-SNAPK-CLAIM-LEASE-001` | A claim takes HEAD only at a newer epoch and only after every older holder's lease has ended (checked after the read, before the update); it voids any open session or cleaning, so the old holder's commit, abort and begin are refused. | M9 any → idle (Claim) | `core/frontend/chunkstore/layout` `claim.go` `RunClaim`, `Head.Claim` | `TestClaim_Closure`, `TestRunClaim_WaitsForTheOldLease`, `TestRunClaim_VoidsTheOldSession`, `TestRunClaim_InterruptAtEveryStep` | — (the snapshot kernel model is not in this repository) | ACTIVE | | `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-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-SNAPK-REMOVE-LEASE-001` | A pool name is removed only inside the holder's own cleaning, only when no root in HEAD names it, and only after the remover's own lease is checked immediately before that delete; a lapsed lease stops the pass, an unreadable root or segment stops it before any delete, and a snapshot open on the volume refuses it. A source scan requires the lease check before every delete in the same block and refuses any other remover. | M9 clean → clean (RemoveUnreachable) | `core/frontend/chunkstore/layout` `remove.go` `RemoveUnreachable` | `TestRemoveUnreachable_RemovesOnlyWhatNoRootNames`, `TestRemoveUnreachable_RefusedOutsideItsCleaning`, `TestRemoveUnreachable_StopsWhenTheLeaseLapses`, `TestRemoveUnreachable_NothingRemovedOnAPartialView`, `TestCleaningPass_InterruptAtEveryStep`, `TestGuard_Controls` | — (the snapshot kernel model is not in this repository) | ACTIVE | | `INV-SNAPK-STALE-HOLDER-001` | Every transition refuses an older epoch of the same server and the same epoch held by another server, in idle, snap and clean; a new transition must be added to the table. | M9 every transition | `core/frontend/chunkstore/layout` `Head.heldBy` and each transition | `TestTransitions_RefuseAStaleHolder` | — (the snapshot kernel model is not in this repository) | ACTIVE | Notes: From 2aebd987ef6131dd932d965d13fedbb3dc257a70 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 24 Nov 2026 15:51:22 -0800 Subject: [PATCH 07/19] test: reload after the fail-stop must return exactly the written record The reload used Load, which hides skipped corrupt records, and accepted no record. The child stops after the rename without a power loss, so the record is on disk: reloadExactly requires LoadWithSkips to return it (deep-equal) with no skip, and its own controls refuse a corrupt, a missing and a different record. The latch note and comments no longer name a directory sync failure as a latch cause (that case fail-stops). Co-Authored-By: Claude Opus 5.5 --- seaweed-block/core/authority/authority.go | 5 +- .../authority_store_dir_fsync_test.go | 81 ++++++++++++++++--- .../authority/workspace_lease_horizon_test.go | 2 +- seaweed-block/docs/design/invariants.md | 2 +- 4 files changed, 75 insertions(+), 15 deletions(-) diff --git a/seaweed-block/core/authority/authority.go b/seaweed-block/core/authority/authority.go index cb28f1b74d..fce81f1169 100644 --- a/seaweed-block/core/authority/authority.go +++ b/seaweed-block/core/authority/authority.go @@ -618,8 +618,9 @@ func (p *Publisher) applyWithWorkspaceMove(ask AssignmentAsk, grant *workspaceGr p.mu.Unlock() if issuedWorkspace != nil { // The store may have written the issuing record before - // failing (e.g. a directory sync after the rename): the - // move's outcome is unknown, not refused. + // failing (a failure after its rename): the move's outcome + // is unknown, not refused. The file store fail-stops on a + // directory fsync failure there instead (exit 74). return fmt.Errorf("authority: durable Put of a workspace move issue failed: %w: %w", err, ErrWorkspaceOutcomeUncertain) } return fmt.Errorf("authority: durable Put failed, rolling back mint: %w", err) diff --git a/seaweed-block/core/authority/authority_store_dir_fsync_test.go b/seaweed-block/core/authority/authority_store_dir_fsync_test.go index f34cd50981..80e3276f10 100644 --- a/seaweed-block/core/authority/authority_store_dir_fsync_test.go +++ b/seaweed-block/core/authority/authority_store_dir_fsync_test.go @@ -5,6 +5,8 @@ import ( "fmt" "os" "os/exec" + "path/filepath" + "reflect" "runtime" "strings" "testing" @@ -72,23 +74,80 @@ func TestPutFailStopsWhenTheDirectoryFsyncFailsAfterRename(t *testing.T) { !strings.Contains(string(out), "directory "+step+": injected directory "+step+" failure") { t.Fatalf("missing the typed fail-stop line:\n%s", out) } - // The restart reloads whatever survived: the new record or none, never an error. - s, err := NewFileAuthorityStore(dir) - if err != nil { - t.Fatal(err) - } - defer s.Close() - recs, err := s.Load() - if err != nil { + // The restart reloads whatever survived. The child stopped after the + // rename without a power loss, so the record is on disk: the reload + // must return exactly it, with no skipped (corrupt) record. + if err := reloadExactly(dir, failStopRecord(kind)); err != nil { t.Fatalf("reload after the fail-stop: %v", err) } - if len(recs) > 1 || (len(recs) == 1 && (recs[0].VolumeID != "v1" || recs[0].Epoch != 7)) { - t.Fatalf("reload after the fail-stop: %+v, want the written record or none", recs) - } }) } } +// reloadExactly reopens the store at dir and returns nil only if it loads +// exactly want and skips nothing. +func reloadExactly(dir string, want DurableRecord) error { + s, err := NewFileAuthorityStore(dir) + if err != nil { + return err + } + defer s.Close() + recs, skips, err := s.LoadWithSkips() + switch { + case err != nil: + return err + case len(skips) != 0: + return fmt.Errorf("%d skipped record(s): %v", len(skips), skips) + case len(recs) != 1: + return fmt.Errorf("%d records, want exactly the written one", len(recs)) + case !reflect.DeepEqual(recs[0], want): + return fmt.Errorf("reloaded %+v, want %+v", recs[0], want) + } + return nil +} + +// The reload check refuses each way the restart could mislead it: a corrupt +// record (skipped by Load), no record, a different record. +func TestReloadExactlyRefusesCorruptMissingOrDifferent(t *testing.T) { + want := failStopRecord("assignment") + put := func(t *testing.T, r DurableRecord) string { + dir := t.TempDir() + s, err := NewFileAuthorityStore(dir) + if err != nil { + t.Fatal(err) + } + if err := s.Put(r); err != nil { + t.Fatal(err) + } + s.Close() + return dir + } + if err := reloadExactly(put(t, want), want); err != nil { + t.Fatalf("control: the written record must reload: %v", err) + } + if reloadExactly(t.TempDir(), want) == nil { + t.Fatal("an empty store passed") + } + other := want + other.Epoch = 8 + if reloadExactly(put(t, other), want) == nil { + t.Fatal("a different record passed") + } + dir := put(t, want) + ents, err := os.ReadDir(dir) + if err != nil || len(ents) == 0 { + t.Fatalf("store dir: %v %d", err, len(ents)) + } + for _, e := range ents { + if err := os.WriteFile(filepath.Join(dir, e.Name()), []byte("corrupt"), 0o644); err != nil { + t.Fatal(err) + } + } + if reloadExactly(dir, want) == nil { + t.Fatal("a corrupt record passed") + } +} + // A close error after a successful directory fsync changes nothing on disk: // the rename is durable, so Put reports the record written (telling the // caller "failed" would make two truths). diff --git a/seaweed-block/core/authority/workspace_lease_horizon_test.go b/seaweed-block/core/authority/workspace_lease_horizon_test.go index ce19c81325..9cbf2570bf 100644 --- a/seaweed-block/core/authority/workspace_lease_horizon_test.go +++ b/seaweed-block/core/authority/workspace_lease_horizon_test.go @@ -351,7 +351,7 @@ func TestWorkspaceAmbiguousExtensionLatchesUncertainty(t *testing.T) { first := p.WorkspaceState("v").Lease.ExpiresAtNS hs.setAfter(func(r DurableRecord) error { if isExtension(r, "v", first) { - return errors.New("injected: directory sync failed after rename") + return errors.New("injected: failure after the rename") } return nil }) diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index f494f56987..ee5b217e86 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -730,7 +730,7 @@ Notes: - `INV-LIFECYCLE-STORE-DURABLE-001` open gaps: Store-directory ancestor sync on Open is best-effort: failures are logged and do not block startup; a new directory entry may not survive an immediate crash when an ancestor cannot be synced. Record-file and store-directory sync after a put remain mandatory. `NodeInventoryStore.RemoveNode` does not fsync its directory after deletion, so a removed node can reappear after a crash. A failed put may still be on disk: if directory fsync fails after rename, restart can load the new record. - `INV-AUTH-PERSIST-BEFORE-PUBLISH-001`: a failure before the rename leaves the old record and is reported failed (the in-memory rollback test); a directory open or fsync failure after the rename leaves the outcome unknown and fail-stops the process, for every record type, so the restart reloads whatever survived and callers re-read. A workspace volume's uncertainty latch (`INV-AUTH-UNCERTAIN-001`) stays for its other causes. -- `INV-AUTH-UNCERTAIN-001`: The cited test asserts the refusal after an unknown-outcome lease extension (rename landed, directory sync failed): the next renewal, a revocation and an endpoint change are all refused. The TLA+ configuration `S5_red_noUncertain` violates `UniqueEpoch` without it. A Revoking lease still gets its bounded drain reply, min(horizon, deadline), never extended: see M2 any (workspace) → Uncertain. A failed move on an uncertain volume is answered as an unknown outcome before any admission refusal, the request's own cancellation or deadline stays typed, and an issued move's replay still returns its stored grant: see M2 Uncertain → Uncertain (move answer). The renewal path reads uncertainty from the lease view (`INV-LEASE-VIEW-001`), not from `persistWorkspaceLocked`. +- `INV-AUTH-UNCERTAIN-001`: The cited test asserts the refusal after an unknown-outcome lease extension (rename landed, then a failure; the file store fail-stops on a directory fsync failure instead, `INV-AUTH-PERSIST-BEFORE-PUBLISH-001`): the next renewal, a revocation and an endpoint change are all refused. The TLA+ configuration `S5_red_noUncertain` violates `UniqueEpoch` without it. A Revoking lease still gets its bounded drain reply, min(horizon, deadline), never extended: see M2 any (workspace) → Uncertain. A failed move on an uncertain volume is answered as an unknown outcome before any admission refusal, the request's own cancellation or deadline stays typed, and an issued move's replay still returns its stored grant: see M2 Uncertain → Uncertain (move answer). The renewal path reads uncertainty from the lease view (`INV-LEASE-VIEW-001`), not from `persistWorkspaceLocked`. - `INV-WS-LEASE-HORIZON-001`: The forced-barrier argument (a renewal that reads its clock after the barrier has read the deadline is refused) assumes nondecreasing master time. That is an assumption of the current `WorkspaceTakeover` model, whose `Tick` and `SlowTick` actions only advance `now`; it is not a consequence of `time.Now` carrying a monotonic reading, because persisted `UnixNano` deadlines are compared as wall-clock values. The existing deadline check stays alongside the horizon. The model still renews with `exp = deadline = now + TTL`; the horizon/grant split is a pending specification update (Part C rule 2). - `INV-WS-LEASE-HORIZON-001`, `INV-WS-LEASE-HORIZON-MONO-001`: a move issue that replaces the lease with the new holder's (a clean handoff, or a forced move past the barrier) is its ordered successor and ends the scope of these rows. If that issue write is persisted ambiguously (it may have landed while memory has not published it), the volume is uncertain and no further grant at the old epoch is issued (`INV-AUTH-UNCERTAIN-001`), so no disk expiry is claimed for it. - `INV-LEASE-VIEW-001`, `INV-LEASE-VIEW-OWNED-001`: writers refresh the view under the publisher lock, then the lease lock, at every change of a derive input; the live renewal path takes only the lease lock (`INV-WS-RENEW-NONBLOCKING-001`). A move issue publishes the derived view and the new holder's initial deadline in one lease-lock section, never lowering a deadline a renewal raised: see M2 Moved → epoch issued (test `TestWorkspaceIssuePublishNeverLowersARenewedDeadline`, `core/authority/workspace_issue_publish_test.go`). From fdf448dd99d8227114515b573922de92683064d4 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 24 Nov 2026 16:36:10 -0800 Subject: [PATCH 08/19] test: removal guard needs a fresh gated lease check per removal In RemoveUnreachable every call of a Delete* or Remove* method must be immediately preceded by an if on StillHeld's error that returns: an ignored check, one check reused for a second delete and an unlisted removal method each fail (controls built from the real remove.go). The removal refuses an older epoch of the same server and the same epoch of another server, each alone, and every non-Run function taking a HolderID must be covered by such a case. Co-Authored-By: Claude Opus 5.5 --- .../frontend/chunkstore/layout/guard_test.go | 102 ++++++++++++++---- .../frontend/chunkstore/layout/stale_test.go | 52 +++++++++ 2 files changed, 131 insertions(+), 23 deletions(-) diff --git a/seaweed-block/core/frontend/chunkstore/layout/guard_test.go b/seaweed-block/core/frontend/chunkstore/layout/guard_test.go index 626b603de6..540797002a 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/guard_test.go +++ b/seaweed-block/core/frontend/chunkstore/layout/guard_test.go @@ -180,21 +180,57 @@ func guardFindings(code map[string]map[string]bool, decl, tests map[string]bool) } // removerOrderFindings checks the removal half of the time premise in the -// sources: in RemoveUnreachable, every statement that deletes -// (DeleteObject) sits in a block where an earlier statement checks the -// remover's own lease (StillHeld). +// sources: in RemoveUnreachable, every statement that calls a method named +// Delete* or Remove* is IMMEDIATELY preceded, in the same block, by a lease +// gate: an if statement whose init calls StillHeld and whose body returns +// on its error. A check whose result is ignored, one check reused for a +// second removal, and a removal method the scan does not list each fail. func removerOrderFindings(t *testing.T, srcs map[string]string) []string { t.Helper() - uses := func(n ast.Node, name string) bool { + removes := func(n ast.Node) bool { found := false ast.Inspect(n, func(n ast.Node) bool { - if sel, ok := n.(*ast.SelectorExpr); ok && sel.Sel.Name == name { - found = true + if c, ok := n.(*ast.CallExpr); ok { + if sel, ok := c.Fun.(*ast.SelectorExpr); ok && (strings.HasPrefix(sel.Sel.Name, "Delete") || strings.HasPrefix(sel.Sel.Name, "Remove")) { + found = true + } } return !found }) return found } + leaseGate := func(st ast.Stmt) bool { + is, ok := st.(*ast.IfStmt) + if !ok || is.Init == nil { + return false + } + as, ok := is.Init.(*ast.AssignStmt) + if !ok || len(as.Rhs) != 1 || len(as.Lhs) != 1 { + return false + } + call, ok := as.Rhs[0].(*ast.CallExpr) + if !ok { + return false + } + sel, ok := call.Fun.(*ast.SelectorExpr) + if !ok || sel.Sel.Name != "StillHeld" { + return false + } + errName, ok := as.Lhs[0].(*ast.Ident) + cond, ok2 := is.Cond.(*ast.BinaryExpr) + if !ok || !ok2 || cond.Op != token.NEQ { + return false + } + if x, ok := cond.X.(*ast.Ident); !ok || x.Name != errName.Name { + return false + } + for _, b := range is.Body.List { + if _, ok := b.(*ast.ReturnStmt); ok { + return true + } + } + return false + } var bad []string for fname, src := range srcs { file, err := parser.ParseFile(token.NewFileSet(), fname, src, 0) @@ -213,24 +249,16 @@ func removerOrderFindings(t *testing.T, srcs map[string]string) []string { return true } for i, st := range blk.List { - if _, isBlock := st.(*ast.BlockStmt); isBlock || !uses(st, "DeleteObject") { - continue + switch st.(type) { + case *ast.BlockStmt, *ast.RangeStmt, *ast.ForStmt: + continue // their bodies are checked as their own blocks } - if _, nested := st.(*ast.RangeStmt); nested { - continue // its body is checked as its own block - } - if _, nested := st.(*ast.ForStmt); nested { + if !removes(st) { continue } deletes++ - checked := false - for _, prev := range blk.List[:i] { - if uses(prev, "StillHeld") { - checked = true - } - } - if !checked { - bad = append(bad, "RemoveUnreachable deletes without a lease check before it in the same block") + if i == 0 || !leaseGate(blk.List[i-1]) { + bad = append(bad, "RemoveUnreachable removes without a lease gate immediately before it (an if on StillHeld's error that returns)") } } return true @@ -309,7 +337,7 @@ func RemoveUnreachable(ctx context.Context, x p, h l, names []string) error { } } return nil -}`, want: "deletes without a lease check"}, +}`, want: "without a lease gate immediately before it"}, "lease check after the delete": {file: "remove.go", src: `type p interface{ DeleteObject(context.Context, string) error } type l interface{ StillHeld(context.Context) error } func RemoveUnreachable(ctx context.Context, x p, h l, names []string) error { @@ -322,7 +350,7 @@ func RemoveUnreachable(ctx context.Context, x p, h l, names []string) error { } } return nil -}`, want: "deletes without a lease check"}, +}`, want: "without a lease gate immediately before it"}, "lease check once before the loop": {file: "remove.go", src: `type p interface{ DeleteObject(context.Context, string) error } type l interface{ StillHeld(context.Context) error } func RemoveUnreachable(ctx context.Context, x p, h l, names []string) error { @@ -335,11 +363,14 @@ func RemoveUnreachable(ctx context.Context, x p, h l, names []string) error { } } return nil -}`, want: "deletes without a lease check"}, +}`, want: "without a lease gate immediately before it"}, "claim without lease wait": {src: `func RunClaim(ctx context.Context, st HeadStore, lease LeaseWait, me HolderID) (Head, error) { return runTransition(ctx, st, func(h Head) (Head, bool, error) { return h, false, nil }) }`, want: "does not wait for the old lease", file: "claim.go"}, "transition not through runTransition": {src: `func RunZz(ctx context.Context, st HeadStore) (Head, error) { h, _, err := st.ReadHead(ctx); return h, err }`, want: "does not go through runTransition"}, + "ignored lease check": {file: "remove.go", src: removeVariant(t, "ignored"), want: "without a lease gate immediately before it"}, + "one check, two deletes": {file: "remove.go", src: removeVariant(t, "second"), want: "without a lease gate immediately before it"}, + "unlisted removal method": {file: "remove.go", src: removeVariant(t, "other"), want: "without a lease gate immediately before it"}, "remover method value": {src: `type p interface{ RemoveName(string) } func w(x p) { f := x.RemoveName; f("o") }`, want: "only RemoveUnreachable removes"}, } { @@ -355,3 +386,28 @@ func w(x p) { f := x.RemoveName; f("o") }`, want: "only RemoveUnreachable remove } } } + +// removeVariant returns remove.go's real source changed in one way, minus +// its package clause and imports (the controls add their own header). +func removeVariant(t *testing.T, mode string) string { + t.Helper() + b, err := os.ReadFile("remove.go") + if err != nil { + t.Fatal(err) + } + src := strings.ReplaceAll(string(b), "\r\n", "\n") + gate := "if err := lease.StillHeld(ctx); err != nil {\n\t\t\treturn removed, fmt.Errorf(\"%w: %v\", ErrLeaseLost, err)\n\t\t}" + switch mode { + case "ignored": + if !strings.Contains(src, gate) { + t.Fatal("remove.go lease gate not found") + } + src = strings.Replace(src, gate, "_ = lease.StillHeld(ctx)", 1) + case "second": + src = strings.Replace(src, "removed = append(removed, c)", "_ = pool.DeleteObject(ctx, c.Path())\n\t\tremoved = append(removed, c)", 1) + case "other": + src = strings.Replace(src, "removed = append(removed, c)", "_ = pool.RemoveOther(ctx, c.Path())\n\t\tremoved = append(removed, c)", 1) + } + i := strings.Index(src, ")\n") + return src[i+2:] +} diff --git a/seaweed-block/core/frontend/chunkstore/layout/stale_test.go b/seaweed-block/core/frontend/chunkstore/layout/stale_test.go index 832a436731..69e0d9a518 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/stale_test.go +++ b/seaweed-block/core/frontend/chunkstore/layout/stale_test.go @@ -1,8 +1,14 @@ package layout import ( + "context" + "errors" + "go/ast" + "go/parser" + "go/token" "reflect" "sort" + "strings" "testing" ) @@ -50,3 +56,49 @@ func TestTransitions_RefuseAStaleHolder(t *testing.T) { t.Fatalf("transitions not in the stale-holder table: %v", missing) } } + +// The removal refuses a stale holder too, one dimension at a time: an +// older epoch of the same server, and the same epoch held by another +// server; nothing is deleted. Every function of the package that takes a +// HolderID and is not a Run transition (those go through the pure methods +// above) must be listed here, so a new one fails until it is covered. +func TestHolderFunctions_RefuseAStaleHolder(t *testing.T) { + callers := map[string]HolderID{ + "older epoch, same server": {Epoch: me.Epoch - 1, Holder: me.Holder}, + "same epoch, another server": {Epoch: me.Epoch, Holder: "srv-b"}, + } + for who, c := range callers { + o, h, _, orphans := removeFixture(t) + r, err := NewReader(removeBase, "v1", o.fetch) + if err != nil { + t.Fatal(err) + } + _, err = RemoveUnreachable(context.Background(), &memHead{h: h}, r, o, &fakeHeld{}, c, "c1", 0, orphans) + if !errors.Is(err, ErrNotHolder) || len(o.deletes) != 0 { + t.Errorf("RemoveUnreachable by %s: %v, %d deletes; want ErrNotHolder and none", who, err, len(o.deletes)) + } + } + covered := map[string]bool{"RemoveUnreachable": true} + var missing []string + for fname, src := range packageSources(t, false) { + file, err := parser.ParseFile(token.NewFileSet(), fname, src, 0) + if err != nil { + t.Fatal(err) + } + for _, d := range file.Decls { + fn, ok := d.(*ast.FuncDecl) + if !ok || fn.Recv != nil || strings.HasPrefix(fn.Name.Name, "Run") { + continue + } + for _, p := range fn.Type.Params.List { + if id, ok := p.Type.(*ast.Ident); ok && id.Name == "HolderID" && !covered[fn.Name.Name] { + missing = append(missing, fn.Name.Name) + } + } + } + } + sort.Strings(missing) + if len(missing) != 0 { + t.Fatalf("functions taking a HolderID not covered by a stale-holder case: %v", missing) + } +} From da0ed44c94e7edbe40c7ab7cb8221eab9255cc38 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 24 Nov 2026 17:23:50 -0800 Subject: [PATCH 09/19] docs: INV-AUTH-PERSIST-BEFORE-PUBLISH-001 statement under 300 bytes The "never reported as failed" detail is already in the row's note. Co-Authored-By: Claude Opus 5.5 --- seaweed-block/docs/design/invariants.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index ee5b217e86..115deddf9c 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -712,7 +712,7 @@ Notes: |---|---|---|---|---|---|---| | `INV-AUTH-HOLDER-IDENTITY-001` | A primary holder is the pair (server id, replica id): every site that decides holdership (adopting a fact, lease first grant, renew, re-grant, HEAD claim, superseded exit) compares both; a missing server id is refused, never guessed. | AUTHORITY: PRIMARY holdership (supporting replicas are not holders) | `core/host/volume/host.go` `applyFact`, `IsSuperseded`, `recordOtherLine`; `assignment_holder.go` `assignmentNamesSelf`, `observeForeignHolder`, `refusePrimaryAssignment`; `host.go` `IsSuperseded`; `core/host/master/services.go` `SubscribeAssignments`; `workspace_service.go` `holderMatches`, `RenewWorkspaceLease`, `AckWorkspaceRevoked`; `cmd/blockvolume/chunk_remote.go` `chunkHolder`; `core/storage/chunk_restore.go` `ClaimChunkHead`; superseded exit covered by #409; `core/host/master/workspace_binding.go` `workspaceLineOwner`, `workspaceSourceHost`; `core/authority/assignment_owner.go` `captureAssignmentOwner`; `core/host/master/services.go` `assignmentFact`; `core/host/master/server_host_identity.go` `refuseServerIDFromOtherHost` (from `ReportHeartbeat`), `refuseWorkspaceHolderHost` (from `holderMatches` and, for a workspace volume, `SubscribeAssignments`), `holderSlotFact` (from `QueryVolumeStatus` and `observationVolume`/`observationReplicas`); `core/csi/master_backend.go` `primaryOwnedFrontends` (a CSI target only from a usable primary frontend); `core/authority/snapshot_builder.go` `expectOwnerForLine` (a moved line's replica facts and endpoint refreshes only from its owner, #425) | `TestAssignmentHolderIdentityRestartedOldProcess`, `TestAssignmentHolderIdentityMatchingServerStillAdopts`, `TestAssignmentHolderIdentityFencesPreviouslyHealthySameReplica`, `TestAssignmentHolderIdentityAdoptsAndWarnsCarriedEndpointMismatch`, `TestAssignmentHolderIdentityForeignStreamOrdering`, `TestAssignmentHolderIdentityForcedMoveRefusesEveryDeliveredVersion`, `TestAssignmentHolderIdentitySameEpochCannotChangeServer` (`core/host/volume/assignment_holder_test.go`); `TestWorkspaceLeaseGuardCarriesHolderServerIdentity` (`core/host/volume/workspace_holder_identity_test.go`); `TestWorkspaceLeaseRequiresHolderServerForGrantRenewAndRegrant`, `TestWorkspaceRevocationACKRequiresHolderServer` (`core/host/master/workspace_holder_identity_test.go`); `TestWorkspaceRPCCleanMovePreservesReplicaIdentity` (`core/host/master/workspace_service_test.go`); HEAD claim: `TestChunkHolderIsServerAndReplica` (`cmd/blockvolume/chunk_remote_test.go`), `TestWALStoreChunk_SameReplicaOnAnotherServerIsFenced` (`core/frontend/durable/provider_chunk_holder_test.go`); superseded exit: covered by #409 (server-id/replica-id pair, never replica alone); supporting replicas are not holders; descriptor identity not in this row; `TestWorkspaceLineOwnerIssuedAndHistorical` (`core/host/master/workspace_line_owner_test.go`), `TestWorkspaceRenewalRPCDuringHeldSameVolumeReservation` (`core/host/master/workspace_lease_horizon_test.go`); `TestAssignmentFactKeepsCapturedMoveOwnerWithoutReadableJournal` (`core/host/master/assignment_fact_owner_test.go`), `TestAssignmentOwnerReservedAndIssuedCapture` (`core/authority/assignment_owner_test.go`), `TestWorkspaceCrashAfterJournalBeforeEpochResumesSameGrant` (`core/authority/workspace_test.go`); `TestServerIDRefusedFromAHostOtherThanItsRegisteredOne`, `TestWorkspaceHolderRefusedFromAnotherHostAtRenewAckAndStream`, `TestPortalAndPrimaryComeFromTheLineServerNotTheFreshestHeartbeat`, `TestDisplayedPrimaryIsTheIssuedHolderNotThePlacementSlot`, `TestStatusListsNoFrontendWhenThePrimaryEvidenceIsMissing`, `TestCSIPublishesNoTargetWhenThePrimaryFrontendIsMissingOrRejected`, `TestDeletionReservedWorkspaceVolumeKeepsTheStreamHostCheck` (`core/host/master/server_host_identity_test.go`); `TestPublishTargetIsPrimaryOwned` (`core/csi/primary_owned_frontend_test.go`). Host scope: registered advertised-host consistency, not process uniqueness; a workspace holder's server id must be registered (no first-seen binding: host addresses change); non-workspace heartbeats from an unregistered id are not checked. Limits: trusts the network peer address (no NAT or proxy between volume and master in OSS); not authentication; `TestBuildSnapshotTakesTheMovedLinesReplicaFromItsOwner` (`core/authority/line_owner_snapshot_test.go`); `TestProcedureForcedMoveWithTheOldHostReturning` (`cmd/blockvolume/procedure_gate_integration_test.go`, tags subprocess chunkstore_integration: every forced-epoch line carries the new owner's endpoints) | `WorkspaceRegrant` `NoForeignAdoption`, `TargetNotFencedByOwnLine` (round 4 pinned simulations only; exhaustive combo10 pending) | ACTIVE | | `INV-AUTH-EPOCH-MINT-001` | Only the publisher mints epochs; a reassignment takes the per-volume maximum epoch plus one, also after a restart. | M2 Bound → Reassigned | `core/authority/authority.go` `applyWithWorkspaceMove`, `maxPublishedEpochForVolume` | `TestG8_0_Publisher_ReassignAdvancesPerVolumeEpochAcrossReplicaSlots` (`core/authority/g8_0_authority_failover_test.go`); `TestDurableAuthority_PublisherAdvancesFromReloaded` (`core/authority/authority_restart_test.go`); `TestG9F2_AssignmentRequestShapeHasNoEpochOrEndpointVersion` (`core/host/master/authority_request_bridge_test.go`) | `ControlPlane` `UniqueEpoch` | ACTIVE | -| `INV-AUTH-PERSIST-BEFORE-PUBLISH-001` | With an authority store configured, an assignment is written to the store before memory or any subscriber sees it, a failed write does not publish it, and an unknown outcome (directory fsync after the rename failed) fail-stops blockmaster, never reported as failed: see M2 any → (store write first). | M2 any → (store write first) | `core/authority/authority.go` `applyWithWorkspaceMove`; `core/authority/authority_store_file.go` `Put` (`failStopDurabilityUnknown` after a failed directory open or fsync behind the rename, every record; a close error after a good fsync is reported written; Windows keeps its previous behaviour) | `TestDurableAuthority_PutFailureRollsBackInMemoryState` (`core/authority/authority_restart_test.go`); `TestPutFailStopsWhenTheDirectoryFsyncFailsAfterRename`, `TestPutReportsWrittenWhenOnlyTheDirectoryCloseFails` (`core/authority/authority_store_dir_fsync_test.go`) | `ControlPlane` `UniqueEpoch` | ACTIVE | +| `INV-AUTH-PERSIST-BEFORE-PUBLISH-001` | With an authority store configured, an assignment is written to the store before memory or any subscriber sees it, a failed write does not publish it, and an unknown outcome (directory fsync after the rename failed) fail-stops blockmaster: see M2 any → (store write first). | M2 any → (store write first) | `core/authority/authority.go` `applyWithWorkspaceMove`; `core/authority/authority_store_file.go` `Put` (`failStopDurabilityUnknown` after a failed directory open or fsync behind the rename, every record; a close error after a good fsync is reported written; Windows keeps its previous behaviour) | `TestDurableAuthority_PutFailureRollsBackInMemoryState` (`core/authority/authority_restart_test.go`); `TestPutFailStopsWhenTheDirectoryFsyncFailsAfterRename`, `TestPutReportsWrittenWhenOnlyTheDirectoryCloseFails` (`core/authority/authority_store_dir_fsync_test.go`) | `ControlPlane` `UniqueEpoch` | ACTIVE | | `INV-AUTH-MOVE-JOURNAL-001` | A workspace move's epoch is issued only after its journal record is durable, and one move request id gets exactly one epoch, also across restarts. | M2 MoveReserved → MoveIssued | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `MoveWorkspace`, `sameWorkspaceRequest` | `TestWorkspaceMoveCannotIssueEpochWithoutJournal`, `TestWorkspaceCrashAfterJournalBeforeEpochResumesSameGrant` (`core/authority/workspace_test.go`); `TestWorkspaceReplayedIssueStartsGranteeLease` (`core/authority/workspace_unclaimed_grant_test.go`) | `ControlPlane` `Idempotent`, `JournalComplete` | ACTIVE | | `INV-AUTH-UNCERTAIN-001` | A failed authority write for a workspace volume, a lease extension included, latches uncertainty until a restart reloads the store: later authority changes and new or extended grants for that volume are refused. See M2 any (workspace) → Uncertain and Uncertain → Uncertain (move answer). | M2 any (workspace) → Uncertain; Uncertain → Uncertain (move answer) | `core/authority/authority.go` `applyWithWorkspaceMove`; `core/authority/workspace.go` `persistWorkspaceLocked`; `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `extendWorkspaceLease`; `core/authority/workspace.go` `WorkspaceMoveOutcomeError`, `MoveWorkspace`; `core/host/master/workspace_service.go` `MoveWorkspace` | `TestWorkspaceAmbiguousExtensionLatchesUncertainty` (`core/authority/workspace_lease_horizon_test.go`); `TestWorkspaceUncertaintyPrecedesRequestRefusal` (`core/authority/workspace_outcome_uncertain_test.go`), `TestWorkspaceMoveUnknownPrecedesAdmissionRefusals` (`core/host/master/workspace_uncertain_precedence_test.go`), `TestWorkspaceUncertainIssueWriteIsTyped` (`core/authority/workspace_outcome_uncertain_test.go`) | `ControlPlane` `UniqueEpoch`; `WorkspaceMoveOutcome` `NoFalseRefusal`, `CallerEndTyped`, `UncertainReplyClass` | ACTIVE | | `INV-LEASE-VIEW-001` | Whenever the publisher lock is released, each volume's lease view, the renewal path's only input, equals derive(the published authority line, workspace state, uncertainty, store presence). | M2 every workspace transition | `core/authority/workspace_lease_view.go` `deriveLeaseLocked`, `refreshLeaseViewLocked`, `publishIssuedLeaseLocked`, `setLeaseDeadlineLocked`; `core/authority/authority.go` `applyWithWorkspaceMove`, `reloadFromStore`; `core/authority/workspace.go` `persistWorkspaceLocked` | `TestWorkspaceLeaseViewMatchesDeriveAfterEveryWriter`, `TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose` (`core/authority/workspace_lease_horizon_test.go`) | — | ACTIVE | From 4c23e07de8b8ca1dd4f56b92566fedf32d17bbf6 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 24 Nov 2026 17:26:18 -0800 Subject: [PATCH 10/19] docs: one property per snapshot kernel ledger row The removal and HEAD-write rows exceeded the ledger's 300-character statement limit; each is now split into rows of one property (the removal itself, what stops it, its source guard; the HEAD write path and its source guard). Co-Authored-By: Claude Opus 5.5 --- seaweed-block/docs/design/invariants.md | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 6e900f4cf6..5f3c99c8bf 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -545,7 +545,7 @@ stateDiagram-v2 ## Part B. Invariant ledger -339 rows: 268 ACTIVE, 67 STUB, 4 ARCHIVED; 15 kept from the internal ledger, 324 new. +342 rows: 271 ACTIVE, 67 STUB, 4 ARCHIVED; 15 kept from the internal ledger, 327 new. The "Machine / transition" column refers to Part A. Notes under a table record what a row does not cover and, for kept rows, what was narrowed from the internal ledger. @@ -1085,7 +1085,8 @@ Notes: | ID | Statement | Machine / transition | Enforced in | Test | TLA+ property | Status | |---|---|---|---|---|---|---| | `INV-SNAPK-NAME-CANONICAL-001` | A chunk is named by its index and the SHA-256 of its bytes under `pool//`; a segment and a root are named by the SHA-256 of their canonical encoding, and decoding refuses any bytes the encoder would not write, so an object has one encoding and one name. | Content-named layout (no state transition) | `core/frontend/chunkstore/layout` `layout.go` `ParseChunkName`, `DecodeSegment`, `DecodeRoot` | `TestParseChunkName_RoundTripAndRefusals`, `TestDecodeSegment_RefusesNonCanonical`, `TestRoot_Refusals`, `TestBuild_ShardsAndIncrementalReuse` | — (the snapshot kernel model is not in this repository) | ACTIVE | -| `INV-SNAPK-HEAD-WRITE-001` | HEAD changes only by one conditional update on its generation through `runTransition`; no path in the package creates a HEAD, and an absent HEAD is refused. A source scan refuses any other use of `UpdateHead`, a transition without its closure and interrupt tests, and any store remover other than the lease-checked RemoveUnreachable. | M9 every transition | `core/frontend/chunkstore/layout` `head.go` `runTransition`; `HeadStore` (read and conditional update only) | `TestGuard_WritersTransitionsAndRemovers`, `TestGuard_Controls`, `TestRunBegin` | — (the snapshot kernel model is not in this repository) | ACTIVE | +| `INV-SNAPK-HEAD-WRITE-001` | HEAD changes only by one conditional update on its generation through `runTransition`; no path in the package creates a HEAD, and an absent HEAD is refused. | M9 every transition | `core/frontend/chunkstore/layout` `head.go` `runTransition`; `HeadStore` (read and conditional update only) | `TestGuard_WritersTransitionsAndRemovers`, `TestRunBegin` | — (the snapshot kernel model is not in this repository) | ACTIVE | +| `INV-SNAPK-HEAD-GUARD-001` | A source scan refuses any other use of `UpdateHead`, a transition without its closure and interrupt tests, and any store remover other than the lease-gated RemoveUnreachable. | M9 every transition | `core/frontend/chunkstore/layout` (source scan of the package) | `TestGuard_WritersTransitionsAndRemovers`, `TestGuard_Controls` | — (the snapshot kernel model is not in this repository) | ACTIVE | | `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` | `TestAbort_Closure`, `TestAbort_IdleMeansNoActivityRemains`, `TestAbort_RollBackAfterOwnCrash`, `TestRunAbort_InterruptAtEveryStep` | — (the snapshot kernel model is not in this repository) | ACTIVE | @@ -1094,8 +1095,10 @@ Notes: | `INV-SNAPK-CLAIM-LEASE-001` | A claim takes HEAD only at a newer epoch and only after every older holder's lease has ended (checked after the read, before the update); it voids any open session or cleaning, so the old holder's commit, abort and begin are refused. | M9 any → idle (Claim) | `core/frontend/chunkstore/layout` `claim.go` `RunClaim`, `Head.Claim` | `TestClaim_Closure`, `TestRunClaim_WaitsForTheOldLease`, `TestRunClaim_VoidsTheOldSession`, `TestRunClaim_InterruptAtEveryStep` | — (the snapshot kernel model is not in this repository) | ACTIVE | | `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-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-SNAPK-REMOVE-LEASE-001` | A pool name is removed only inside the holder's own cleaning, only when no root in HEAD names it, and only after the remover's own lease is checked immediately before that delete; a lapsed lease stops the pass, an unreadable root or segment stops it before any delete, and a snapshot open on the volume refuses it. A source scan requires the lease check before every delete in the same block and refuses any other remover. | M9 clean → clean (RemoveUnreachable) | `core/frontend/chunkstore/layout` `remove.go` `RemoveUnreachable` | `TestRemoveUnreachable_RemovesOnlyWhatNoRootNames`, `TestRemoveUnreachable_RefusedOutsideItsCleaning`, `TestRemoveUnreachable_StopsWhenTheLeaseLapses`, `TestRemoveUnreachable_NothingRemovedOnAPartialView`, `TestCleaningPass_InterruptAtEveryStep`, `TestGuard_Controls` | — (the snapshot kernel model is not in this repository) | ACTIVE | -| `INV-SNAPK-STALE-HOLDER-001` | Every transition refuses an older epoch of the same server and the same epoch held by another server, in idle, snap and clean; a new transition must be added to the table. | M9 every transition | `core/frontend/chunkstore/layout` `Head.heldBy` and each transition | `TestTransitions_RefuseAStaleHolder` | — (the snapshot kernel model is not in this repository) | ACTIVE | +| `INV-SNAPK-REMOVE-LEASE-001` | A pool name is removed only inside the holder's own cleaning, only when no root in HEAD (current or snapshot) names it, and only after the remover's own lease is checked immediately before that delete. | M9 clean → clean (RemoveUnreachable) | `core/frontend/chunkstore/layout` `remove.go` `RemoveUnreachable` | `TestRemoveUnreachable_RemovesOnlyWhatNoRootNames`, `TestCleaningPass_InterruptAtEveryStep`, `TestHolderFunctions_RefuseAStaleHolder` | — (the snapshot kernel model is not in this repository) | ACTIVE | +| `INV-SNAPK-REMOVE-STOP-001` | A lapsed lease stops a removal pass before the next delete; an unreadable root or segment stops it before any delete; a snapshot open on the volume, another cleaning or idle refuses it. | M9 clean → clean (RemoveUnreachable) | `core/frontend/chunkstore/layout` `remove.go` `RemoveUnreachable` | `TestRemoveUnreachable_StopsWhenTheLeaseLapses`, `TestRemoveUnreachable_NothingRemovedOnAPartialView`, `TestRemoveUnreachable_RefusedOutsideItsCleaning` | — (the snapshot kernel model is not in this repository) | ACTIVE | +| `INV-SNAPK-REMOVE-GUARD-001` | A source scan requires, immediately before every Delete or Remove call in RemoveUnreachable, an if on StillHeld's error that returns: an ignored check, a reused check or an unlisted removal method fails. | M9 clean → clean (RemoveUnreachable) | `core/frontend/chunkstore/layout` (source scan of `remove.go`) | `TestGuard_WritersTransitionsAndRemovers`, `TestGuard_Controls` | — (the snapshot kernel model is not in this repository) | ACTIVE | +| `INV-SNAPK-STALE-HOLDER-001` | Every transition refuses an older epoch of the same server, the same epoch held by another server, and the same epoch and server with another claim id, in idle, snap and clean; a new transition must be added to the table. | M9 every transition | `core/frontend/chunkstore/layout` `Head.heldBy` and each transition | `TestTransitions_RefuseAStaleHolder` | — (the snapshot kernel model is not in this repository) | ACTIVE | Notes: From 249afe303aa2fa02a4c6a093dc2df6765143ee75 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 24 Nov 2026 18:14:22 -0800 Subject: [PATCH 11/19] layout: removal by mark and conditional delete (7') The removal no longer rests on a lease check before an unconditional delete, which a delete landing after the lease and a successor's commit defeated. Every object entry carries the session of its last writer and a mark. RemoveUnreachable plans after BeginClean, then for each unreachable candidate MARKs it (conditional on the metadata read for the plan, unmarked) and DELETEs it (conditional on that mark). Writing an object for a session (EnsureObject) creates it, or reuses an existing one by a conditional update that sets the session and clears any mark, so a reuse after the plan or after the mark makes the remover's write fail its own condition, however late it lands. A commit names only objects its own session wrote or reused, unmarked. The source guard now requires DeleteMarked as the remover's only removal, each immediately after a gate on its mark's error. Tests cover both reuse windows (after the plan, after the mark), another session's mark, the commit's session rule and the cleaning killed at each of its six writes. Co-Authored-By: Claude Opus 5.5 --- .../frontend/chunkstore/head_readers_test.go | 30 +- .../core/frontend/chunkstore/layout/commit.go | 53 ++-- .../frontend/chunkstore/layout/commit_test.go | 58 ++-- .../frontend/chunkstore/layout/guard_test.go | 117 ++++---- .../frontend/chunkstore/layout/objects.go | 87 ++++++ .../chunkstore/layout/objects_test.go | 189 ++++++++++++ .../core/frontend/chunkstore/layout/remove.go | 63 ++-- .../frontend/chunkstore/layout/remove_test.go | 271 ++++++++++-------- .../chunkstore/layout/session_test.go | 97 +++++-- .../frontend/chunkstore/layout/stale_test.go | 6 +- seaweed-block/docs/design/invariants.md | 13 +- 11 files changed, 680 insertions(+), 304 deletions(-) create mode 100644 seaweed-block/core/frontend/chunkstore/layout/objects.go create mode 100644 seaweed-block/core/frontend/chunkstore/layout/objects_test.go diff --git a/seaweed-block/core/frontend/chunkstore/head_readers_test.go b/seaweed-block/core/frontend/chunkstore/head_readers_test.go index 434da26d5c..05e5a59161 100644 --- a/seaweed-block/core/frontend/chunkstore/head_readers_test.go +++ b/seaweed-block/core/frontend/chunkstore/head_readers_test.go @@ -40,7 +40,7 @@ var headReaders = map[string]string{ "core/frontend/chunkstore/share_guard.go beginShare -> ReadHead": "refuses outcome_unknown: the HEAD to share is no longer current", "core/frontend/chunkstore/usage.go Usage -> ReadHead": "GAP: reports an empty image, no error (probe Usage)", "core/frontend/chunkstore/verify.go readHead -> LookupEntry": "finding ROOT_INVALID (probe Verify)", - "core/frontend/chunkstore/layout/remove.go RemoveUnreachable -> ReadHead": "refuses ErrHeadAbsent and deletes nothing (probe LayoutRemoval)", + "core/frontend/chunkstore/layout/remove.go RemoveUnreachable -> ReadHead": "refuses ErrHeadAbsent and writes nothing to the objects (probe LayoutRemoval)", "core/frontend/chunkstore/layout/head.go runTransition -> ReadHead": "refuses ErrHeadAbsent and writes nothing; no layout transition creates a HEAD (probe LayoutTransition)", "core/frontend/chunkstore/verify.go run -> LookupEntry": "finding ROOT_INVALID (probe Verify)", "core/frontend/chunkstore/volume_delete.go DeleteVolume -> ReadHead": "operator delete writes a deleting HEAD from nothing and completes (probe DeleteVolume)", @@ -271,11 +271,11 @@ func TestHeadReaders_AbsentHeadProbes(t *testing.T) { t.Fatal(err) } pool := &countingPool{} - if _, err := layout.RemoveUnreachable(ctx, &absentLayoutHead{}, r, pool, okLease{}, layout.HolderID{Epoch: 1, Holder: "h"}, "c", 0, []layout.ChunkName{layout.NameChunk(1, []byte("x"))}); !errors.Is(err, layout.ErrHeadAbsent) { + if _, err := layout.RemoveUnreachable(ctx, &absentLayoutHead{}, r, pool, layout.HolderID{Epoch: 1, Holder: "h"}, "c", 0, []layout.ChunkName{layout.NameChunk(1, []byte("x"))}); !errors.Is(err, layout.ErrHeadAbsent) { t.Fatalf("layout removal over an absent HEAD: %v; want ErrHeadAbsent", err) } - if pool.deletes != 0 { - t.Fatalf("layout removal over an absent HEAD deleted %d objects", pool.deletes) + if pool.writes != 0 { + t.Fatalf("layout removal over an absent HEAD wrote %d times to the objects", pool.writes) } }) t.Run("ForkReplay", func(t *testing.T) { @@ -312,10 +312,20 @@ func (a *absentLayoutHead) UpdateHead(context.Context, uint64, layout.Head) erro return nil } -type countingPool struct{ deletes int } +// countingPool is a layout object store that counts writes and holds +// nothing. +type countingPool struct{ writes int } -func (p *countingPool) DeleteObject(context.Context, string) error { p.deletes++; return nil } - -type okLease struct{} - -func (okLease) StillHeld(context.Context) error { return nil } +func (p *countingPool) Stat(context.Context, string) (layout.ObjectMeta, bool, error) { + return layout.ObjectMeta{}, false, nil +} +func (p *countingPool) Create(context.Context, string, []byte, string) error { p.writes++; return nil } +func (p *countingPool) Reuse(context.Context, string, layout.ObjectMeta, string) error { + p.writes++ + return nil +} +func (p *countingPool) Mark(context.Context, string, layout.ObjectMeta, string) error { + p.writes++ + return nil +} +func (p *countingPool) DeleteMarked(context.Context, string, string) error { p.writes++; return nil } diff --git a/seaweed-block/core/frontend/chunkstore/layout/commit.go b/seaweed-block/core/frontend/chunkstore/layout/commit.go index 3afbc378a1..ca60b41a95 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/commit.go +++ b/seaweed-block/core/frontend/chunkstore/layout/commit.go @@ -100,12 +100,14 @@ func (h Head) Commit(me HolderID, session string, root RootName, position uint64 return next, true, nil } -// RunCommit checks that every object the new root reaches is written (the -// new chunks of this volume against HEAD's current root, every segment, -// the root), then commits by one conditional update. Prev must build to -// HEAD's current root; a re-run after a lost reply finds the commit -// applied and writes nothing. -func RunCommit(ctx context.Context, st HeadStore, look Lookup, volRoot, vol string, me HolderID, req CommitRequest) (Head, error) { +// RunCommit checks that every object the new root reaches is written by +// this session and unmarked (the new chunks of this volume against HEAD's +// current root, every segment, the root: see EnsureObject), then commits +// by one conditional update. An object present but written by another +// session, or marked for removal, is not prepared: EnsureObject reuses it +// first. Prev must build to HEAD's current root; a re-run after a lost +// reply finds the commit applied and writes nothing. +func RunCommit(ctx context.Context, st HeadStore, os ObjectStore, vol string, me HolderID, req CommitRequest) (Head, error) { root, segs, err := rootOf(req.Next) if err != nil { return Head{}, err @@ -131,12 +133,15 @@ func RunCommit(ctx context.Context, st HeadStore, look Lookup, volRoot, vol stri return Head{}, false, ErrStaleBase } } - missing, err := MissingOwn(ctx, look, volRoot, vol, newOwn(vol, req.Prev, req.Next)) - if err != nil { - return Head{}, false, err + var rels []string + chunks := newOwn(vol, req.Prev, req.Next) + idx := make([]uint64, 0, len(chunks)) + for i := range chunks { + idx = append(idx, i) } - if len(missing) > 0 { - return Head{}, false, fmt.Errorf("%w: %d chunks, first %s", ErrNotPrepared, len(missing), missing[0]) + sort.Slice(idx, func(a, b int) bool { return idx[a] < idx[b] }) + for _, i := range idx { + rels = append(rels, chunks[i].Chunk.Path()) } names := make([]SegName, 0, len(segs)) for n := range segs { @@ -144,24 +149,18 @@ func RunCommit(ctx context.Context, st HeadStore, look Lookup, volRoot, vol stri } sort.Slice(names, func(a, b int) bool { return names[a].Shard < names[b].Shard }) for _, n := range names { - if err := present(ctx, look, volRoot, n.Path()); err != nil { - return Head{}, false, err - } + rels = append(rels, n.Path()) } - if err := present(ctx, look, volRoot, root.Path()); err != nil { - return Head{}, false, err + rels = append(rels, root.Path()) + for _, rel := range rels { + ok, err := ownedBySession(ctx, os, rel, req.Session) + if err != nil { + return Head{}, false, fmt.Errorf("layout: look up %s: %w", rel, err) + } + if !ok { + return Head{}, false, fmt.Errorf("%w: %s (absent, written by another session, or marked)", ErrNotPrepared, rel) + } } return h.Commit(me, req.Session, root, req.Position, req.Snapshot) }) } - -func present(ctx context.Context, look Lookup, volRoot, rel string) error { - ok, err := Present(ctx, look, volRoot, rel) - if err != nil { - return fmt.Errorf("layout: look up %s: %w", rel, err) - } - if !ok { - return fmt.Errorf("%w: %s", ErrNotPrepared, rel) - } - return nil -} diff --git a/seaweed-block/core/frontend/chunkstore/layout/commit_test.go b/seaweed-block/core/frontend/chunkstore/layout/commit_test.go index 5a2119b002..79044c537a 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/commit_test.go +++ b/seaweed-block/core/frontend/chunkstore/layout/commit_test.go @@ -11,9 +11,9 @@ import ( const volRoot = "/swblock/chunks/v1" -// prepared writes (in the fake store) every object a commit of next needs: -// next's own chunks, its segments and its root. -func prepared(t *testing.T, f *fakeStore, next map[uint64]Ref) RootName { +// prepared writes (in the object store, as session) every object a commit +// of next needs: next's own chunks, its segments and its root. +func prepared(t *testing.T, f *memObjects, next map[uint64]Ref, session string) RootName { t.Helper() root, segs, err := Build(next) if err != nil { @@ -21,17 +21,17 @@ func prepared(t *testing.T, f *fakeStore, next map[uint64]Ref) RootName { } for i, r := range next { if r.Owner == "v1" { - f.have[path.Join(volRoot, next[i].Chunk.Path())] = true + f.put(next[i].Chunk.Path(), []byte("c"), session) } } for n := range segs { - f.have[path.Join(volRoot, n.Path())] = true + f.put(n.Path(), []byte("s"), session) } rn, _, err := NameRoot(root) if err != nil { t.Fatal(err) } - f.have[path.Join(volRoot, rn.Path())] = true + f.put(rn.Path(), []byte("r"), session) return rn } @@ -89,19 +89,19 @@ func TestCommit_Closure(t *testing.T) { // commitFixture: HEAD is snap(s1) at current root = prev's root; prev and // next share chunk 0 (unchanged), next changes chunk 3, adds chunk 10004 // and names chunk 7 of volume "src". -func commitFixture(t *testing.T) (*fakeStore, Head, CommitRequest) { +func commitFixture(t *testing.T) (*memObjects, Head, CommitRequest) { t.Helper() - f := &fakeStore{have: map[string]bool{}} + f := newMemObjects(volRoot) prev := manifest(ref("v1", 0, "a"), ref("v1", 3, "b")) - prevRoot := prepared(t, f, prev) + prevRoot := prepared(t, f, prev, "s0") next := manifest(ref("v1", 0, "a"), ref("v1", 3, "b2"), ref("v1", 10004, "c"), ref("src", 7, "d")) - prepared(t, f, next) + prepared(t, f, next, "s1") h := Head{Gen: 7, Epoch: 3, Holder: "srv-a", Activity: Activity{Kind: ActSnap, Session: "s1"}, Current: &prevRoot, Position: 40} return f, h, CommitRequest{Session: "s1", Prev: prev, Next: next, Position: 50, Snapshot: "hourly"} } -func runCommit(st HeadStore, f *fakeStore, req CommitRequest) (Head, error) { - return RunCommit(context.Background(), st, f.look, volRoot, "v1", me, req) +func runCommit(st HeadStore, f *memObjects, req CommitRequest) (Head, error) { + return RunCommit(context.Background(), st, f, "v1", me, req) } func TestRunCommit_LooksUpOnlyWhatIsNew(t *testing.T) { @@ -146,7 +146,7 @@ func TestRunCommit_RefusesUnwrittenObjects(t *testing.T) { case "root": p = root.Path() } - delete(f.have, path.Join(volRoot, p)) + delete(f.objs, path.Join(volRoot, p)) st := &memHead{h: &h} if _, err := runCommit(st, f, req); !errors.Is(err, ErrNotPrepared) { t.Fatalf("commit with its %s missing: %v; want ErrNotPrepared", what, err) @@ -179,9 +179,9 @@ func TestRunCommit_StaleBaseAndLookupFailure(t *testing.T) { t.Fatal("HEAD written by a refused commit") } // The first commit of a volume: no current root, no previous manifest. - f2 := &fakeStore{have: map[string]bool{}} + f2 := newMemObjects(volRoot) next := manifest(ref("v1", 1, "x")) - prepared(t, f2, next) + prepared(t, f2, next, "s1") h2 := Head{Gen: 1, Epoch: 3, Holder: "srv-a", Activity: Activity{Kind: ActSnap, Session: "s1"}} if got, err := runCommit(&memHead{h: &h2}, f2, CommitRequest{Session: "s1", Next: next, Position: 5}); err != nil || got.Current == nil { t.Fatalf("first commit: %+v %v", got, err) @@ -207,8 +207,8 @@ func TestRunCommit_InterruptAtEveryStep(t *testing.T) { // refused. func TestRunCommit_AfterAnEmptyPublishedRoot(t *testing.T) { ctx := context.Background() - f := &fakeStore{have: map[string]bool{}} - prepared(t, f, nil) + f := newMemObjects(volRoot) + prepared(t, f, nil, "s0") h := idleHead() st := &memHead{h: &h} if _, err := RunBegin(ctx, st, me, "s0"); err != nil { @@ -223,11 +223,12 @@ func TestRunCommit_AfterAnEmptyPublishedRoot(t *testing.T) { if _, err := RunBegin(ctx, st, me, "s1"); err != nil { t.Fatal(err) } + prepared(t, f, nil, "s1") // each session writes (reuses) what it commits if _, err := runCommit(st, f, CommitRequest{Session: "s1", Prev: map[uint64]Ref{}, Position: 1}); err != nil { t.Fatalf("empty -> empty: %v", err) } next := manifest(ref("v1", 1, "x")) - prepared(t, f, next) + prepared(t, f, next, "s2") if _, err := RunBegin(ctx, st, me, "s2"); err != nil { t.Fatal(err) } @@ -266,3 +267,24 @@ func TestAbort_AfterCommitLeavesTheCommit(t *testing.T) { t.Fatalf("Abort after the commit wrote or changed HEAD: %+v", st.h) } } + +// A commit names only objects its own session wrote or reused, unmarked: +// one written by another session, or marked by a cleaning, is not +// prepared until EnsureObject reuses it. +func TestRunCommit_NeedsObjectsOfItsOwnSession(t *testing.T) { + for _, meta := range []ObjectMeta{{Session: "s0"}, {Session: "s1", Mark: "c9"}} { + f, h, req := commitFixture(t) + rel := req.Next[10004].Chunk.Path() + f.objs[path.Join(volRoot, rel)].meta = meta + st := &memHead{h: &h} + if _, err := runCommit(st, f, req); !errors.Is(err, ErrNotPrepared) || st.updates != 0 { + t.Fatalf("object %+v: %v (%d writes); want ErrNotPrepared, nothing written", meta, err, st.updates) + } + if err := EnsureObject(context.Background(), f, rel, []byte("c"), "s1"); err != nil { + t.Fatal(err) + } + if _, err := runCommit(st, f, req); err != nil { + t.Fatalf("after EnsureObject reused it: %v", err) + } + } +} diff --git a/seaweed-block/core/frontend/chunkstore/layout/guard_test.go b/seaweed-block/core/frontend/chunkstore/layout/guard_test.go index 540797002a..ca861ff2be 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/guard_test.go +++ b/seaweed-block/core/frontend/chunkstore/layout/guard_test.go @@ -179,27 +179,28 @@ func guardFindings(code map[string]map[string]bool, decl, tests map[string]bool) return bad } -// removerOrderFindings checks the removal half of the time premise in the -// sources: in RemoveUnreachable, every statement that calls a method named -// Delete* or Remove* is IMMEDIATELY preceded, in the same block, by a lease -// gate: an if statement whose init calls StillHeld and whose body returns -// on its error. A check whose result is ignored, one check reused for a -// second removal, and a removal method the scan does not list each fail. +// removerOrderFindings checks the removal rule (7') in the sources: in +// RemoveUnreachable the only removal call is DeleteMarked (a delete +// conditional on the remover's own mark), and each is IMMEDIATELY +// preceded, in the same block, by a mark gate: an if statement whose init +// calls Mark and whose body leaves on its error (return or continue). An +// unconditional delete, an ignored mark, one mark reused for a second +// delete and an unlisted removal method each fail. func removerOrderFindings(t *testing.T, srcs map[string]string) []string { t.Helper() - removes := func(n ast.Node) bool { - found := false + removals := func(n ast.Node) []string { + var names []string ast.Inspect(n, func(n ast.Node) bool { if c, ok := n.(*ast.CallExpr); ok { if sel, ok := c.Fun.(*ast.SelectorExpr); ok && (strings.HasPrefix(sel.Sel.Name, "Delete") || strings.HasPrefix(sel.Sel.Name, "Remove")) { - found = true + names = append(names, sel.Sel.Name) } } - return !found + return true }) - return found + return names } - leaseGate := func(st ast.Stmt) bool { + markGate := func(st ast.Stmt) bool { is, ok := st.(*ast.IfStmt) if !ok || is.Init == nil { return false @@ -213,7 +214,7 @@ func removerOrderFindings(t *testing.T, srcs map[string]string) []string { return false } sel, ok := call.Fun.(*ast.SelectorExpr) - if !ok || sel.Sel.Name != "StillHeld" { + if !ok || sel.Sel.Name != "Mark" { return false } errName, ok := as.Lhs[0].(*ast.Ident) @@ -224,12 +225,19 @@ func removerOrderFindings(t *testing.T, srcs map[string]string) []string { if x, ok := cond.X.(*ast.Ident); !ok || x.Name != errName.Name { return false } - for _, b := range is.Body.List { - if _, ok := b.(*ast.ReturnStmt); ok { - return true + leaves := false + ast.Inspect(is.Body, func(n ast.Node) bool { + switch x := n.(type) { + case *ast.ReturnStmt: + leaves = true + case *ast.BranchStmt: + if x.Tok == token.CONTINUE { + leaves = true + } } - } - return false + return !leaves + }) + return leaves } var bad []string for fname, src := range srcs { @@ -253,12 +261,18 @@ func removerOrderFindings(t *testing.T, srcs map[string]string) []string { case *ast.BlockStmt, *ast.RangeStmt, *ast.ForStmt: continue // their bodies are checked as their own blocks } - if !removes(st) { + names := removals(st) + if len(names) == 0 { continue } deletes++ - if i == 0 || !leaseGate(blk.List[i-1]) { - bad = append(bad, "RemoveUnreachable removes without a lease gate immediately before it (an if on StillHeld's error that returns)") + for _, name := range names { + if name != "DeleteMarked" { + bad = append(bad, "RemoveUnreachable calls "+name+": its only removal is DeleteMarked, conditional on its own mark") + } + } + if i == 0 || !markGate(blk.List[i-1]) { + bad = append(bad, "RemoveUnreachable removes without a mark gate immediately before it (an if on Mark's error that leaves)") } } return true @@ -328,49 +342,14 @@ func TestGuard_Controls(t *testing.T) { "lease wait outside claim": {src: `func w(ctx context.Context, l LeaseWait) error { return l.OldLeaseEnded(ctx, 1) }`, want: "only RunClaim claims"}, "remover outside RemoveUnreachable": {src: `type p interface{ DeleteObject(context.Context, string) error } func w(ctx context.Context, x p) error { return x.DeleteObject(ctx, "o") }`, want: "only RemoveUnreachable removes"}, - "removal without lease check": {file: "remove.go", src: `type p interface{ DeleteObject(context.Context, string) error } -type l interface{ StillHeld(context.Context) error } -func RemoveUnreachable(ctx context.Context, x p, h l, names []string) error { - for _, n := range names { - if err := x.DeleteObject(ctx, n); err != nil { - return err - } - } - return nil -}`, want: "without a lease gate immediately before it"}, - "lease check after the delete": {file: "remove.go", src: `type p interface{ DeleteObject(context.Context, string) error } -type l interface{ StillHeld(context.Context) error } -func RemoveUnreachable(ctx context.Context, x p, h l, names []string) error { - for _, n := range names { - if err := x.DeleteObject(ctx, n); err != nil { - return err - } - if err := h.StillHeld(ctx); err != nil { - return err - } - } - return nil -}`, want: "without a lease gate immediately before it"}, - "lease check once before the loop": {file: "remove.go", src: `type p interface{ DeleteObject(context.Context, string) error } -type l interface{ StillHeld(context.Context) error } -func RemoveUnreachable(ctx context.Context, x p, h l, names []string) error { - if err := h.StillHeld(ctx); err != nil { - return err - } - for _, n := range names { - if err := x.DeleteObject(ctx, n); err != nil { - return err - } - } - return nil -}`, want: "without a lease gate immediately before it"}, "claim without lease wait": {src: `func RunClaim(ctx context.Context, st HeadStore, lease LeaseWait, me HolderID) (Head, error) { return runTransition(ctx, st, func(h Head) (Head, bool, error) { return h, false, nil }) }`, want: "does not wait for the old lease", file: "claim.go"}, "transition not through runTransition": {src: `func RunZz(ctx context.Context, st HeadStore) (Head, error) { h, _, err := st.ReadHead(ctx); return h, err }`, want: "does not go through runTransition"}, - "ignored lease check": {file: "remove.go", src: removeVariant(t, "ignored"), want: "without a lease gate immediately before it"}, - "one check, two deletes": {file: "remove.go", src: removeVariant(t, "second"), want: "without a lease gate immediately before it"}, - "unlisted removal method": {file: "remove.go", src: removeVariant(t, "other"), want: "without a lease gate immediately before it"}, + "unconditional delete": {file: "remove.go", src: removeVariant(t, "unconditional"), want: "its only removal is DeleteMarked"}, + "ignored mark": {file: "remove.go", src: removeVariant(t, "ignored"), want: "without a mark gate immediately before it"}, + "one mark, two deletes": {file: "remove.go", src: removeVariant(t, "second"), want: "without a mark gate immediately before it"}, + "unlisted removal method": {file: "remove.go", src: removeVariant(t, "other"), want: "without a mark gate immediately before it"}, "remover method value": {src: `type p interface{ RemoveName(string) } func w(x p) { f := x.RemoveName; f("o") }`, want: "only RemoveUnreachable removes"}, } { @@ -396,17 +375,21 @@ func removeVariant(t *testing.T, mode string) string { t.Fatal(err) } src := strings.ReplaceAll(string(b), "\r\n", "\n") - gate := "if err := lease.StillHeld(ctx); err != nil {\n\t\t\treturn removed, fmt.Errorf(\"%w: %v\", ErrLeaseLost, err)\n\t\t}" + gate := "if err := os.Mark(ctx, c.Path(), plan, session); err != nil {" + if !strings.Contains(src, gate) { + t.Fatal("remove.go mark gate not found") + } switch mode { case "ignored": - if !strings.Contains(src, gate) { - t.Fatal("remove.go lease gate not found") - } - src = strings.Replace(src, gate, "_ = lease.StillHeld(ctx)", 1) + i := strings.Index(src, gate) + j := strings.Index(src[i:], "\n\t\t}\n") + i + len("\n\t\t}\n") + src = src[:i] + "_ = os.Mark(ctx, c.Path(), plan, session)\n" + src[j:] case "second": - src = strings.Replace(src, "removed = append(removed, c)", "_ = pool.DeleteObject(ctx, c.Path())\n\t\tremoved = append(removed, c)", 1) + src = strings.Replace(src, "removed = append(removed, c)", "_ = os.DeleteMarked(ctx, c.Path(), session)\n\t\tremoved = append(removed, c)", 1) case "other": - src = strings.Replace(src, "removed = append(removed, c)", "_ = pool.RemoveOther(ctx, c.Path())\n\t\tremoved = append(removed, c)", 1) + src = strings.Replace(src, "removed = append(removed, c)", "_ = os.RemoveOther(ctx, c.Path())\n\t\tremoved = append(removed, c)", 1) + case "unconditional": + src = strings.Replace(src, "if err := os.DeleteMarked(ctx, c.Path(), session); err != nil {", "if err := os.DeleteObject(ctx, c.Path()); err != nil {", 1) } i := strings.Index(src, ")\n") return src[i+2:] diff --git a/seaweed-block/core/frontend/chunkstore/layout/objects.go b/seaweed-block/core/frontend/chunkstore/layout/objects.go new file mode 100644 index 0000000000..1a63a9995b --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/layout/objects.go @@ -0,0 +1,87 @@ +package layout + +import ( + "context" + "errors" + "fmt" +) + +// ObjectMeta is what an object entry (chunk, segment, root) carries besides +// its bytes: the session of its last writer and a removal mark (the +// session of a cleaning that planned to remove it; empty when unmarked). +type ObjectMeta struct { + Session string + Mark string +} + +// ErrExists is returned by ObjectStore.Create when the entry exists. +var ErrExists = errors.New("layout: object exists") + +// ObjectStore holds a volume's objects by path relative to the volume +// root. Every change of an existing entry is conditional on its metadata, +// so a late write fails its own condition instead of undoing a newer one. +type ObjectStore interface { + // Stat returns an entry's metadata; a missing entry is found=false. + Stat(ctx context.Context, rel string) (meta ObjectMeta, found bool, err error) + // Create writes a new entry exclusively (data first, entry after), + // with session as its writer; ErrExists if the entry exists. + Create(ctx context.Context, rel string, data []byte, session string) error + // Reuse sets session as the writer and clears the mark, only if the + // entry's metadata is still expect (ErrPrecondition otherwise). + Reuse(ctx context.Context, rel string, expect ObjectMeta, session string) error + // Mark sets mark, only if the entry's metadata is still expect + // (ErrPrecondition otherwise). + Mark(ctx context.Context, rel string, expect ObjectMeta, mark string) error + // DeleteMarked deletes the entry only if it carries mark + // (ErrPrecondition otherwise); a missing entry succeeds. + DeleteMarked(ctx context.Context, rel string, mark string) error +} + +// maxEnsureRounds bounds EnsureObject's retries when another writer moves +// the entry between its read and its conditional write. +const maxEnsureRounds = 8 + +// EnsureObject is transition 3, the write of one object for a session: an +// absent entry is created with the session as writer; an existing one +// (content-named, so already complete) is reused by a conditional update +// that sets the session and clears any mark, so a cleaning's planned mark +// or delete of it fails its own condition from then on. An entry already +// written by this session and unmarked needs nothing. +func EnsureObject(ctx context.Context, os ObjectStore, rel string, data []byte, session string) error { + if session == "" { + return errors.New("layout: EnsureObject needs a session") + } + for round := 0; round < maxEnsureRounds; round++ { + meta, found, err := os.Stat(ctx, rel) + if err != nil { + return err + } + switch { + case !found: + err = os.Create(ctx, rel, data, session) + if errors.Is(err, ErrExists) { + continue + } + return err + case meta.Session == session && meta.Mark == "": + return nil + default: + err = os.Reuse(ctx, rel, meta, session) + if errors.Is(err, ErrPrecondition) { + continue + } + return err + } + } + return fmt.Errorf("layout: %s kept moving under %d attempts", rel, maxEnsureRounds) +} + +// ownedBySession reports whether rel exists, carries session as its writer +// and is unmarked: an object a commit of that session may name. +func ownedBySession(ctx context.Context, os ObjectStore, rel, session string) (bool, error) { + meta, found, err := os.Stat(ctx, rel) + if err != nil { + return false, err + } + return found && meta.Session == session && meta.Mark == "", nil +} diff --git a/seaweed-block/core/frontend/chunkstore/layout/objects_test.go b/seaweed-block/core/frontend/chunkstore/layout/objects_test.go new file mode 100644 index 0000000000..19bae22a9f --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/layout/objects_test.go @@ -0,0 +1,189 @@ +package layout + +import ( + "context" + "errors" + "path" + "testing" +) + +// memObject is one entry: its bytes and metadata. +type memObject struct { + data []byte + meta ObjectMeta +} + +// memObjects is an ObjectStore of one volume, keyed by full path under +// root, with an optional failing path, a record of every Stat, and a kill +// point counted over its writes (Create, Reuse, Mark, DeleteMarked). +type memObjects struct { + root string + objs map[string]*memObject + fail string + asked []string + writes []string + killAt int + after bool + dead bool + hook func(op, rel string) // runs before a write applies + // afterStat runs after a Stat of rel returned (a writer acting between + // a read and the conditional write that follows it). + afterStat func(rel string) +} + +func newMemObjects(root string) *memObjects { + return &memObjects{root: root, objs: map[string]*memObject{}} +} + +func (m *memObjects) full(rel string) string { return path.Join(m.root, rel) } + +func (m *memObjects) Stat(_ context.Context, rel string) (ObjectMeta, bool, error) { + if m.dead { + return ObjectMeta{}, false, errKilled + } + p := m.full(rel) + m.asked = append(m.asked, p) + if p == m.fail { + return ObjectMeta{}, false, errors.New("filer unavailable") + } + o, ok := m.objs[p] + if m.afterStat != nil { + defer m.afterStat(rel) + } + if !ok { + return ObjectMeta{}, false, nil + } + return o.meta, true, nil +} + +// write runs op's effect under the kill point: before it applies, or +// applied with its reply lost. +func (m *memObjects) write(op, rel string, apply func() error) error { + if m.dead { + return errKilled + } + if m.hook != nil { + m.hook(op, rel) + } + m.writes = append(m.writes, op+" "+rel) + kill := len(m.writes) == m.killAt + if kill && !m.after { + m.dead = true + return errKilled + } + err := apply() + if kill { + m.dead = true + return errKilled + } + return err +} + +func (m *memObjects) Create(_ context.Context, rel string, data []byte, session string) error { + return m.write("create", rel, func() error { + if _, ok := m.objs[m.full(rel)]; ok { + return ErrExists + } + m.objs[m.full(rel)] = &memObject{data: append([]byte(nil), data...), meta: ObjectMeta{Session: session}} + return nil + }) +} + +func (m *memObjects) Reuse(_ context.Context, rel string, expect ObjectMeta, session string) error { + return m.write("reuse", rel, func() error { + o, ok := m.objs[m.full(rel)] + if !ok || o.meta != expect { + return ErrPrecondition + } + o.meta = ObjectMeta{Session: session} + return nil + }) +} + +func (m *memObjects) Mark(_ context.Context, rel string, expect ObjectMeta, mark string) error { + return m.write("mark", rel, func() error { + o, ok := m.objs[m.full(rel)] + if !ok || o.meta != expect { + return ErrPrecondition + } + o.meta.Mark = mark + return nil + }) +} + +func (m *memObjects) DeleteMarked(_ context.Context, rel string, mark string) error { + return m.write("delete", rel, func() error { + o, ok := m.objs[m.full(rel)] + if !ok { + return nil + } + if o.meta.Mark != mark { + return ErrPrecondition + } + delete(m.objs, m.full(rel)) + return nil + }) +} + +// put stores an object directly (fixture setup, no kill point). +func (m *memObjects) put(rel string, data []byte, session string) { + m.objs[m.full(rel)] = &memObject{data: append([]byte(nil), data...), meta: ObjectMeta{Session: session}} +} + +func (m *memObjects) has(rel string) bool { _, ok := m.objs[m.full(rel)]; return ok } + +// data returns every object's bytes by full path (for the reachability +// walk and the reader). +func (m *memObjects) data() map[string][]byte { + out := map[string][]byte{} + for p, o := range m.objs { + out[p] = o.data + } + return out +} + +func (m *memObjects) fetch(_ context.Context, p string) ([]byte, bool, error) { + if m.dead { + return nil, false, errKilled + } + o, ok := m.objs[p] + if !ok { + return nil, false, nil + } + return o.data, true, nil +} + +func (m *memObjects) restart() { m.dead, m.killAt = false, 0 } + +// EnsureObject: an absent object is created by the session; an existing +// one, written by another session or marked, is reused (session set, mark +// cleared); one already the session's and unmarked is left; a racing +// writer between the read and the conditional write is retried. +func TestEnsureObject(t *testing.T) { + ctx := context.Background() + o := newMemObjects("/v") + if err := EnsureObject(ctx, o, "pool/0/a", []byte("x"), "s1"); err != nil || o.objs["/v/pool/0/a"].meta != (ObjectMeta{Session: "s1"}) { + t.Fatalf("create: %v %+v", err, o.objs["/v/pool/0/a"]) + } + writes := len(o.writes) + if err := EnsureObject(ctx, o, "pool/0/a", []byte("x"), "s1"); err != nil || len(o.writes) != writes { + t.Fatalf("own unmarked object rewritten: %v (%d writes)", err, len(o.writes)-writes) + } + o.objs["/v/pool/0/a"].meta = ObjectMeta{Session: "c9", Mark: "c9"} + if err := EnsureObject(ctx, o, "pool/0/a", []byte("x"), "s2"); err != nil || o.objs["/v/pool/0/a"].meta != (ObjectMeta{Session: "s2"}) { + t.Fatalf("reuse of a marked object: %v %+v; want session s2, mark cleared", err, o.objs["/v/pool/0/a"].meta) + } + raced := false + o.hook = func(op, rel string) { + if op == "reuse" && !raced { + raced = true + o.objs["/v/pool/0/a"].meta = ObjectMeta{Session: "other"} + } + } + if err := EnsureObject(ctx, o, "pool/0/a", []byte("x"), "s3"); err != nil || o.objs["/v/pool/0/a"].meta.Session != "s3" { + t.Fatalf("reuse racing another writer: %v %+v; want retried and s3", err, o.objs["/v/pool/0/a"].meta) + } + if err := EnsureObject(ctx, o, "pool/0/b", nil, ""); err == nil { + t.Fatal("EnsureObject without a session accepted") + } +} diff --git a/seaweed-block/core/frontend/chunkstore/layout/remove.go b/seaweed-block/core/frontend/chunkstore/layout/remove.go index b3ce03db59..8f656dfa23 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/remove.go +++ b/seaweed-block/core/frontend/chunkstore/layout/remove.go @@ -7,34 +7,22 @@ import ( "sort" ) -// ErrLeaseLost: the remover's own lease is no longer valid; nothing more -// is removed. -var ErrLeaseLost = errors.New("layout: remover's lease is not valid") - -// LeaseHeld is the remover's half of the time premise: it returns nil only -// while the caller's own lease is valid. Remove calls it immediately before -// every delete. -type LeaseHeld interface { - StillHeld(ctx context.Context) error -} - -// Pool deletes one object of the volume by its path relative to the volume -// root; deleting an absent object succeeds. -type Pool interface { - DeleteObject(ctx context.Context, rel string) error -} - -// RemoveUnreachable is transition 7 for one pool shard: for the holder -// with clean(session) open at HEAD's epoch, every candidate chunk of shard -// that no root in HEAD (current and every snapshot) names in this -// volume's pool is deleted, each delete preceded by a check of the -// remover's own lease. HEAD is read once, after BeginClean: while clean is -// open no commit can add a root, and a claim that voids the cleaning waits -// for this lease to end, which the check before every delete sees. It -// returns the names it deleted, in index order. -func RemoveUnreachable(ctx context.Context, st HeadStore, r *Reader, pool Pool, lease LeaseHeld, me HolderID, session string, shard uint64, candidates []ChunkName) ([]ChunkName, error) { - if lease == nil || pool == nil || r == nil { - return nil, errors.New("layout: removal needs a reader, a pool and a lease check") +// RemoveUnreachable is the cleaning's removal (transition 7') for one pool +// shard: for the holder with its own clean(session) open at HEAD's epoch, +// each candidate chunk that no root in HEAD (current or any snapshot) +// names in this volume's pool is removed in two conditional writes on its +// own entry: MARK, expected the metadata read when the plan was made and +// unmarked, sets the mark to this session; DELETE, expected that mark, +// deletes it. A writer that reuses the object in between (EnsureObject: +// new session, mark cleared) makes the mark or the delete fail its own +// condition, however late it lands; no lease reasoning is needed. A +// candidate already marked by another session, or moved, is left alone. +// Chunks a restore target names stay live here: the source's snapshot +// root names them, and that snapshot stays in HEAD while it has dependents. +// It returns the names it deleted, in index order. +func RemoveUnreachable(ctx context.Context, st HeadStore, r *Reader, os ObjectStore, me HolderID, session string, shard uint64, candidates []ChunkName) ([]ChunkName, error) { + if os == nil || r == nil { + return nil, errors.New("layout: removal needs a reader and an object store") } h, found, err := st.ReadHead(ctx) if err != nil { @@ -60,10 +48,23 @@ func RemoveUnreachable(ctx context.Context, st HeadStore, r *Reader, pool Pool, if Shard(c.Index) != shard || live[c] { continue } - if err := lease.StillHeld(ctx); err != nil { - return removed, fmt.Errorf("%w: %v", ErrLeaseLost, err) + plan, found, err := os.Stat(ctx, c.Path()) + if err != nil { + return removed, err } - if err := pool.DeleteObject(ctx, c.Path()); err != nil { + if !found || plan.Mark != "" { + continue + } + if err := os.Mark(ctx, c.Path(), plan, session); err != nil { + if errors.Is(err, ErrPrecondition) { + continue // reused or marked since the plan + } + return removed, fmt.Errorf("layout: mark %s: %w", c, err) + } + if err := os.DeleteMarked(ctx, c.Path(), session); err != nil { + if errors.Is(err, ErrPrecondition) { + continue // reused since the mark + } return removed, fmt.Errorf("layout: delete %s: %w", c, err) } removed = append(removed, c) diff --git a/seaweed-block/core/frontend/chunkstore/layout/remove_test.go b/seaweed-block/core/frontend/chunkstore/layout/remove_test.go index 31a901b9d3..696950f90f 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/remove_test.go +++ b/seaweed-block/core/frontend/chunkstore/layout/remove_test.go @@ -10,97 +10,53 @@ import ( const removeBase = "/swblock/chunks" // volRoot = removeBase/v1 -// objPool is a volume's objects for removal tests: Fetch reads them, Pool -// deletes them, with an optional kill point counted over deletes. -type objPool struct { - objs map[string][]byte - deletes []string - killAt int - after bool - dead bool -} - -func (o *objPool) fetch(_ context.Context, p string) ([]byte, bool, error) { - if o.dead { - return nil, false, errKilled - } - b, ok := o.objs[p] - return b, ok, nil -} - -func (o *objPool) DeleteObject(_ context.Context, rel string) error { - if o.dead { - return errKilled - } - o.deletes = append(o.deletes, rel) - kill := len(o.deletes) == o.killAt - if kill && !o.after { - o.dead = true - return errKilled - } - delete(o.objs, path.Join(volRoot, rel)) - if kill { - o.dead = true - return errKilled - } - return nil -} - -type fakeHeld struct { - calls int - lostAt int // the n-th call (1-based) and later fail; 0 = never -} - -func (l *fakeHeld) StillHeld(context.Context) error { - l.calls++ - if l.lostAt > 0 && l.calls >= l.lostAt { - return errors.New("lease lapsed") - } - return nil -} - // removeFixture: HEAD clean(c1) at epoch 3; the current root names chunks // 0 and 3, the snapshot "daily" an older image naming chunks 0 and 2 (all // in shard 0); chunks 5 and 7 are in the pool but no root names them, and -// chunk 10001 (shard 1) is unreferenced too. -func removeFixture(t *testing.T) (*objPool, *Head, []ChunkName, []ChunkName) { +// chunk 10001 (shard 1) is unreferenced too. Every object was written by +// session s0. +func removeFixture(t *testing.T) (*memObjects, *Head, []ChunkName, []ChunkName) { t.Helper() - objs := map[string][]byte{} + data := map[string][]byte{} cur := manifest(ref("v1", 0, "a"), ref("v1", 3, "b")) old := manifest(ref("v1", 0, "a"), ref("v1", 2, "c")) - curRoot := writeImage(t, objs, cur, map[uint64][]byte{0: []byte("a"), 3: []byte("b")}) - oldRoot := writeImage(t, objs, old, map[uint64][]byte{0: []byte("a"), 2: []byte("c")}) + curRoot := writeImage(t, data, cur, map[uint64][]byte{0: []byte("a"), 3: []byte("b")}) + oldRoot := writeImage(t, data, old, map[uint64][]byte{0: []byte("a"), 2: []byte("c")}) var orphans []ChunkName for i, d := range map[uint64]string{5: "e", 7: "f", 10001: "g"} { c := NameChunk(i, []byte(d)) - objs[path.Join(volRoot, c.Path())] = []byte(d) + data[path.Join(volRoot, c.Path())] = []byte(d) orphans = append(orphans, c) } + o := newMemObjects(volRoot) + for p, b := range data { + o.objs[p] = &memObject{data: b, meta: ObjectMeta{Session: "s0"}} + } h := &Head{Gen: 7, Epoch: 3, Holder: "srv-a", Activity: Activity{Kind: ActClean, Session: "c1"}, Current: &curRoot, Snapshots: map[string]Snapshot{"daily": {Root: oldRoot}}} live := []ChunkName{cur[0].Chunk, cur[3].Chunk, old[2].Chunk} - return &objPool{objs: objs}, h, live, orphans + return o, h, live, orphans } -func removeShard0(t *testing.T, st HeadStore, o *objPool, l LeaseHeld, session string, cands []ChunkName) ([]ChunkName, error) { +func removeShard0(t *testing.T, st HeadStore, o *memObjects, session string, cands []ChunkName) ([]ChunkName, error) { t.Helper() r, err := NewReader(removeBase, "v1", o.fetch) if err != nil { t.Fatal(err) } - return RemoveUnreachable(context.Background(), st, r, o, l, me, session, 0, cands) + return RemoveUnreachable(context.Background(), st, r, o, me, session, 0, cands) } -func inPool(o *objPool, c ChunkName) bool { _, ok := o.objs[path.Join(volRoot, c.Path())]; return ok } +func inPool(o *memObjects, c ChunkName) bool { return o.has(c.Path()) } -// Only names no root in HEAD reaches are removed: the current root's and -// a snapshot's chunks stay, shard 0's orphans go, the shard-1 orphan is -// not touched by a shard-0 pass; the lease is checked before every delete. +// Only names no root in HEAD reaches are removed, each by a mark then a +// delete conditional on that mark: the current root's and a snapshot's +// chunks stay, shard 0's orphans go, the shard-1 orphan is not touched by +// a shard-0 pass. func TestRemoveUnreachable_RemovesOnlyWhatNoRootNames(t *testing.T) { o, h, live, orphans := removeFixture(t) - l := &fakeHeld{} cands := append(append([]ChunkName(nil), live...), orphans...) - removed, err := removeShard0(t, &memHead{h: h}, o, l, "c1", cands) + removed, err := removeShard0(t, &memHead{h: h}, o, "c1", cands) if err != nil { t.Fatal(err) } @@ -112,10 +68,11 @@ func TestRemoveUnreachable_RemovesOnlyWhatNoRootNames(t *testing.T) { t.Fatalf("reachable chunk %s was removed", c) } } - if l.calls != len(o.deletes) { - t.Fatalf("lease checks %d for %d deletes; want one before each", l.calls, len(o.deletes)) + want := []string{"mark " + removed[0].Path(), "delete " + removed[0].Path(), "mark " + removed[1].Path(), "delete " + removed[1].Path()} + if fmt.Sprint(o.writes) != fmt.Sprint(want) { + t.Fatalf("writes %v; want each removal as a mark then its conditional delete: %v", o.writes, want) } - if err := reachableMissing(h, o.objs); err != nil { + if err := reachableMissing(h, o.data()); err != nil { t.Fatalf("after removal HEAD reaches a missing object: %v", err) } for _, c := range orphans { @@ -139,41 +96,114 @@ func TestRemoveUnreachable_RefusedOutsideItsCleaning(t *testing.T) { } { o, h, _, orphans := removeFixture(t) tc.edit(h) - if _, err := removeShard0(t, &memHead{h: h}, o, &fakeHeld{}, "c1", orphans); !errors.Is(err, tc.want) || len(o.deletes) != 0 { - t.Errorf("%s: %v, %d deletes; want %v and none", name, err, len(o.deletes), tc.want) + if _, err := removeShard0(t, &memHead{h: h}, o, "c1", orphans); !errors.Is(err, tc.want) || len(o.writes) != 0 { + t.Errorf("%s: %v, %d writes; want %v and none", name, err, len(o.writes), tc.want) } } o, _, _, orphans := removeFixture(t) - if _, err := removeShard0(t, &memHead{}, o, &fakeHeld{}, "c1", orphans); !errors.Is(err, ErrHeadAbsent) || len(o.deletes) != 0 { - t.Errorf("absent HEAD: %v, %d deletes", err, len(o.deletes)) + if _, err := removeShard0(t, &memHead{}, o, "c1", orphans); !errors.Is(err, ErrHeadAbsent) || len(o.writes) != 0 { + t.Errorf("absent HEAD: %v, %d writes", err, len(o.writes)) } } -// A lease that lapses mid-pass stops the removal before the next delete. -func TestRemoveUnreachable_StopsWhenTheLeaseLapses(t *testing.T) { +// The race the conditional writes close: a successor (after a claim that +// voided this cleaning) reuses an orphan the old remover planned to remove, +// between the old plan and its mark, or between its mark and its delete, +// and commits a root naming it. The old mark or the old delete fails its +// condition; the object stays. +func TestRemoveUnreachable_AReuseDefeatsALateMarkOrDelete(t *testing.T) { + for _, between := range []string{"mark", "delete"} { + t.Run("reuse before the old "+between, func(t *testing.T) { + o, h, _, orphans := removeFixture(t) + var target ChunkName + for _, c := range orphans { + if c.Index == 5 { + target = c + } + } + o.hook = func(op, rel string) { + if op == between && rel == target.Path() { + o.hook = nil + if err := EnsureObject(context.Background(), o, rel, []byte("e"), "successor"); err != nil { + t.Fatal(err) + } + } + } + if _, err := removeShard0(t, &memHead{h: h}, o, "c1", orphans); err != nil { + t.Fatal(err) + } + if !inPool(o, target) || o.objs[path.Join(volRoot, target.Path())].meta != (ObjectMeta{Session: "successor"}) { + t.Fatalf("chunk %s after a reuse before the old %s: present %t meta %+v; want kept, the successor's", target, between, inPool(o, target), o.objs[path.Join(volRoot, target.Path())]) + } + }) + } +} + +// The window the mark's condition is for: a successor reuses an orphan +// right after the remover read it for its plan. The mark, conditional on +// the metadata of the plan (not a fresh read), fails; the object stays. +func TestRemoveUnreachable_AReuseAfterThePlanDefeatsTheMark(t *testing.T) { o, h, _, orphans := removeFixture(t) - removed, err := removeShard0(t, &memHead{h: h}, o, &fakeHeld{lostAt: 2}, "c1", orphans) - if !errors.Is(err, ErrLeaseLost) || len(removed) != 1 || len(o.deletes) != 1 { - t.Fatalf("lease lapsing before the second delete: removed %v, %v; want one delete then ErrLeaseLost", removed, err) + var target ChunkName + for _, c := range orphans { + if c.Index == 5 { + target = c + } + } + o.afterStat = func(rel string) { + if rel == target.Path() { + o.afterStat = nil + if err := EnsureObject(context.Background(), o, rel, []byte("e"), "successor"); err != nil { + t.Fatal(err) + } + } + } + if _, err := removeShard0(t, &memHead{h: h}, o, "c1", orphans); err != nil { + t.Fatal(err) + } + if !inPool(o, target) { + t.Fatalf("chunk %s reused after the plan was removed", target) + } +} + +// A candidate already marked by another session is left alone. +func TestRemoveUnreachable_LeavesAnotherSessionsMark(t *testing.T) { + o, h, _, orphans := removeFixture(t) + for _, c := range orphans { + if c.Index == 5 { + o.objs[path.Join(volRoot, c.Path())].meta.Mark = "c0" + } + } + removed, err := removeShard0(t, &memHead{h: h}, o, "c1", orphans) + if err != nil || len(removed) != 1 || removed[0].Index != 7 { + t.Fatalf("removed %v %v; want only chunk 7 (5 carries another session's mark)", removed, err) } } // A root or segment HEAD names that cannot be read stops the pass before -// any delete: nothing is removed on a partial view. +// any write: nothing is removed on a partial view. func TestRemoveUnreachable_NothingRemovedOnAPartialView(t *testing.T) { o, h, _, orphans := removeFixture(t) delete(o.objs, path.Join(volRoot, h.Snapshots["daily"].Root.Path())) - if _, err := removeShard0(t, &memHead{h: h}, o, &fakeHeld{}, "c1", orphans); !errors.Is(err, ErrMissing) || len(o.deletes) != 0 { - t.Fatalf("unreadable snapshot root: %v, %d deletes; want ErrMissing and none", err, len(o.deletes)) + if _, err := removeShard0(t, &memHead{h: h}, o, "c1", orphans); !errors.Is(err, ErrMissing) || len(o.writes) != 0 { + t.Fatalf("unreadable snapshot root: %v, %d writes; want ErrMissing and none", err, len(o.writes)) } } +func (v *memVolume) fetch(_ context.Context, p string) ([]byte, bool, error) { + if v.dead { + return nil, false, errKilled + } + b, ok := v.objects[p] + return b, ok, nil +} + // cleaningPass is the whole cleaning operation as the holder runs it after // a (re)start: a cleaning of its own left open is ended first, then // BeginClean, the removal of shard 0, EndClean. -func cleaningPass(st *memVolume, o *objPool, session string, cands []ChunkName) error { +func cleaningPass(v *memVolume, session string, cands []ChunkName) error { ctx := context.Background() - h, found, err := st.ReadHead(ctx) + h, found, err := v.ReadHead(ctx) if err != nil { return err } @@ -181,86 +211,83 @@ func cleaningPass(st *memVolume, o *objPool, session string, cands []ChunkName) return ErrHeadAbsent } if h.Activity.Kind == ActClean && h.heldBy(me) { - if _, err := RunEndClean(ctx, st, me, h.Activity.Session); err != nil { + if _, err := RunEndClean(ctx, v, me, h.Activity.Session); err != nil { return err } } - if _, err := RunBeginClean(ctx, st, me, session); err != nil { + if _, err := RunBeginClean(ctx, v, me, session); err != nil { return err } - r, err := NewReader(removeBase, "v1", o.fetch) + r, err := NewReader(removeBase, "v1", v.fetch) if err != nil { return err } - if _, err := RemoveUnreachable(ctx, st, r, o, &fakeHeld{}, me, session, 0, cands); err != nil { + if _, err := RemoveUnreachable(ctx, v, r, v, me, session, 0, cands); err != nil { return err } - _, err = RunEndClean(ctx, st, me, session) + _, err = RunEndClean(ctx, v, me, session) return err } // Interrupt at every step of the cleaning operation: killed at each of its -// writes (BeginClean, every delete, EndClean), before the write applies -// and after it applied with its reply lost; at no point does HEAD reach a -// missing object, and the restarted holder ends idle with every orphan of -// shard 0 removed and every reachable object present. +// writes (BeginClean, each mark, each conditional delete, EndClean), before +// the write applies and after it applied with its reply lost; at no point +// does HEAD reach a missing object, and the restarted holder (a new +// session) ends idle with every orphan of shard 0 removed and every +// reachable object present. A mark left by the killed session is cleared +// by nothing but a reuse, so a marked orphan stays until then. func TestCleaningPass_InterruptAtEveryStep(t *testing.T) { - fresh := func() (*memVolume, *objPool, []ChunkName, []ChunkName) { + fresh := func() (*memVolume, []ChunkName, []ChunkName) { o, h, live, orphans := removeFixture(t) h.Activity = Activity{Kind: ActIdle} - return &memVolume{head: &memHead{h: h}, objects: o.objs}, o, live, orphans + v := &memVolume{head: &memHead{h: h}, objects: map[string][]byte{}, metas: map[string]ObjectMeta{}} + for p, ob := range o.objs { + v.objects[p] = ob.data + v.metas[p] = ob.meta + } + return v, live, orphans } - v, o, live, orphans := fresh() + v, live, orphans := fresh() cands := append(append([]ChunkName(nil), live...), orphans...) - if err := cleaningPass(v, o, "c1", cands); err != nil { + if err := cleaningPass(v, "c1", cands); err != nil { t.Fatal(err) } - steps := len(v.writes) + len(o.deletes) - if steps != 4 { - t.Fatalf("the cleaning made %d writes; want 4 (BeginClean, two deletes, EndClean)", steps) + steps := append([]string(nil), v.writes...) + if len(steps) != 6 { + t.Fatalf("the cleaning made %d writes: %v; want 6 (BeginClean, mark and delete twice, EndClean)", len(steps), steps) } - // Kill points: HEAD writes are counted by memVolume, deletes by objPool; - // step k is the k-th write of either kind in run order. - order := []string{"head", "delete", "delete", "head"} - for k := range order { + for k := range steps { for _, after := range []bool{false, true} { - t.Run(fmt.Sprintf("step%d %s/after=%t", k+1, order[k], after), func(t *testing.T) { - v, o, live, orphans := fresh() - nth := 0 - for _, kind := range order[:k+1] { - if kind == order[k] { - nth++ - } - } - if order[k] == "head" { - v.killAt, v.after = nth, after - } else { - o.killAt, o.after = nth, after - } - if err := cleaningPass(v, o, "c1", cands); !errors.Is(err, errKilled) { + t.Run(fmt.Sprintf("step%d %s/after=%t", k+1, steps[k], after), func(t *testing.T) { + v, live, orphans := fresh() + v.killAt, v.after = k+1, after + if err := cleaningPass(v, "c1", cands); !errors.Is(err, errKilled) { t.Fatalf("killed run: %v", err) } - if err := reachableMissing(v.head.h, o.objs); err != nil { + if err := reachableMissing(v.head.h, v.objects); err != nil { t.Fatalf("after the kill HEAD reaches a missing object: %v", err) } - v.dead, v.killAt, o.dead, o.killAt = false, 0, false, 0 - if err := cleaningPass(v, o, "c2", cands); err != nil { + v.dead, v.killAt = false, 0 + v.head.restart() + if err := cleaningPass(v, "c2", cands); err != nil { t.Fatalf("re-run: %v", err) } if v.head.h.Activity.Kind != ActIdle { t.Fatalf("activity after the re-run: %+v", v.head.h.Activity) } for _, c := range orphans { - if c.Index != 10001 && inPool(o, c) { - t.Fatalf("orphan %s still present", c) + p := path.Join(volRoot, c.Path()) + _, present := v.objects[p] + if c.Index != 10001 && present && v.meta(p).Mark != "c1" { + t.Fatalf("orphan %s still present and not held by the killed session's mark", c) } } for _, c := range live { - if !inPool(o, c) { + if _, ok := v.objects[path.Join(volRoot, c.Path())]; !ok { t.Fatalf("reachable %s removed", c) } } - if err := reachableMissing(v.head.h, o.objs); err != nil { + if err := reachableMissing(v.head.h, v.objects); err != nil { t.Fatal(err) } }) diff --git a/seaweed-block/core/frontend/chunkstore/layout/session_test.go b/seaweed-block/core/frontend/chunkstore/layout/session_test.go index c8e89926de..129b7e48cb 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/session_test.go +++ b/seaweed-block/core/frontend/chunkstore/layout/session_test.go @@ -13,6 +13,7 @@ import ( type memVolume struct { head *memHead objects map[string][]byte + metas map[string]ObjectMeta writes []string // every write, in order killAt int after bool @@ -54,35 +55,91 @@ func (v *memVolume) UpdateHead(ctx context.Context, gen uint64, next Head) error return nil } -func (v *memVolume) look(_ context.Context, dir, name string) (bool, error) { - if v.dead { - return false, errKilled +// memVolume is also the volume's ObjectStore: every object write counts +// toward the same kill point as HEAD's. An object a fixture stored without +// metadata reads as written by session "s0". +func (v *memVolume) meta(p string) ObjectMeta { + if m, ok := v.metas[p]; ok { + return m } - _, ok := v.objects[path.Join(dir, name)] - return ok, nil + return ObjectMeta{Session: "s0"} } -// put writes an object if absent (a content name that exists is complete, -// so a present one is skipped). -func (v *memVolume) put(rel string, b []byte) error { - p := path.Join(volRoot, rel) +func (v *memVolume) Stat(_ context.Context, rel string) (ObjectMeta, bool, error) { if v.dead { - return errKilled + return ObjectMeta{}, false, errKilled } - if _, ok := v.objects[p]; ok { - return nil + p := path.Join(volRoot, rel) + if _, ok := v.objects[p]; !ok { + return ObjectMeta{}, false, nil } - apply, die, err := v.write("create " + rel) + return v.meta(p), true, nil +} + +// objWrite applies f under the shared kill point. +func (v *memVolume) objWrite(what string, f func() error) error { + apply, die, err := v.write(what) if err != nil { return err } if apply { - v.objects[p] = append([]byte(nil), b...) + err = f() } if die { return errKilled } - return nil + return err +} + +func (v *memVolume) Create(_ context.Context, rel string, data []byte, session string) error { + p := path.Join(volRoot, rel) + return v.objWrite("create "+rel, func() error { + if _, ok := v.objects[p]; ok { + return ErrExists + } + v.objects[p] = append([]byte(nil), data...) + v.metas[p] = ObjectMeta{Session: session} + return nil + }) +} + +func (v *memVolume) Reuse(_ context.Context, rel string, expect ObjectMeta, session string) error { + p := path.Join(volRoot, rel) + return v.objWrite("reuse "+rel, func() error { + if _, ok := v.objects[p]; !ok || v.meta(p) != expect { + return ErrPrecondition + } + v.metas[p] = ObjectMeta{Session: session} + return nil + }) +} + +func (v *memVolume) Mark(_ context.Context, rel string, expect ObjectMeta, mark string) error { + p := path.Join(volRoot, rel) + return v.objWrite("mark "+rel, func() error { + if _, ok := v.objects[p]; !ok || v.meta(p) != expect { + return ErrPrecondition + } + m := v.meta(p) + m.Mark = mark + v.metas[p] = m + return nil + }) +} + +func (v *memVolume) DeleteMarked(_ context.Context, rel string, mark string) error { + p := path.Join(volRoot, rel) + return v.objWrite("delete "+rel, func() error { + if _, ok := v.objects[p]; !ok { + return nil + } + if v.meta(p).Mark != mark { + return ErrPrecondition + } + delete(v.objects, p) + delete(v.metas, p) + return nil + }) } // snapshotSession is the whole snapshot transaction as the holder runs it @@ -115,7 +172,7 @@ func snapshotSession(v *memVolume, session string, data map[uint64][]byte, req C return fmt.Errorf("unexpected current root %s", cur) } for i, r := range newOwn("v1", req.Prev, req.Next) { - if err := v.put(r.Chunk.Path(), data[i]); err != nil { + if err := EnsureObject(ctx, v, r.Chunk.Path(), data[i], session); err != nil { return err } } @@ -124,7 +181,7 @@ func snapshotSession(v *memVolume, session string, data map[uint64][]byte, req C return err } for n, b := range segs { - if err := v.put(n.Path(), b); err != nil { + if err := EnsureObject(ctx, v, n.Path(), b, session); err != nil { return err } } @@ -132,11 +189,11 @@ func snapshotSession(v *memVolume, session string, data map[uint64][]byte, req C if err != nil { return err } - if err := v.put(rn.Path(), rb); err != nil { + if err := EnsureObject(ctx, v, rn.Path(), rb, session); err != nil { return err } req.Session = session - _, err = RunCommit(ctx, v, v.look, volRoot, "v1", me, req) + _, err = RunCommit(ctx, v, v, "v1", me, req) return err } @@ -162,7 +219,7 @@ func sessionFixture(t *testing.T) (func() *memVolume, map[uint64][]byte, CommitR prevRoot := writeImage(t, objs, prev, prevData) h := Head{Gen: 7, Epoch: 3, Holder: "srv-a", Activity: Activity{Kind: ActIdle}, Current: &prevRoot, Position: 40, Snapshots: map[string]Snapshot{"daily": {Root: prevRoot}}} - return &memVolume{head: &memHead{h: &h}, objects: objs} + return &memVolume{head: &memHead{h: &h}, objects: objs, metas: map[string]ObjectMeta{}} } return fresh, data, CommitRequest{Prev: prev, Next: next, Position: 50, Snapshot: "hourly"} } diff --git a/seaweed-block/core/frontend/chunkstore/layout/stale_test.go b/seaweed-block/core/frontend/chunkstore/layout/stale_test.go index 69e0d9a518..dcb7ee16b6 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/stale_test.go +++ b/seaweed-block/core/frontend/chunkstore/layout/stale_test.go @@ -73,9 +73,9 @@ func TestHolderFunctions_RefuseAStaleHolder(t *testing.T) { if err != nil { t.Fatal(err) } - _, err = RemoveUnreachable(context.Background(), &memHead{h: h}, r, o, &fakeHeld{}, c, "c1", 0, orphans) - if !errors.Is(err, ErrNotHolder) || len(o.deletes) != 0 { - t.Errorf("RemoveUnreachable by %s: %v, %d deletes; want ErrNotHolder and none", who, err, len(o.deletes)) + _, err = RemoveUnreachable(context.Background(), &memHead{h: h}, r, o, c, "c1", 0, orphans) + if !errors.Is(err, ErrNotHolder) || len(o.writes) != 0 { + t.Errorf("RemoveUnreachable by %s: %v, %d writes; want ErrNotHolder and none", who, err, len(o.writes)) } } covered := map[string]bool{"RemoveUnreachable": true} diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 5f3c99c8bf..918edde458 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -541,11 +541,11 @@ stateDiagram-v2 | any | idle at epoch e | e above HEAD's epoch (the same epoch and server is a replay); every older holder's lease has ended, checked after the read and before the update | claim.go `Head.Claim`, `RunClaim` (`LeaseWait.OldLeaseEnded`) | `INV-SNAPK-CLAIM-LEASE-001` | | idle | clean(c) | holder at HEAD's epoch; 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; 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 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; the remover's own lease is checked before every delete | remove.go `RemoveUnreachable` (`LeaseHeld.StillHeld`) | `INV-SNAPK-REMOVE-LEASE-001` | +| clean(c) | clean(c), names removed | holder at HEAD's epoch 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-SNAPK-REMOVE-MARK-001` | ## Part B. Invariant ledger -342 rows: 271 ACTIVE, 67 STUB, 4 ARCHIVED; 15 kept from the internal ledger, 327 new. +343 rows: 272 ACTIVE, 67 STUB, 4 ARCHIVED; 15 kept from the internal ledger, 328 new. The "Machine / transition" column refers to Part A. Notes under a table record what a row does not cover and, for kept rows, what was narrowed from the internal ledger. @@ -1086,7 +1086,7 @@ Notes: |---|---|---|---|---|---|---| | `INV-SNAPK-NAME-CANONICAL-001` | A chunk is named by its index and the SHA-256 of its bytes under `pool//`; a segment and a root are named by the SHA-256 of their canonical encoding, and decoding refuses any bytes the encoder would not write, so an object has one encoding and one name. | Content-named layout (no state transition) | `core/frontend/chunkstore/layout` `layout.go` `ParseChunkName`, `DecodeSegment`, `DecodeRoot` | `TestParseChunkName_RoundTripAndRefusals`, `TestDecodeSegment_RefusesNonCanonical`, `TestRoot_Refusals`, `TestBuild_ShardsAndIncrementalReuse` | — (the snapshot kernel model is not in this repository) | ACTIVE | | `INV-SNAPK-HEAD-WRITE-001` | HEAD changes only by one conditional update on its generation through `runTransition`; no path in the package creates a HEAD, and an absent HEAD is refused. | M9 every transition | `core/frontend/chunkstore/layout` `head.go` `runTransition`; `HeadStore` (read and conditional update only) | `TestGuard_WritersTransitionsAndRemovers`, `TestRunBegin` | — (the snapshot kernel model is not in this repository) | ACTIVE | -| `INV-SNAPK-HEAD-GUARD-001` | A source scan refuses any other use of `UpdateHead`, a transition without its closure and interrupt tests, and any store remover other than the lease-gated RemoveUnreachable. | M9 every transition | `core/frontend/chunkstore/layout` (source scan of the package) | `TestGuard_WritersTransitionsAndRemovers`, `TestGuard_Controls` | — (the snapshot kernel model is not in this repository) | ACTIVE | +| `INV-SNAPK-HEAD-GUARD-001` | A source scan refuses any other use of `UpdateHead`, a transition without its closure and interrupt tests, and any store remover other than the mark-gated RemoveUnreachable. | M9 every transition | `core/frontend/chunkstore/layout` (source scan of the package) | `TestGuard_WritersTransitionsAndRemovers`, `TestGuard_Controls` | — (the snapshot kernel model is not in this repository) | ACTIVE | | `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` | `TestAbort_Closure`, `TestAbort_IdleMeansNoActivityRemains`, `TestAbort_RollBackAfterOwnCrash`, `TestRunAbort_InterruptAtEveryStep` | — (the snapshot kernel model is not in this repository) | ACTIVE | @@ -1095,9 +1095,10 @@ Notes: | `INV-SNAPK-CLAIM-LEASE-001` | A claim takes HEAD only at a newer epoch and only after every older holder's lease has ended (checked after the read, before the update); it voids any open session or cleaning, so the old holder's commit, abort and begin are refused. | M9 any → idle (Claim) | `core/frontend/chunkstore/layout` `claim.go` `RunClaim`, `Head.Claim` | `TestClaim_Closure`, `TestRunClaim_WaitsForTheOldLease`, `TestRunClaim_VoidsTheOldSession`, `TestRunClaim_InterruptAtEveryStep` | — (the snapshot kernel model is not in this repository) | ACTIVE | | `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-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-SNAPK-REMOVE-LEASE-001` | A pool name is removed only inside the holder's own cleaning, only when no root in HEAD (current or snapshot) names it, and only after the remover's own lease is checked immediately before that delete. | M9 clean → clean (RemoveUnreachable) | `core/frontend/chunkstore/layout` `remove.go` `RemoveUnreachable` | `TestRemoveUnreachable_RemovesOnlyWhatNoRootNames`, `TestCleaningPass_InterruptAtEveryStep`, `TestHolderFunctions_RefuseAStaleHolder` | — (the snapshot kernel model is not in this repository) | ACTIVE | -| `INV-SNAPK-REMOVE-STOP-001` | A lapsed lease stops a removal pass before the next delete; an unreadable root or segment stops it before any delete; a snapshot open on the volume, another cleaning or idle refuses it. | M9 clean → clean (RemoveUnreachable) | `core/frontend/chunkstore/layout` `remove.go` `RemoveUnreachable` | `TestRemoveUnreachable_StopsWhenTheLeaseLapses`, `TestRemoveUnreachable_NothingRemovedOnAPartialView`, `TestRemoveUnreachable_RefusedOutsideItsCleaning` | — (the snapshot kernel model is not in this repository) | ACTIVE | -| `INV-SNAPK-REMOVE-GUARD-001` | A source scan requires, immediately before every Delete or Remove call in RemoveUnreachable, an if on StillHeld's error that returns: an ignored check, a reused check or an unlisted removal method fails. | M9 clean → clean (RemoveUnreachable) | `core/frontend/chunkstore/layout` (source scan of `remove.go`) | `TestGuard_WritersTransitionsAndRemovers`, `TestGuard_Controls` | — (the snapshot kernel model is not in this repository) | ACTIVE | +| `INV-SNAPK-REMOVE-MARK-001` | A pool name is removed only inside the holder's own cleaning, only when no root in HEAD names it, by a mark conditional on the metadata read for the plan and then a delete conditional on that mark. | M9 clean → clean (RemoveUnreachable) | `core/frontend/chunkstore/layout` `remove.go` `RemoveUnreachable` | `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` `RemoveUnreachable` | `TestRemoveUnreachable_AReuseAfterThePlanDefeatsTheMark`, `TestRemoveUnreachable_AReuseDefeatsALateMarkOrDelete`, `TestRemoveUnreachable_NothingRemovedOnAPartialView`, `TestRemoveUnreachable_RefusedOutsideItsCleaning` | — (the snapshot kernel model is not in this repository) | ACTIVE | +| `INV-SNAPK-REMOVE-GUARD-001` | A source scan requires DeleteMarked as RemoveUnreachable's only removal, each immediately after an if on its Mark's error that leaves: an unconditional delete, an ignored mark, a reused mark or another method fails. | M9 clean → clean (RemoveUnreachable) | `core/frontend/chunkstore/layout` (source scan of `remove.go`) | `TestGuard_WritersTransitionsAndRemovers`, `TestGuard_Controls` | — (the snapshot kernel model is not in this repository) | ACTIVE | +| `INV-SNAPK-REUSE-001` | Writing an object for a session creates it, or reuses an existing one by a conditional update that sets the session and clears any mark; a commit names only objects its session wrote or reused, unmarked. | M9 snap → idle (Upload, Commit) | `core/frontend/chunkstore/layout` `objects.go` `EnsureObject`; `commit.go` `RunCommit` | `TestEnsureObject`, `TestRunCommit_NeedsObjectsOfItsOwnSession`, `TestSnapshotSession_InterruptAtEveryStep` | — (the snapshot kernel model is not in this repository) | ACTIVE | | `INV-SNAPK-STALE-HOLDER-001` | Every transition refuses an older epoch of the same server, the same epoch held by another server, and the same epoch and server with another claim id, in idle, snap and clean; a new transition must be added to the table. | M9 every transition | `core/frontend/chunkstore/layout` `Head.heldBy` and each transition | `TestTransitions_RefuseAStaleHolder` | — (the snapshot kernel model is not in this repository) | ACTIVE | Notes: From 4310a0946983f2a513f50bea567adb87c6b1f704 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 24 Nov 2026 18:23:08 -0800 Subject: [PATCH 12/19] test: the removal's conditional writes on a real filer An integration test (stock weed, chunkstore_integration tag) runs the layout's object writes against a real filer through a filer-backed object store whose entries carry the writer's session and the removal mark as extended attributes: a delete with another mark is refused; a reuse by a successor makes the remover's late mark and late delete both fail their conditions and the object stays; a mark on the current metadata and its own delete remove it; deleting a missing entry succeeds. Co-Authored-By: Claude Opus 5.5 --- .../layout_objects_integration_test.go | 180 ++++++++++++++++++ 1 file changed, 180 insertions(+) create mode 100644 seaweed-block/core/frontend/chunkstore/layout_objects_integration_test.go diff --git a/seaweed-block/core/frontend/chunkstore/layout_objects_integration_test.go b/seaweed-block/core/frontend/chunkstore/layout_objects_integration_test.go new file mode 100644 index 0000000000..928e4d1c78 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/layout_objects_integration_test.go @@ -0,0 +1,180 @@ +//go:build chunkstore_integration + +package chunkstore + +import ( + "context" + "errors" + "path" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" +) + +// filerObjects is a layout.ObjectStore on a real filer: an object is an +// entry under root whose extended attributes carry the writer's session +// and the removal mark ("-" when unmarked); every change of an existing +// entry is a conditional update or delete on those attributes. +type filerObjects struct { + cl *SWFS + root string +} + +const ( + objSessKey = "swb-sess" + objMarkKey = "swb-mark" + unmarked = "-" +) + +func (f filerObjects) loc(rel string) (string, string) { + full := path.Join(f.root, rel) + return path.Dir(full), path.Base(full) +} + +func metaOf(e *filerpb.Entry) layout.ObjectMeta { + m := layout.ObjectMeta{Session: string(e.GetExtended()[objSessKey]), Mark: string(e.GetExtended()[objMarkKey])} + if m.Mark == unmarked { + m.Mark = "" + } + return m +} + +func markValue(m string) []byte { + if m == "" { + return []byte(unmarked) + } + return []byte(m) +} + +func expected(m layout.ObjectMeta) map[string][]byte { + return map[string][]byte{objSessKey: []byte(m.Session), objMarkKey: markValue(m.Mark)} +} + +func layoutErr(err error) error { + if errors.Is(err, ErrPrecondition) { + return layout.ErrPrecondition + } + return err +} + +func (f filerObjects) Stat(ctx context.Context, rel string) (layout.ObjectMeta, bool, error) { + dir, name := f.loc(rel) + e, err := f.cl.LookupEntry(ctx, dir, name) + if errors.Is(err, ErrNotFound) { + return layout.ObjectMeta{}, false, nil + } + if err != nil { + return layout.ObjectMeta{}, false, err + } + return metaOf(e), true, nil +} + +func (f filerObjects) Create(ctx context.Context, rel string, data []byte, session string) error { + dir, name := f.loc(rel) + e := &filerpb.Entry{Name: name, Content: data, Attributes: &filerpb.FuseAttributes{FileMode: 0o644, Mtime: time.Now().Unix()}, + Extended: map[string][]byte{objSessKey: []byte(session), objMarkKey: []byte(unmarked)}} + err := f.cl.CreateEntry(ctx, dir, e, true) + if errors.Is(err, ErrExists) { + return layout.ErrExists + } + return layoutErr(err) +} + +// rewrite updates the entry's attributes to next, conditional on expect. +func (f filerObjects) rewrite(ctx context.Context, rel string, expect, next layout.ObjectMeta) error { + dir, name := f.loc(rel) + e, err := f.cl.LookupEntry(ctx, dir, name) + if errors.Is(err, ErrNotFound) { + return layout.ErrPrecondition + } + if err != nil { + return err + } + e.Extended[objSessKey] = []byte(next.Session) + e.Extended[objMarkKey] = markValue(next.Mark) + return layoutErr(f.cl.UpdateEntry(ctx, dir, e, expected(expect))) +} + +func (f filerObjects) Reuse(ctx context.Context, rel string, expect layout.ObjectMeta, session string) error { + return f.rewrite(ctx, rel, expect, layout.ObjectMeta{Session: session}) +} + +func (f filerObjects) Mark(ctx context.Context, rel string, expect layout.ObjectMeta, mark string) error { + return f.rewrite(ctx, rel, expect, layout.ObjectMeta{Session: expect.Session, Mark: mark}) +} + +func (f filerObjects) DeleteMarked(ctx context.Context, rel string, mark string) error { + dir, name := f.loc(rel) + err := f.cl.DeleteEntry(ctx, dir, name, map[string][]byte{objMarkKey: markValue(mark)}) + if errors.Is(err, ErrPrecondition) { + if _, found, serr := f.Stat(ctx, rel); serr == nil && !found { + return nil // a missing entry succeeds + } + return layout.ErrPrecondition + } + return err +} + +// On a real filer (stock weed): the removal's two conditional writes and +// the upload's reuse write behave as the layout needs. A delete whose +// mark does not match is refused; a reuse (another session, mark cleared) +// makes the remover's late mark and late delete both fail their +// conditions and the object stays; a mark on the current metadata and its +// own delete remove it. +func TestIntegration_ObjectMarkAndConditionalDelete(t *testing.T) { + c := startWeed(t) + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute) + defer cancel() + const root = "/swblock/objs/v1" + f := filerObjects{cl: c.client(t, root+"/"), root: root} + rel := layout.NameChunk(5, []byte("orphan")).Path() + + if err := layout.EnsureObject(ctx, f, rel, []byte("orphan"), "s0"); err != nil { + t.Fatal(err) + } + plan, found, err := f.Stat(ctx, rel) + if err != nil || !found || plan != (layout.ObjectMeta{Session: "s0"}) { + t.Fatalf("created object: %+v %t %v", plan, found, err) + } + if err := f.Mark(ctx, rel, plan, "c1"); err != nil { + t.Fatalf("mark on the plan's metadata: %v", err) + } + if err := f.DeleteMarked(ctx, rel, "c9"); !errors.Is(err, layout.ErrPrecondition) { + t.Fatalf("delete with another mark: %v; want refused by the filer", err) + } + if _, found, _ := f.Stat(ctx, rel); !found { + t.Fatal("a refused conditional delete removed the entry") + } + // A successor reuses the object: session set, mark cleared. + if err := layout.EnsureObject(ctx, f, rel, []byte("orphan"), "successor"); err != nil { + t.Fatal(err) + } + if m, _, _ := f.Stat(ctx, rel); m != (layout.ObjectMeta{Session: "successor"}) { + t.Fatalf("after the reuse: %+v; want session successor, unmarked", m) + } + if err := f.DeleteMarked(ctx, rel, "c1"); !errors.Is(err, layout.ErrPrecondition) { + t.Fatalf("the old remover's late delete: %v; want refused by the filer", err) + } + if err := f.Mark(ctx, rel, plan, "c1"); !errors.Is(err, layout.ErrPrecondition) { + t.Fatalf("the old remover's late mark on its plan's metadata: %v; want refused by the filer", err) + } + if _, found, _ := f.Stat(ctx, rel); !found { + t.Fatal("the reused object was removed") + } + // A remover planning on the current metadata removes it. + now, _, _ := f.Stat(ctx, rel) + if err := f.Mark(ctx, rel, now, "c2"); err != nil { + t.Fatal(err) + } + if err := f.DeleteMarked(ctx, rel, "c2"); err != nil { + t.Fatalf("delete with its own mark: %v", err) + } + if _, found, _ := f.Stat(ctx, rel); found { + t.Fatal("the marked object was not deleted") + } + if err := f.DeleteMarked(ctx, rel, "c2"); err != nil { + t.Fatalf("delete of a missing entry: %v; want success", err) + } +} From b95486c1242f517e6c94f2a48894b86c0b5e7c34 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 24 Nov 2026 18:27:12 -0800 Subject: [PATCH 13/19] layout: the removal reads its tags before its HEAD view Read lazily after HEAD, a candidate's tag could already be a successor's: a stale remover that paused after reading HEAD would then mark and delete a chunk the successor had reused and committed. The removal now reads every candidate's tag first, only then reads HEAD and requires it is still this holder's with its own cleaning, and marks against the earlier tags: a successor that acted before the HEAD read leaves a HEAD that is not this holder's (nothing is written); one that acted after rewrote the tag (the mark fails). Tests cover both, and the old order fails the first. Co-Authored-By: Claude Opus 5.5 --- .../frontend/chunkstore/layout/guard_test.go | 2 +- .../frontend/chunkstore/layout/head_test.go | 8 +++ .../core/frontend/chunkstore/layout/remove.go | 62 ++++++++++++------- .../frontend/chunkstore/layout/remove_test.go | 53 ++++++++++++++++ seaweed-block/docs/design/invariants.md | 4 +- 5 files changed, 102 insertions(+), 27 deletions(-) diff --git a/seaweed-block/core/frontend/chunkstore/layout/guard_test.go b/seaweed-block/core/frontend/chunkstore/layout/guard_test.go index ca861ff2be..7789a3c09b 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/guard_test.go +++ b/seaweed-block/core/frontend/chunkstore/layout/guard_test.go @@ -375,7 +375,7 @@ func removeVariant(t *testing.T, mode string) string { t.Fatal(err) } src := strings.ReplaceAll(string(b), "\r\n", "\n") - gate := "if err := os.Mark(ctx, c.Path(), plan, session); err != nil {" + gate := "if err := os.Mark(ctx, c.Path(), tag, session); err != nil {" if !strings.Contains(src, gate) { t.Fatal("remove.go mark gate not found") } diff --git a/seaweed-block/core/frontend/chunkstore/layout/head_test.go b/seaweed-block/core/frontend/chunkstore/layout/head_test.go index a6100d3f0c..8f9653ca0d 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/head_test.go +++ b/seaweed-block/core/frontend/chunkstore/layout/head_test.go @@ -120,6 +120,9 @@ type memHead struct { after bool dead bool hook func() // runs between a read and the next update + // afterRead runs once after a ReadHead returned (another actor acting + // right after this reader's view of HEAD). + afterRead func() } var errKilled = errors.New("process killed") @@ -135,6 +138,11 @@ func (m *memHead) ReadHead(context.Context) (Head, bool, error) { } b, _ := m.h.Encode() h, err := DecodeHead(b, m.h.Gen) + if m.afterRead != nil { + f := m.afterRead + m.afterRead = nil + defer func() { m.mu.Unlock(); f(); m.mu.Lock() }() + } return h, true, err } diff --git a/seaweed-block/core/frontend/chunkstore/layout/remove.go b/seaweed-block/core/frontend/chunkstore/layout/remove.go index 8f656dfa23..998e3d4d42 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/remove.go +++ b/seaweed-block/core/frontend/chunkstore/layout/remove.go @@ -8,22 +8,44 @@ import ( ) // RemoveUnreachable is the cleaning's removal (transition 7') for one pool -// shard: for the holder with its own clean(session) open at HEAD's epoch, -// each candidate chunk that no root in HEAD (current or any snapshot) -// names in this volume's pool is removed in two conditional writes on its -// own entry: MARK, expected the metadata read when the plan was made and -// unmarked, sets the mark to this session; DELETE, expected that mark, -// deletes it. A writer that reuses the object in between (EnsureObject: -// new session, mark cleared) makes the mark or the delete fail its own -// condition, however late it lands; no lease reasoning is needed. A -// candidate already marked by another session, or moved, is left alone. -// Chunks a restore target names stay live here: the source's snapshot -// root names them, and that snapshot stays in HEAD while it has dependents. -// It returns the names it deleted, in index order. +// shard, for the holder with its own clean(session) open at HEAD's epoch, +// in an order that makes its plan atomic with its HEAD view +// (read-validate-write): +// 1. read the tag (writer session, mark) of every candidate; +// 2. only then read HEAD, require it is still this holder's with +// clean(session), and compute what any root in it (current or +// snapshot) names in this volume's pool; +// 3. MARK each candidate no root names, expected the tag from step 1; +// 4. DELETE it, expected that mark. +// +// If a successor acted before step 2, HEAD is no longer this holder's and +// nothing is written. If it acted after, every tag from step 1 predates +// its writes: a session that names a chunk no root named at its Begin +// writes that chunk's entry (create, or reuse with a new tag), so the MARK +// or the DELETE fails its condition, however late it lands. No lease +// reasoning is needed. A candidate marked by another session is left +// alone. Chunks a restore target names stay live: the source's snapshot +// root names them while it has dependents. It returns the names it +// deleted, in index order. func RemoveUnreachable(ctx context.Context, st HeadStore, r *Reader, os ObjectStore, me HolderID, session string, shard uint64, candidates []ChunkName) ([]ChunkName, error) { if os == nil || r == nil { return nil, errors.New("layout: removal needs a reader and an object store") } + sorted := append([]ChunkName(nil), candidates...) + sort.Slice(sorted, func(a, b int) bool { return sorted[a].Index < sorted[b].Index }) + plan := map[ChunkName]ObjectMeta{} + for _, c := range sorted { + if Shard(c.Index) != shard { + continue + } + meta, found, err := os.Stat(ctx, c.Path()) + if err != nil { + return nil, err + } + if found && meta.Mark == "" { + plan[c] = meta + } + } h, found, err := st.ReadHead(ctx) if err != nil { return nil, err @@ -41,23 +63,15 @@ func RemoveUnreachable(ctx context.Context, st HeadStore, r *Reader, os ObjectSt if err != nil { return nil, err } - sorted := append([]ChunkName(nil), candidates...) - sort.Slice(sorted, func(a, b int) bool { return sorted[a].Index < sorted[b].Index }) var removed []ChunkName for _, c := range sorted { - if Shard(c.Index) != shard || live[c] { + tag, planned := plan[c] + if !planned || live[c] { continue } - plan, found, err := os.Stat(ctx, c.Path()) - if err != nil { - return removed, err - } - if !found || plan.Mark != "" { - continue - } - if err := os.Mark(ctx, c.Path(), plan, session); err != nil { + if err := os.Mark(ctx, c.Path(), tag, session); err != nil { if errors.Is(err, ErrPrecondition) { - continue // reused or marked since the plan + continue // written since the plan } return removed, fmt.Errorf("layout: mark %s: %w", c, err) } diff --git a/seaweed-block/core/frontend/chunkstore/layout/remove_test.go b/seaweed-block/core/frontend/chunkstore/layout/remove_test.go index 696950f90f..645e2391c1 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/remove_test.go +++ b/seaweed-block/core/frontend/chunkstore/layout/remove_test.go @@ -166,6 +166,59 @@ func TestRemoveUnreachable_AReuseAfterThePlanDefeatsTheMark(t *testing.T) { } } +// The stale remover's whole window: right after it reads HEAD, its lease +// ends and a successor claims, reuses an orphan (EnsureObject) and commits +// a root naming it. The remover's tags were read before its HEAD view, so +// the reuse changed the tag and its mark fails; had it read the tags after +// HEAD, it would mark and delete a chunk the successor's root names. +func TestRemoveUnreachable_ASuccessorAfterTheHeadViewDefeatsTheMark(t *testing.T) { + o, h, _, orphans := removeFixture(t) + var target ChunkName + for _, c := range orphans { + if c.Index == 5 { + target = c + } + } + st := &memHead{h: h} + st.afterRead = func() { + if err := EnsureObject(context.Background(), o, target.Path(), []byte("e"), "successor"); err != nil { + t.Fatal(err) + } + // The successor's commit names the reused chunk; the old holder's + // HEAD view (already taken) still shows its own cleaning. + next := manifest(Ref{Owner: "v1", Chunk: target}) + rn := writeImage(t, map[string][]byte{}, next, map[uint64][]byte{5: []byte("e")}) + root, segs, _ := Build(next) + _ = root + for n, b := range segs { + o.put(n.Path(), b, "successor") + } + _, rb, _ := NameRoot(root) + o.put(rn.Path(), rb, "successor") + h.Epoch, h.Holder, h.Activity, h.Current = 4, "srv-b", Activity{Kind: ActIdle}, &rn + } + if _, err := removeShard0(t, st, o, "c1", orphans); err != nil { + t.Fatal(err) + } + if !inPool(o, target) { + t.Fatalf("chunk %s, reused and committed by the successor after the remover's HEAD view, was removed", target) + } + if err := reachableMissing(h, o.data()); err != nil { + t.Fatalf("the successor's HEAD reaches a missing object: %v", err) + } +} + +// A successor that acts before the remover's HEAD view (the remover paused +// right after BeginClean) leaves a HEAD that is no longer the remover's: +// the pass stops before any write. +func TestRemoveUnreachable_ASuccessorBeforeTheHeadViewStopsThePass(t *testing.T) { + o, h, _, orphans := removeFixture(t) + h.Epoch, h.Holder, h.Activity = 4, "srv-b", Activity{Kind: ActIdle} + if _, err := removeShard0(t, &memHead{h: h}, o, "c1", orphans); !errors.Is(err, ErrNotHolder) || len(o.writes) != 0 { + t.Fatalf("remover after a claim: %v, %d writes; want ErrNotHolder and none", err, len(o.writes)) + } +} + // A candidate already marked by another session is left alone. func TestRemoveUnreachable_LeavesAnotherSessionsMark(t *testing.T) { o, h, _, orphans := removeFixture(t) diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 918edde458..bb1d739f40 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -1095,8 +1095,8 @@ Notes: | `INV-SNAPK-CLAIM-LEASE-001` | A claim takes HEAD only at a newer epoch and only after every older holder's lease has ended (checked after the read, before the update); it voids any open session or cleaning, so the old holder's commit, abort and begin are refused. | M9 any → idle (Claim) | `core/frontend/chunkstore/layout` `claim.go` `RunClaim`, `Head.Claim` | `TestClaim_Closure`, `TestRunClaim_WaitsForTheOldLease`, `TestRunClaim_VoidsTheOldSession`, `TestRunClaim_InterruptAtEveryStep` | — (the snapshot kernel model is not in this repository) | ACTIVE | | `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-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-SNAPK-REMOVE-MARK-001` | A pool name is removed only inside the holder's own cleaning, only when no root in HEAD names it, by a mark conditional on the metadata read for the plan and then a delete conditional on that mark. | M9 clean → clean (RemoveUnreachable) | `core/frontend/chunkstore/layout` `remove.go` `RemoveUnreachable` | `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` `RemoveUnreachable` | `TestRemoveUnreachable_AReuseAfterThePlanDefeatsTheMark`, `TestRemoveUnreachable_AReuseDefeatsALateMarkOrDelete`, `TestRemoveUnreachable_NothingRemovedOnAPartialView`, `TestRemoveUnreachable_RefusedOutsideItsCleaning` | — (the snapshot kernel model is not in this repository) | ACTIVE | +| `INV-SNAPK-REMOVE-MARK-001` | A pool name 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` `RemoveUnreachable` | `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` `RemoveUnreachable` | `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-GUARD-001` | A source scan requires DeleteMarked as RemoveUnreachable's only removal, each immediately after an if on its Mark's error that leaves: an unconditional delete, an ignored mark, a reused mark or another method fails. | M9 clean → clean (RemoveUnreachable) | `core/frontend/chunkstore/layout` (source scan of `remove.go`) | `TestGuard_WritersTransitionsAndRemovers`, `TestGuard_Controls` | — (the snapshot kernel model is not in this repository) | ACTIVE | | `INV-SNAPK-REUSE-001` | Writing an object for a session creates it, or reuses an existing one by a conditional update that sets the session and clears any mark; a commit names only objects its session wrote or reused, unmarked. | M9 snap → idle (Upload, Commit) | `core/frontend/chunkstore/layout` `objects.go` `EnsureObject`; `commit.go` `RunCommit` | `TestEnsureObject`, `TestRunCommit_NeedsObjectsOfItsOwnSession`, `TestSnapshotSession_InterruptAtEveryStep` | — (the snapshot kernel model is not in this repository) | ACTIVE | | `INV-SNAPK-STALE-HOLDER-001` | Every transition refuses an older epoch of the same server, the same epoch held by another server, and the same epoch and server with another claim id, in idle, snap and clean; a new transition must be added to the table. | M9 every transition | `core/frontend/chunkstore/layout` `Head.heldBy` and each transition | `TestTransitions_RefuseAStaleHolder` | — (the snapshot kernel model is not in this repository) | ACTIVE | From 0ecfbd330daf2357ed1fa346b00e6f3b8b3da724 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 24 Nov 2026 18:30:57 -0800 Subject: [PATCH 14/19] storage: export a read-only decode of one v3 WAL record DecodeWALRecordV3 wraps the decoder recovery uses (same geometry, size and CRC checks and errors) and returns LSN, type, LBA, length and the whole record size; WALRecordHeaderBytesV3 is the header the codec adds. For read-only tools that analyse crash images; recovery does not use it. Co-Authored-By: Claude Opus 5.5 --- seaweed-block/core/storage/wal_record_v3.go | 34 +++++++++++ .../core/storage/wal_record_v3_test.go | 59 +++++++++++++++++++ 2 files changed, 93 insertions(+) create mode 100644 seaweed-block/core/storage/wal_record_v3.go create mode 100644 seaweed-block/core/storage/wal_record_v3_test.go diff --git a/seaweed-block/core/storage/wal_record_v3.go b/seaweed-block/core/storage/wal_record_v3.go new file mode 100644 index 0000000000..21a66b49c1 --- /dev/null +++ b/seaweed-block/core/storage/wal_record_v3.go @@ -0,0 +1,34 @@ +package storage + +// WALRecordV3 is the checked header of one impl-3 WAL record, for read-only +// tools (crash-image analysis, diagnostics). Recovery does not use it. +type WALRecordV3 struct { + LSN uint64 + Type uint8 + LBA uint64 + Length uint32 // the payload bytes the record covers + Size uint64 // the whole record, header included + Padding bool +} + +// WALRecordHeaderBytesV3 is what a record adds to its payload (prefix, CRC32C +// and EntrySize): the same constant the encoder and decoder use. +const WALRecordHeaderBytesV3 = walEntryHeaderSizeV3 + +// DecodeWALRecordV3 decodes the record at the start of buf with the decoder +// recovery uses: the same geometry, size and CRC checks and errors. It adds +// no parsing of its own; nonce, cursor and lap admission stay the scanner's. +func DecodeWALRecordV3(buf []byte, blockSize uint32, numBlocks uint64) (WALRecordV3, error) { + e, err := decodeWALEntryV3(buf, blockSize, numBlocks) + if err != nil { + return WALRecordV3{}, err + } + return WALRecordV3{ + LSN: e.LSN, + Type: e.Type, + LBA: e.LBA, + Length: e.Length, + Size: uint64(walEntryHeaderSizeV3 + len(e.Data)), + Padding: e.Type == walEntryPadding, + }, nil +} diff --git a/seaweed-block/core/storage/wal_record_v3_test.go b/seaweed-block/core/storage/wal_record_v3_test.go new file mode 100644 index 0000000000..a81efe2301 --- /dev/null +++ b/seaweed-block/core/storage/wal_record_v3_test.go @@ -0,0 +1,59 @@ +package storage + +import ( + "bytes" + "errors" + "testing" +) + +// DecodeWALRecordV3 must agree with the internal decoder field for field on +// valid records and fail exactly when it fails, with the same error. +func TestDecodeWALRecordV3AgreesWithTheInternalDecoder(t *testing.T) { + var nonce [16]byte + copy(nonce[:], "0123456789abcdef") + write := walEntryV3{LSN: 21, Type: walEntryWrite, LBA: 3, Length: v3TestBlockSize, DurableLSN: 20, + LogicalStart: 4096, Nonce: nonce, Data: bytes.Repeat([]byte{0xA5}, int(v3TestBlockSize))} + pad := walEntryV3{Type: walEntryPadding, Nonce: nonce, Length: 512, Data: make([]byte, 512)} + for name, e := range map[string]walEntryV3{"write": write, "barrier": v3TestBarrier(), "padding": pad} { + t.Run(name, func(t *testing.T) { + b, err := encodeWALEntryV3(e, v3TestBlockSize, v3TestNumBlocks) + if err != nil { + t.Fatalf("fixture not encodable: %v", err) + } + in, ierr := decodeWALEntryV3(b, v3TestBlockSize, v3TestNumBlocks) + out, oerr := DecodeWALRecordV3(b, v3TestBlockSize, v3TestNumBlocks) + if ierr != nil || oerr != nil { + t.Fatalf("valid record: internal %v, exported %v", ierr, oerr) + } + want := WALRecordV3{LSN: in.LSN, Type: in.Type, LBA: in.LBA, Length: in.Length, + Size: uint64(len(b)), Padding: in.Type == walEntryPadding} + if out != want { + t.Fatalf("exported %+v, internal decode gives %+v", out, want) + } + }) + } + b, err := encodeWALEntryV3(write, v3TestBlockSize, v3TestNumBlocks) + if err != nil { + t.Fatal(err) + } + if got := uint64(len(b)); got != uint64(WALRecordHeaderBytesV3)+uint64(v3TestBlockSize) { + t.Fatalf("a %d-byte write's record is %d bytes, want header %d + payload", v3TestBlockSize, got, WALRecordHeaderBytesV3) + } + // every single-byte corruption and every truncation: both decoders refuse, with the same error + for i := 0; i < len(b); i++ { + c := append([]byte(nil), b...) + c[i] ^= 0x40 + _, ierr := decodeWALEntryV3(c, v3TestBlockSize, v3TestNumBlocks) + _, oerr := DecodeWALRecordV3(c, v3TestBlockSize, v3TestNumBlocks) + if (ierr == nil) != (oerr == nil) || ierr != nil && !errors.Is(oerr, ierr) && oerr.Error() != ierr.Error() { + t.Fatalf("byte %d corrupted: internal %v, exported %v", i, ierr, oerr) + } + } + for n := 0; n < len(b); n += 97 { + _, ierr := decodeWALEntryV3(b[:n], v3TestBlockSize, v3TestNumBlocks) + _, oerr := DecodeWALRecordV3(b[:n], v3TestBlockSize, v3TestNumBlocks) + if ierr == nil || oerr == nil || oerr.Error() != ierr.Error() { + t.Fatalf("truncated to %d: internal %v, exported %v", n, ierr, oerr) + } + } +} From 5046436c8bc3ef15d5efe14b191cb3eb0b1c7f9a Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 24 Nov 2026 18:35:38 -0800 Subject: [PATCH 15/19] test: the systemd startup gate asserts serve-after-barrier in process (no fence exit) and a moved source's exit 78 Fixes #572. Co-Authored-By: Claude Opus 5.5 --- .../startup_systemd_integration_test.go | 90 +++++++++++++++---- 1 file changed, 74 insertions(+), 16 deletions(-) diff --git a/seaweed-block/cmd/blockvolume/startup_systemd_integration_test.go b/seaweed-block/cmd/blockvolume/startup_systemd_integration_test.go index 95263837fa..7263493f5f 100644 --- a/seaweed-block/cmd/blockvolume/startup_systemd_integration_test.go +++ b/seaweed-block/cmd/blockvolume/startup_systemd_integration_test.go @@ -161,31 +161,41 @@ func TestSystemdExpiredStartupExits75ThenRegrantServes(t *testing.T) { if firstPID == "0" { t.Fatal("returning unit did not start a real process") } - // Existing assignment wait is30s. This is an outer failed-run guard, not - // an injected success delay or a replacement product deadline. - waitGAP1(t, "GAP-1: first startup never exited75; stayed alive non-serving", 45*time.Second, func() bool { - s := gap1Unit(t, unit) + // The returning process waits in process for the master's barrier and + // serves after it, with no fence exit and no restart (the startup wait, + // #535): first it reports the barrier as its MasterWait, never serving. + var barrierMs int64 + waitGAP1(t, "returning unit never reported the master's barrier", 30*time.Second, func() bool { if gap1Operational(t, statusAddr, volume) { - t.Fatal("fixture returned before the expired-grant barrier: cannot count this as a startup-timeout red") + t.Fatal("the returning unit served before reporting a barrier wait: an expired lease was re-granted without the barrier") } - if s["ExecMainStatus"] == "75" { + if s := gap1Unit(t, unit); s["MainPID"] != firstPID { + t.Fatalf("the returning unit exited while waiting for the barrier: %+v", s) + } + if w := gap1MasterWait(t, statusAddr, volume); w.Reason == "barrier" && w.UntilMs > 0 { + barrierMs = w.UntilMs + t.Logf("captured master wait: reason=%s until=%d", w.Reason, w.UntilMs) return true } - if s["MainPID"] != "0" && s["MainPID"] != firstPID { - t.Fatalf("restart without captured75: %+v", s) - } return false }) - waitGAP1(t, "systemd did not restart/regrant/attach", 100*time.Second, func() bool { + // Then the same process serves: not before the barrier, and within the + // startup wait's bound (barrier + 30 s; the outer guard adds slack). + waitGAP1(t, "the returning unit never served after the barrier", 75*time.Second, func() bool { s := gap1Unit(t, unit) - n, e := strconv.Atoi(s["NRestarts"]) - if e != nil { - t.Fatalf("invalid captured NRestarts: %+v", s) + if s["MainPID"] != firstPID || s["NRestarts"] != "0" { + t.Fatalf("the returning unit restarted (a fence exit) instead of serving in process: %+v", s) } - if n > 2 { - t.Fatalf("barrier retry exceeded three total launches: %+v", s) + if !gap1Operational(t, statusAddr, volume) { + return false } - return n >= 1 && s["MainPID"] != "0" && s["MainPID"] != firstPID && gap1Operational(t, statusAddr, volume) + if now := time.Now().UnixMilli(); now < barrierMs { + t.Fatalf("served at %d, before the master's barrier %d", now, barrierMs) + } + if late := time.Now().UnixMilli() - barrierMs; late > 30_000 { + t.Fatalf("served %d ms after the barrier: past the startup wait's 30 s bound", late) + } + return true }) after, err := gap1ReadHead(t, remote) if err != nil || after.Gen <= before.Gen || after.Holder != before.Holder || after.Epoch != before.Epoch { @@ -215,6 +225,54 @@ func TestSystemdExpiredStartupExits75ThenRegrantServes(t *testing.T) { } gap1PlannedStopDoesNotRestart(t, ws, unit, statusAddr, volume, after.Epoch, "r1", s["NRestarts"], s["InvocationID"]) gap1PrestartedTargetServesAfterMove(t, fixture, ws, remote, target, stem, filepath.Join(bin, "blockvolume"), args, root, volume, want) + gap1MovedSourceExits78(t, fixture, filepath.Join(bin, "blockvolume"), args, stem, statusAddr, volume) +} + +// gap1MovedSourceExits78 is the negative case of the in-process wait: after +// the volume moved to another host, the old source started again learns the +// move and exits 78 (final), which the unit's RestartPreventExitStatus keeps +// from restarting; it never serves. +func gap1MovedSourceExits78(t *testing.T, fixture *gap1Fixture, exe string, args []string, stem, statusAddr, volume string) { + t.Helper() + unit := stem + "-moved-source" + fixture.start(t, unit, true, exe, args...) + waitGAP1(t, "the moved-away source never exited 78", 90*time.Second, func() bool { + if gap1Operational(t, statusAddr, volume) { + t.Fatal("the moved-away source served") + } + s := gap1Unit(t, unit) + if s["ExecMainStatus"] == "75" { + t.Fatalf("the moved-away source exited 75 (retry) instead of 78 (moved): %+v", s) + } + return s["ExecMainStatus"] == "78" && s["MainPID"] == "0" + }) + time.Sleep(7 * time.Second) // past RestartSec: a restart would have happened + if s := gap1Unit(t, unit); s["NRestarts"] != "0" || s["MainPID"] != "0" { + t.Fatalf("systemd restarted the moved-away source after its exit 78: %+v", s) + } +} + +// gap1MasterWait reads the volume's /status MasterWait (the startup wait's +// reason and the master's barrier time), zero when absent. +func gap1MasterWait(t *testing.T, addr, volume string) struct { + Reason string + UntilMs int64 +} { + t.Helper() + var out struct { + MasterWait *struct { + Reason string + UntilMs int64 + } + } + code, body, err := gap1StatusAt(addr, volume, "/status") + if err != nil || code != http.StatusOK || json.Unmarshal(body, &out) != nil || out.MasterWait == nil { + return struct { + Reason string + UntilMs int64 + }{} + } + return *out.MasterWait } // Roots are deliberately independent of testing.TempDir: unknown unit cleanup From 0666f6ad185f1a47eb7ecce9bdbbfd31cd6abd74 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 24 Nov 2026 18:41:39 -0800 Subject: [PATCH 16/19] test: the moved-source case stops the new holder first (the simulated hosts share one volume lock directory) Co-Authored-By: Claude Opus 5.5 --- .../blockvolume/startup_systemd_integration_test.go | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/seaweed-block/cmd/blockvolume/startup_systemd_integration_test.go b/seaweed-block/cmd/blockvolume/startup_systemd_integration_test.go index 7263493f5f..c42db24829 100644 --- a/seaweed-block/cmd/blockvolume/startup_systemd_integration_test.go +++ b/seaweed-block/cmd/blockvolume/startup_systemd_integration_test.go @@ -229,11 +229,17 @@ func TestSystemdExpiredStartupExits75ThenRegrantServes(t *testing.T) { } // gap1MovedSourceExits78 is the negative case of the in-process wait: after -// the volume moved to another host, the old source started again learns the -// move and exits 78 (final), which the unit's RestartPreventExitStatus keeps -// from restarting; it never serves. +// the volume moved to another host (and the new holder stopped), the old +// source started again learns the move and exits 78 (final), which the unit's +// RestartPreventExitStatus keeps from restarting; it never serves. func gap1MovedSourceExits78(t *testing.T, fixture *gap1Fixture, exe string, args []string, stem, statusAddr, volume string) { t.Helper() + // The simulated hosts share this kernel's per-host volume lock directory: + // stop the new holder (the prestarted target) so the old source can open + // its root at all; on real separate hosts the two never share a lock. + target := stem + "-prestarted-target" + gap1Systemctl(t, "stop", target) + waitGAP1(t, "the new holder did not stop", 30*time.Second, func() bool { return gap1Unit(t, target)["MainPID"] == "0" }) unit := stem + "-moved-source" fixture.start(t, unit, true, exe, args...) waitGAP1(t, "the moved-away source never exited 78", 90*time.Second, func() bool { From 06641576457767c964f9a4e9128b5e5b41f0991e Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 24 Nov 2026 18:45:01 -0800 Subject: [PATCH 17/19] test: the moved-away source never serves and exits only 75 (no lineage of its own) Co-Authored-By: Claude Opus 5.5 --- .../startup_systemd_integration_test.go | 33 +++++++++++-------- 1 file changed, 20 insertions(+), 13 deletions(-) diff --git a/seaweed-block/cmd/blockvolume/startup_systemd_integration_test.go b/seaweed-block/cmd/blockvolume/startup_systemd_integration_test.go index c42db24829..d968c5289e 100644 --- a/seaweed-block/cmd/blockvolume/startup_systemd_integration_test.go +++ b/seaweed-block/cmd/blockvolume/startup_systemd_integration_test.go @@ -225,14 +225,17 @@ func TestSystemdExpiredStartupExits75ThenRegrantServes(t *testing.T) { } gap1PlannedStopDoesNotRestart(t, ws, unit, statusAddr, volume, after.Epoch, "r1", s["NRestarts"], s["InvocationID"]) gap1PrestartedTargetServesAfterMove(t, fixture, ws, remote, target, stem, filepath.Join(bin, "blockvolume"), args, root, volume, want) - gap1MovedSourceExits78(t, fixture, filepath.Join(bin, "blockvolume"), args, stem, statusAddr, volume) + gap1MovedSourceNeverServes(t, fixture, filepath.Join(bin, "blockvolume"), args, stem, statusAddr, volume) } -// gap1MovedSourceExits78 is the negative case of the in-process wait: after -// the volume moved to another host (and the new holder stopped), the old -// source started again learns the move and exits 78 (final), which the unit's -// RestartPreventExitStatus keeps from restarting; it never serves. -func gap1MovedSourceExits78(t *testing.T, fixture *gap1Fixture, exe string, args []string, stem, statusAddr, volume string) { +// gap1MovedSourceNeverServes is the negative case of the in-process wait: +// after the volume moved to another host (and the new holder stopped), the +// old source started again never serves and never adopts the line naming the +// other host. It has no lineage of its own from the master, so it exits 75 +// (retry: zero observed-own lineage selects retry, never a fence) rather than +// 78; the exit-78 refusal of a running holder that is moved is covered by +// the master-wait integration tests. +func gap1MovedSourceNeverServes(t *testing.T, fixture *gap1Fixture, exe string, args []string, stem, statusAddr, volume string) { t.Helper() // The simulated hosts share this kernel's per-host volume lock directory: // stop the new holder (the prestarted target) so the old source can open @@ -242,20 +245,24 @@ func gap1MovedSourceExits78(t *testing.T, fixture *gap1Fixture, exe string, args waitGAP1(t, "the new holder did not stop", 30*time.Second, func() bool { return gap1Unit(t, target)["MainPID"] == "0" }) unit := stem + "-moved-source" fixture.start(t, unit, true, exe, args...) - waitGAP1(t, "the moved-away source never exited 78", 90*time.Second, func() bool { + waitGAP1(t, "the moved-away source never exited", 75*time.Second, func() bool { if gap1Operational(t, statusAddr, volume) { t.Fatal("the moved-away source served") } s := gap1Unit(t, unit) - if s["ExecMainStatus"] == "75" { - t.Fatalf("the moved-away source exited 75 (retry) instead of 78 (moved): %+v", s) + switch s["ExecMainStatus"] { + case "", "0": + return false + case "75": + return true } - return s["ExecMainStatus"] == "78" && s["MainPID"] == "0" + t.Fatalf("the moved-away source exited %s; want 75 (retry, no lineage of its own): %+v", s["ExecMainStatus"], s) + return false }) - time.Sleep(7 * time.Second) // past RestartSec: a restart would have happened - if s := gap1Unit(t, unit); s["NRestarts"] != "0" || s["MainPID"] != "0" { - t.Fatalf("systemd restarted the moved-away source after its exit 78: %+v", s) + if gap1Operational(t, statusAddr, volume) { + t.Fatal("the moved-away source served after its exit") } + gap1Systemctl(t, "stop", unit) } // gap1MasterWait reads the volume's /status MasterWait (the startup wait's From 3bb31d2fa8b7ac01b9e67d6ed5b6f2b5b2cd8958 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 24 Nov 2026 18:55:25 -0800 Subject: [PATCH 18/19] layout: a later cleaning reclaims a name a dead remover marked The removal planned only unmarked candidates, so a name marked by a cleaning that died before its delete stayed in the pool for ever. Every found candidate is now planned with its whole tag (session and mark) as read; the conditional mark replaces an abandoned mark, and the dead remover's late delete, conditional on its own mark, fails. The interrupt test now requires every orphan gone after the re-run. Co-Authored-By: Claude Opus 5.5 --- .../core/frontend/chunkstore/layout/remove.go | 9 +++-- .../frontend/chunkstore/layout/remove_test.go | 40 ++++++++++++++----- seaweed-block/docs/design/invariants.md | 3 +- 3 files changed, 38 insertions(+), 14 deletions(-) diff --git a/seaweed-block/core/frontend/chunkstore/layout/remove.go b/seaweed-block/core/frontend/chunkstore/layout/remove.go index 998e3d4d42..d84751bf69 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/remove.go +++ b/seaweed-block/core/frontend/chunkstore/layout/remove.go @@ -23,8 +23,11 @@ import ( // its writes: a session that names a chunk no root named at its Begin // writes that chunk's entry (create, or reuse with a new tag), so the MARK // or the DELETE fails its condition, however late it lands. No lease -// reasoning is needed. A candidate marked by another session is left -// alone. Chunks a restore target names stay live: the source's snapshot +// reasoning is needed. A candidate an earlier session marked and did not +// delete (it died in between) is planned again: its tag carries that +// mark, so the MARK replaces it, and the earlier session's late DELETE, +// conditional on its own mark, fails. Every unreachable name is therefore +// removed by the next completed cleaning. Chunks a restore target names stay live: the source's snapshot // root names them while it has dependents. It returns the names it // deleted, in index order. func RemoveUnreachable(ctx context.Context, st HeadStore, r *Reader, os ObjectStore, me HolderID, session string, shard uint64, candidates []ChunkName) ([]ChunkName, error) { @@ -42,7 +45,7 @@ func RemoveUnreachable(ctx context.Context, st HeadStore, r *Reader, os ObjectSt if err != nil { return nil, err } - if found && meta.Mark == "" { + if found { plan[c] = meta } } diff --git a/seaweed-block/core/frontend/chunkstore/layout/remove_test.go b/seaweed-block/core/frontend/chunkstore/layout/remove_test.go index 645e2391c1..a48faa2145 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/remove_test.go +++ b/seaweed-block/core/frontend/chunkstore/layout/remove_test.go @@ -219,17 +219,37 @@ func TestRemoveUnreachable_ASuccessorBeforeTheHeadViewStopsThePass(t *testing.T) } } -// A candidate already marked by another session is left alone. -func TestRemoveUnreachable_LeavesAnotherSessionsMark(t *testing.T) { +// A candidate an earlier session marked and never deleted (it died in +// between) is reclaimed by the next cleaning, and the earlier session's +// late delete, conditional on its own mark, fails once it is re-marked. +func TestRemoveUnreachable_ReclaimsAnAbandonedMark(t *testing.T) { + ctx := context.Background() o, h, _, orphans := removeFixture(t) + var p5 string for _, c := range orphans { if c.Index == 5 { - o.objs[path.Join(volRoot, c.Path())].meta.Mark = "c0" + p5 = path.Join(volRoot, c.Path()) + o.objs[p5].meta.Mark = "c0" } } removed, err := removeShard0(t, &memHead{h: h}, o, "c1", orphans) - if err != nil || len(removed) != 1 || removed[0].Index != 7 { - t.Fatalf("removed %v %v; want only chunk 7 (5 carries another session's mark)", removed, err) + if err != nil || len(removed) != 2 { + t.Fatalf("removed %v %v; want chunks 5 (abandoned mark) and 7", removed, err) + } + o2, _, _, orphans2 := removeFixture(t) + var c5 ChunkName + for _, c := range orphans2 { + if c.Index == 5 { + c5 = c + o2.objs[path.Join(volRoot, c.Path())].meta.Mark = "c0" + } + } + tag, _, _ := o2.Stat(ctx, c5.Path()) + if err := o2.Mark(ctx, c5.Path(), tag, "c1"); err != nil { + t.Fatal(err) + } + if err := o2.DeleteMarked(ctx, c5.Path(), "c0"); !errors.Is(err, ErrPrecondition) { + t.Fatalf("the dead session's late delete after the re-mark: %v; want ErrPrecondition", err) } } @@ -286,9 +306,9 @@ func cleaningPass(v *memVolume, session string, cands []ChunkName) error { // writes (BeginClean, each mark, each conditional delete, EndClean), before // the write applies and after it applied with its reply lost; at no point // does HEAD reach a missing object, and the restarted holder (a new -// session) ends idle with every orphan of shard 0 removed and every -// reachable object present. A mark left by the killed session is cleared -// by nothing but a reuse, so a marked orphan stays until then. +// session) ends idle with every orphan of shard 0 removed (also one the +// killed session marked and did not delete) and every reachable object +// present. func TestCleaningPass_InterruptAtEveryStep(t *testing.T) { fresh := func() (*memVolume, []ChunkName, []ChunkName) { o, h, live, orphans := removeFixture(t) @@ -331,8 +351,8 @@ func TestCleaningPass_InterruptAtEveryStep(t *testing.T) { for _, c := range orphans { p := path.Join(volRoot, c.Path()) _, present := v.objects[p] - if c.Index != 10001 && present && v.meta(p).Mark != "c1" { - t.Fatalf("orphan %s still present and not held by the killed session's mark", c) + if c.Index != 10001 && present { + t.Fatalf("orphan %s still present after the re-run (mark %q)", c, v.meta(p).Mark) } } for _, c := range live { diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index bb1d739f40..3403bf1914 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -545,7 +545,7 @@ stateDiagram-v2 ## Part B. Invariant ledger -343 rows: 272 ACTIVE, 67 STUB, 4 ARCHIVED; 15 kept from the internal ledger, 328 new. +344 rows: 273 ACTIVE, 67 STUB, 4 ARCHIVED; 15 kept from the internal ledger, 329 new. The "Machine / transition" column refers to Part A. Notes under a table record what a row does not cover and, for kept rows, what was narrowed from the internal ledger. @@ -1097,6 +1097,7 @@ Notes: | `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-SNAPK-REMOVE-MARK-001` | A pool name 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` `RemoveUnreachable` | `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` `RemoveUnreachable` | `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` `RemoveUnreachable` | `TestRemoveUnreachable_ReclaimsAnAbandonedMark`, `TestCleaningPass_InterruptAtEveryStep` | — (the snapshot kernel model is not in this repository) | ACTIVE | | `INV-SNAPK-REMOVE-GUARD-001` | A source scan requires DeleteMarked as RemoveUnreachable's only removal, each immediately after an if on its Mark's error that leaves: an unconditional delete, an ignored mark, a reused mark or another method fails. | M9 clean → clean (RemoveUnreachable) | `core/frontend/chunkstore/layout` (source scan of `remove.go`) | `TestGuard_WritersTransitionsAndRemovers`, `TestGuard_Controls` | — (the snapshot kernel model is not in this repository) | ACTIVE | | `INV-SNAPK-REUSE-001` | Writing an object for a session creates it, or reuses an existing one by a conditional update that sets the session and clears any mark; a commit names only objects its session wrote or reused, unmarked. | M9 snap → idle (Upload, Commit) | `core/frontend/chunkstore/layout` `objects.go` `EnsureObject`; `commit.go` `RunCommit` | `TestEnsureObject`, `TestRunCommit_NeedsObjectsOfItsOwnSession`, `TestSnapshotSession_InterruptAtEveryStep` | — (the snapshot kernel model is not in this repository) | ACTIVE | | `INV-SNAPK-STALE-HOLDER-001` | Every transition refuses an older epoch of the same server, the same epoch held by another server, and the same epoch and server with another claim id, in idle, snap and clean; a new transition must be added to the table. | M9 every transition | `core/frontend/chunkstore/layout` `Head.heldBy` and each transition | `TestTransitions_RefuseAStaleHolder` | — (the snapshot kernel model is not in this repository) | ACTIVE | From e502ad4b9235a8182313bb6fd6818e67a53f624d Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 24 Nov 2026 19:05:39 -0800 Subject: [PATCH 19/19] test: the moved-away source's journal shows the refused foreign line and no adoption Co-Authored-By: Claude Opus 5.5 --- .../startup_systemd_integration_test.go | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/seaweed-block/cmd/blockvolume/startup_systemd_integration_test.go b/seaweed-block/cmd/blockvolume/startup_systemd_integration_test.go index d968c5289e..808e5e2f58 100644 --- a/seaweed-block/cmd/blockvolume/startup_systemd_integration_test.go +++ b/seaweed-block/cmd/blockvolume/startup_systemd_integration_test.go @@ -262,6 +262,27 @@ func gap1MovedSourceNeverServes(t *testing.T, fixture *gap1Fixture, exe string, if gap1Operational(t, statusAddr, volume) { t.Fatal("the moved-away source served after its exit") } + // The exit must come from the move, not from an unassigned or + // disconnected timeout: the journal shows the source received the line + // naming the other host, refused it as another server's, and never adopted + // a lineage of its own. + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + journal, err := exec.CommandContext(ctx, "journalctl", "--unit="+unit, "--no-pager", "--output=cat").CombinedOutput() + cancel() + if err != nil { + t.Fatalf("moved-away source journal: %v %s", err, journal) + } + for _, want := range []string{ + fmt.Sprintf("assignment identity refusal volume=%q replica=%q server=%q", volume, "r1", "s2"), + fmt.Sprintf("foreign assignment server=%q replica=%q recorded, not adopted", "s2", "r1"), + } { + if !strings.Contains(string(journal), want) { + t.Fatalf("the moved-away source's journal lacks %q: its exit is not proven to come from the move\n%s", want, journal) + } + } + if strings.Contains(string(journal), "adopted as PRIMARY") { + t.Fatalf("the moved-away source adopted a lineage:\n%s", journal) + } gap1Systemctl(t, "stop", unit) }