From bb97d6a7f443e5ab846686e161dc7db578efb9b3 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 26 Nov 2026 04:00:07 -0800 Subject: [PATCH 01/14] fix(blockmaster): refuse a replicated cluster spec with the product loop off With --cluster-spec, a replicated volume's placement is bound, its line minted and its promotion gate run only by the lifecycle product loop. With --lifecycle-product-loop-interval at its default 0 that loop never runs, so the master starts, accepts heartbeats and never gives the volume a line; every replica waits at epoch 0 with no error. blockmaster now refuses to start when its cluster spec holds a volume with replication factor above 1 and the loop is off, naming the flag. A static --topology (whose observation controller mints) and single-replica volumes are untouched. Co-Authored-By: Claude Opus 5.5 --- seaweed-block/cmd/blockmaster/main.go | 4 + .../cmd/blockmaster/product_loop_guard.go | 26 +++++ .../blockmaster/product_loop_guard_test.go | 96 +++++++++++++++++++ 3 files changed, 126 insertions(+) create mode 100644 seaweed-block/cmd/blockmaster/product_loop_guard.go create mode 100644 seaweed-block/cmd/blockmaster/product_loop_guard_test.go diff --git a/seaweed-block/cmd/blockmaster/main.go b/seaweed-block/cmd/blockmaster/main.go index 20d4a3757f..17c501ce3c 100644 --- a/seaweed-block/cmd/blockmaster/main.go +++ b/seaweed-block/cmd/blockmaster/main.go @@ -227,6 +227,10 @@ func run(f flags) int { fmt.Fprintln(os.Stderr, "blockmaster:", err) return 2 } + if err := requireProductLoop(f.lifecycleLoop, clusterImport); err != nil { + fmt.Fprintln(os.Stderr, "blockmaster:", err) + return 2 + } if len(topo.Volumes) == 0 && len(clusterImport.Nodes) == 0 { // Without a topology the observation host classifies every // volume UnknownReplicaClaim; controller can never mint. diff --git a/seaweed-block/cmd/blockmaster/product_loop_guard.go b/seaweed-block/cmd/blockmaster/product_loop_guard.go new file mode 100644 index 0000000000..4d11c21803 --- /dev/null +++ b/seaweed-block/cmd/blockmaster/product_loop_guard.go @@ -0,0 +1,26 @@ +package main + +import ( + "fmt" + "time" +) + +// requireProductLoop refuses a start whose cluster spec holds a replicated +// volume (replication factor above 1) while the lifecycle product loop is +// off. On the cluster-spec path that loop alone binds a replicated volume's +// placement, mints its line and runs its promotion gate, so with the loop +// off the volume never gets a line. A static --topology (whose observation +// controller mints) and single-replica volumes are untouched. +func requireProductLoop(interval time.Duration, spec clusterSpecImport) error { + if interval > 0 { + return nil + } + for _, v := range spec.Volumes { + if v.ReplicationFactor > 1 { + return fmt.Errorf("cluster spec volume %s has replication factor %d but --lifecycle-product-loop-interval is 0 (off): "+ + "with --cluster-spec a replicated volume is bound and promoted only by that loop; set --lifecycle-product-loop-interval (for example 100ms)", + v.VolumeID, v.ReplicationFactor) + } + } + return nil +} diff --git a/seaweed-block/cmd/blockmaster/product_loop_guard_test.go b/seaweed-block/cmd/blockmaster/product_loop_guard_test.go new file mode 100644 index 0000000000..96c15ae958 --- /dev/null +++ b/seaweed-block/cmd/blockmaster/product_loop_guard_test.go @@ -0,0 +1,96 @@ +package main + +import ( + "io" + "os" + "path/filepath" + "strings" + "testing" + "time" +) + +// clusterSpecWithRF writes a cluster spec of three nodes and one volume v1 +// with the given replication factor (placements on the first rf nodes). +func clusterSpecWithRF(t *testing.T, rf int) string { + t.Helper() + var b strings.Builder + b.WriteString("nodes:\n") + for i := 1; i <= 3; i++ { + b.WriteString(" - server_id: s" + string(rune('0'+i)) + "\n data_addr: 127.0.0.1:1" + string(rune('0'+i)) + "601\n ctrl_addr: 127.0.0.1:1" + string(rune('0'+i)) + "602\n") + } + b.WriteString("volumes:\n - id: v1\n size_bytes: 268435456\n replication_factor: " + string(rune('0'+rf)) + "\n placements:\n") + for i := 1; i <= rf; i++ { + b.WriteString(" - server_id: s" + string(rune('0'+i)) + "\n replica_id: r" + string(rune('0'+i)) + "\n") + } + p := filepath.Join(t.TempDir(), "cluster-spec.yaml") + if err := os.WriteFile(p, []byte(b.String()), 0o600); err != nil { + t.Fatal(err) + } + return p +} + +// A replicated cluster-spec volume with the product loop off is refused at +// start, naming the flag, before anything is opened (run returns 2). +func TestReplicatedClusterSpecWithTheProductLoopOffIsRefused(t *testing.T) { + f, err := parseFlags([]string{ + "--authority-store", filepath.Join(t.TempDir(), "authority"), + "--lifecycle-store", filepath.Join(t.TempDir(), "lifecycle"), + "--cluster-spec", clusterSpecWithRF(t, 3), + "--expected-slots-per-volume", "3", + "--listen", "127.0.0.1:0", + }) + if err != nil { + t.Fatal(err) + } + r, w, err := os.Pipe() + if err != nil { + t.Fatal(err) + } + saved := os.Stderr + os.Stderr = w + done := make(chan int, 1) + go func() { done <- run(f) }() // without the guard run starts and serves + var code int + select { + case code = <-done: + case <-time.After(10 * time.Second): + os.Stderr = saved + t.Fatal("blockmaster started with a replicated cluster spec and the product loop off") + } + os.Stderr = saved + w.Close() + out, _ := io.ReadAll(r) + if code != 2 || !strings.Contains(string(out), "--lifecycle-product-loop-interval") || !strings.Contains(string(out), "v1") { + t.Fatalf("run=%d, stderr %q; want 2 and the flag named", code, out) + } +} + +// The same spec with the loop on, a single-replica spec with the loop off, +// and no cluster spec (a static topology) all pass the guard. +func TestTheProductLoopGuardPassesWhatItShould(t *testing.T) { + for name, c := range map[string]struct { + rf int + interval time.Duration + }{ + "rf3 with the loop on": {3, 100 * time.Millisecond}, + "rf1 with the loop off": {1, 0}, + } { + spec, err := loadClusterSpec(clusterSpecWithRF(t, c.rf)) + if err != nil { + t.Fatalf("%s: %v", name, err) + } + if err := requireProductLoop(c.interval, spec); err != nil { + t.Fatalf("%s: refused: %v", name, err) + } + } + if err := requireProductLoop(0, clusterSpecImport{}); err != nil { + t.Fatalf("no cluster spec (static topology): refused: %v", err) + } + spec, err := loadClusterSpec(clusterSpecWithRF(t, 2)) + if err != nil { + t.Fatal(err) + } + if err := requireProductLoop(0, spec); err == nil { + t.Fatal("rf2 with the loop off passed") + } +} From deee2e25ff4fb9f5da5a397a7676eb9801addffd Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 26 Nov 2026 04:03:48 -0800 Subject: [PATCH 02/14] docs(invariants): INV-AUTH-REPLICATED-SPEC-NEEDS-LOOP-001 for the startup refusal Co-Authored-By: Claude Opus 5.5 --- seaweed-block/docs/design/invariants.md | 1 + 1 file changed, 1 insertion(+) diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 9e8375a9f4..6129f629dc 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -716,6 +716,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/frontend/chunkstore/layout/start.go` `Start`, `core/frontend/chunkstore/layout/claim.go` `Claim`; 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: with mutual TLS on, a node may act only for the server id bound to its certificate (`TERM-CALLER-001`; `auth.RequireNode` in `ReportHeartbeat`, `SubscribeAssignments`, `RenewWorkspaceLease`, `AckWorkspaceRevoked`, `QueryVolumeStatus`; `TestNodeActsOnlyForItsOwnServerID`, `core/host/master/auth_red_test.go`), and the registered-host check stays beside it (no NAT or proxy between volume and master in OSS); in development mode (plaintext on loopback, no role file) there is no 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-CALLER-ROLE-001` | With mutual TLS on, every blockmaster gRPC call (unary, and before every stream send) is decided by the caller's certificate and the current role file: an unknown caller is refused UNAUTHENTICATED, a role its method's rule does not admit PERMISSION_DENIED, a method without a rule always. | AUTHORITY: control API callers (people, tools, nodes) | `core/auth/identity.go` `Authenticator.PeerIdentity`, `Authenticator.Reload`; `core/auth/authorize.go` `Rule.Allows`, `UnaryInterceptor`, `StreamInterceptor`, `RequireNode`, `RequireRole`; `core/host/master/authz.go` `masterRules`, `serverAuth`; `core/rpc/link/tls.go` `ServerCredentials`, `ClientCredentials`; `cmd/blockmaster/auth.go` `authFlags.validate`, `authFlags.build` | `TestPeerIdentity`, `TestRoleFileReload` (`core/auth/identity_test.go`); `TestRuleAllows`, `TestRequireNodeAndRole`, `TestUnaryInterceptor`, `TestStreamEndsAtTheReloadThatRevokesItsCaller` (`core/auth/authorize_test.go`); `TestMasterAuthorizationTableCoversEveryMethod` (`core/host/master/authz_test.go`); `TestForcedMoveNeedsAnAdmin`, `TestNodeActsOnlyForItsOwnServerID` (`core/host/master/auth_red_test.go`); `TestMasterLinkMutualTLS` (`core/rpc/link/tls_test.go`); `TestAuthFlags` (`cmd/blockmaster/auth_flags_test.go`); `TestMasterTLSFlags` (`cmd/blockvolume/master_tls_test.go`). Also: a mutating operator or admin method writes its audit attempt before it runs or is refused as audit unavailable (`Rule.Strict`; `TestMasterOperatorMethodsAreStrict` (inverted: a new operator or admin method fails unless strict or named with its reason), `core/host/master/authz_test.go`; `TestStrictCallsNeedTheirAttemptLine`, `core/auth/strict_audit_test.go`), node calls never wait on the audit log; a reload that removes a caller, or changes its role so the method's rule no longer admits it, ends its open streams at the reload; a forced move needs an admin; plaintext listens only on loopback without a role file (development mode). Limits: the audit log records outcomes and decides nothing; the volume process's own HTTP routes stay loopback-only and unauthenticated. | `AuthLease` (exhaustive run pending) | ACTIVE | +| `INV-AUTH-REPLICATED-SPEC-NEEDS-LOOP-001` | blockmaster refuses to start when its cluster spec holds a replicated volume (replication factor above 1) while the lifecycle product loop is off: on that path only the loop binds, mints and promotes such a volume, so it would never get a line. | M2 none → Bound (a replicated cluster-spec volume's first line) | `cmd/blockmaster/product_loop_guard.go` `requireProductLoop`; `cmd/blockmaster/main.go` `run` | `TestReplicatedClusterSpecWithTheProductLoopOffIsRefused`, `TestTheProductLoopGuardPassesWhatItShould` (`cmd/blockmaster/product_loop_guard_test.go`) | — (a startup configuration check). Limits: static `--topology` is not refused (its observation controller mints), and has no automatic failover in v1 | 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` | `TestLayoutGrantedEpochIssuerSites`, `TestLayoutEpochEnumerationRejectsANewIssuer`, `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-RESTART-REISSUE-001` | A line records the primary process it was issued for (durable); a current primary reporting another process is re-issued its line at a new endpoint version, and a primary adopts no line issued for another process, so a restarted process never reuses the dead one's sessions. | M2 authority (RefreshEndpoint); M3 primary adoption | `core/authority/authority.go` `applyWithWorkspaceMove` (records the ask's or the source's incarnation); `core/authority/controller.go` `endpointStale`, `sameAsk`; `core/authority/workspace.go` `persistWorkspaceTimedLocked`; `core/authority/observation_store.go` `SlotFactAt`; `core/host/master/host.go` (the source); `core/host/volume/host.go` `applyFact` | `TestPublisher_RestartedPrimaryGetsANewEndpointVersion`, `TestPublisher_AskWithoutAProcessIsIssuedForTheReportedOne`, `TestTopologyController_RestartedPrimaryAtTheSameAddressIsReissued`, `TestTopologyController_QueuedRefreshIsReplacedForANewerProcess`, `TestTopologyController_UnnamedLineIsReissuedOnceForTheReportingProcess`, `TestWorkspaceLeaseWriteKeepsTheLinesIncarnationAcrossReload`, `TestObservationStore_SlotFactAtIsTheProcessAtThoseEndpoints` (`core/authority/restart_endpoint_version_test.go`); `TestLinesNameTheirPrimarysProcess`, `TestLineForTheTargetsEndpointsNamesTheTargetsProcess` (`core/host/master/line_incarnation_test.go`); `TestHost_ApplyFact_LineIssuedForAnotherProcessIsNotAdopted`, `TestHost_ApplyFact_UnnamedLineIsNotAdoptedWhereLinesNameTheirProcess` (`core/host/volume/line_incarnation_test.go`); `TestHostConfigAdoptsOnlyLinesNamingThisProcess` (`cmd/blockvolume/lines_name_their_process_test.go`); `TestRestartedPrimaryAtTheSameEpochIsAdmitted` (`core/replication/primary_restart_session_test.go`) | — | 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 | From 613c5d478909c21c179d3c752a1eff51fb047156 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 26 Nov 2026 04:13:25 -0800 Subject: [PATCH 03/14] fix(master): CreateVolume refuses a replication factor the master does not decide The controller validates every replicated volume it decides against the master's one slot count (--expected-slots-per-volume) and refuses the whole decision when one differs. CreateVolume accepted any replication factor, so an RF2 create on an RF3 master gave a 2-slot placement which, once its replicas heartbeat, stopped assignment and failover for every replicated volume of the cluster. CreateVolume now answers FailedPrecondition, naming both counts, when a replication factor above 1 differs from the master's. Single-replica volumes (which never reach the check) are admitted as before. Co-Authored-By: Claude Opus 5.5 --- seaweed-block/core/authority/controller.go | 4 ++ .../host/master/create_rf_mismatch_test.go | 40 +++++++++++++++++++ .../host/master/lifecycle_service_test.go | 6 +-- seaweed-block/core/host/master/services.go | 8 ++++ seaweed-block/docs/design/invariants.md | 1 + 5 files changed, 56 insertions(+), 3 deletions(-) create mode 100644 seaweed-block/core/host/master/create_rf_mismatch_test.go diff --git a/seaweed-block/core/authority/controller.go b/seaweed-block/core/authority/controller.go index 27e32379c8..322aba42b6 100644 --- a/seaweed-block/core/authority/controller.go +++ b/seaweed-block/core/authority/controller.go @@ -57,6 +57,10 @@ func (c *TopologyController) SetNowForTest(now func() time.Time) { c.now = now } +// ExpectedSlotsPerVolume is the one replica-slot count every volume the +// controller decides must have (validateVolumeTopology). +func (c *TopologyController) ExpectedSlotsPerVolume() int { return c.config.ExpectedSlotsPerVolume } + // SubmitClusterSnapshot is the cluster-scoped entry point for // topology, health, and convergence observations. Rejects empty // snapshots to preserve the "supported truth only" invariant on diff --git a/seaweed-block/core/host/master/create_rf_mismatch_test.go b/seaweed-block/core/host/master/create_rf_mismatch_test.go new file mode 100644 index 0000000000..9abb05bb75 --- /dev/null +++ b/seaweed-block/core/host/master/create_rf_mismatch_test.go @@ -0,0 +1,40 @@ +package master + +import ( + "context" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/authority" + control "github.com/seaweedfs/seaweed-block/core/rpc/control" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" +) + +// One replicated factor per cluster: an RF2 create on an RF3 master (expected +// slots 3) is refused with FailedPrecondition and records nothing, while an +// RF3 and an RF1 create are admitted; and every existing volume keeps failing +// over (no volume of another slot count can stop the controller's decisions). +func TestAnRF2CreateOnAnRF3MasterIsRefusedAndFailoverContinues(t *testing.T) { + h := newBootGraceMaster(t, Config{ControllerConfig: authority.TopologyControllerConfig{PrimaryBootGrace: 200 * time.Millisecond}}) + defer closeTestMaster(t, h) + svc := newServices(h) + _, err := svc.CreateVolume(context.Background(), &control.CreateVolumeRequest{VolumeId: "v-rf2", SizeBytes: 1 << 20, ReplicationFactor: 2}) + if status.Code(err) != codes.FailedPrecondition { + t.Fatalf("RF2 create on an RF3 master: %v; want FailedPrecondition", err) + } + if _, ok := h.Lifecycle().Volumes.GetVolume("v-rf2"); ok { + t.Fatal("the refused RF2 create left a volume record") + } + for _, rf := range []int32{3, 1} { + id := map[int32]string{3: "v-rf3-new", 1: "v-rf1-new"}[rf] + if _, err := svc.CreateVolume(context.Background(), &control.CreateVolumeRequest{VolumeId: id, SizeBytes: 1 << 20, ReplicationFactor: rf}); err != nil { + t.Fatalf("RF%d create on an RF3 master: %v", rf, err) + } + } + time.Sleep(250 * time.Millisecond) // past the boot grace + ineligible := restarting + ineligible.eligible = false + unsupportedTick(t, h, ineligible) + expectFailoverToR2(t, h, "an existing RF3 volume after the refused RF2 create") +} diff --git a/seaweed-block/core/host/master/lifecycle_service_test.go b/seaweed-block/core/host/master/lifecycle_service_test.go index ee87b37c06..6fa79e0c42 100644 --- a/seaweed-block/core/host/master/lifecycle_service_test.go +++ b/seaweed-block/core/host/master/lifecycle_service_test.go @@ -92,15 +92,15 @@ func TestRestoreCreateVolumePersistsRequestBeforeTargetAndHealsRetry(t *testing. if _, ok := h.Lifecycle().Volumes.GetVolume("net-target"); ok { t.Fatal("RF2 restore created a target record") } - if _, err := svc.CreateVolume(context.Background(), &control.CreateVolumeRequest{VolumeId: "net-source", SizeBytes: 1 << 20, ReplicationFactor: 2}); err != nil { + if _, err := svc.CreateVolume(context.Background(), &control.CreateVolumeRequest{VolumeId: "net-source", SizeBytes: 1 << 20, ReplicationFactor: 3}); err != nil { t.Fatal(err) } unsafe = &control.CreateVolumeRequest{VolumeId: "from-net", SourceVolume: "net-source", SourceSnapshot: "daily", CreateRequestId: "restore-from-net"} if _, err := svc.CreateVolume(context.Background(), unsafe); status.Code(err) != codes.FailedPrecondition { - t.Fatalf("RF2 source restore: %v; want refusal", err) + t.Fatalf("RF3 source restore: %v; want refusal", err) } if _, ok := h.Lifecycle().Volumes.GetVolume("from-net"); ok { - t.Fatal("RF2 source restore created a target record") + t.Fatal("RF3 source restore created a target record") } } diff --git a/seaweed-block/core/host/master/services.go b/seaweed-block/core/host/master/services.go index b7dd2ce62f..60050718d5 100644 --- a/seaweed-block/core/host/master/services.go +++ b/seaweed-block/core/host/master/services.go @@ -70,6 +70,14 @@ func (s *services) CreateVolume(ctx context.Context, req *control.CreateVolumeRe if stores.Deletions.Reserved(spec.VolumeID) { return nil, status.Errorf(codes.FailedPrecondition, "create volume: %s is being deleted or was deleted; its id is never reused", spec.VolumeID) } + // One replicated factor per cluster: the controller validates every + // replicated volume it decides against the master's one slot count and + // refuses the whole decision when one differs, so a volume of another + // replication factor would stop every replicated volume's assignment and + // failover. Single-replica volumes never reach that check. + if c := s.host.ctrl; c != nil && spec.ReplicationFactor > 1 && spec.ReplicationFactor != c.ExpectedSlotsPerVolume() { + return nil, status.Errorf(codes.FailedPrecondition, "create volume: %s has replication factor %d, but this master decides replicated volumes of %d replicas (--expected-slots-per-volume); one replicated factor per cluster", spec.VolumeID, spec.ReplicationFactor, c.ExpectedSlotsPerVolume()) + } // A retry may carry a different restore tuple. The target's durable // binding decides that conflict before looking up the caller's new source // snapshot, which might itself be absent. diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 9e8375a9f4..3bf9e3e97f 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -716,6 +716,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/frontend/chunkstore/layout/start.go` `Start`, `core/frontend/chunkstore/layout/claim.go` `Claim`; 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: with mutual TLS on, a node may act only for the server id bound to its certificate (`TERM-CALLER-001`; `auth.RequireNode` in `ReportHeartbeat`, `SubscribeAssignments`, `RenewWorkspaceLease`, `AckWorkspaceRevoked`, `QueryVolumeStatus`; `TestNodeActsOnlyForItsOwnServerID`, `core/host/master/auth_red_test.go`), and the registered-host check stays beside it (no NAT or proxy between volume and master in OSS); in development mode (plaintext on loopback, no role file) there is no 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-CALLER-ROLE-001` | With mutual TLS on, every blockmaster gRPC call (unary, and before every stream send) is decided by the caller's certificate and the current role file: an unknown caller is refused UNAUTHENTICATED, a role its method's rule does not admit PERMISSION_DENIED, a method without a rule always. | AUTHORITY: control API callers (people, tools, nodes) | `core/auth/identity.go` `Authenticator.PeerIdentity`, `Authenticator.Reload`; `core/auth/authorize.go` `Rule.Allows`, `UnaryInterceptor`, `StreamInterceptor`, `RequireNode`, `RequireRole`; `core/host/master/authz.go` `masterRules`, `serverAuth`; `core/rpc/link/tls.go` `ServerCredentials`, `ClientCredentials`; `cmd/blockmaster/auth.go` `authFlags.validate`, `authFlags.build` | `TestPeerIdentity`, `TestRoleFileReload` (`core/auth/identity_test.go`); `TestRuleAllows`, `TestRequireNodeAndRole`, `TestUnaryInterceptor`, `TestStreamEndsAtTheReloadThatRevokesItsCaller` (`core/auth/authorize_test.go`); `TestMasterAuthorizationTableCoversEveryMethod` (`core/host/master/authz_test.go`); `TestForcedMoveNeedsAnAdmin`, `TestNodeActsOnlyForItsOwnServerID` (`core/host/master/auth_red_test.go`); `TestMasterLinkMutualTLS` (`core/rpc/link/tls_test.go`); `TestAuthFlags` (`cmd/blockmaster/auth_flags_test.go`); `TestMasterTLSFlags` (`cmd/blockvolume/master_tls_test.go`). Also: a mutating operator or admin method writes its audit attempt before it runs or is refused as audit unavailable (`Rule.Strict`; `TestMasterOperatorMethodsAreStrict` (inverted: a new operator or admin method fails unless strict or named with its reason), `core/host/master/authz_test.go`; `TestStrictCallsNeedTheirAttemptLine`, `core/auth/strict_audit_test.go`), node calls never wait on the audit log; a reload that removes a caller, or changes its role so the method's rule no longer admits it, ends its open streams at the reload; a forced move needs an admin; plaintext listens only on loopback without a role file (development mode). Limits: the audit log records outcomes and decides nothing; the volume process's own HTTP routes stay loopback-only and unauthenticated. | `AuthLease` (exhaustive run pending) | ACTIVE | +| `INV-AUTH-ONE-REPLICATED-FACTOR-001` | A replicated volume is created only with the master's one replica-slot count (--expected-slots-per-volume): CreateVolume refuses another replication factor above 1, since one mismatched volume would stop the controller's decisions for every volume. | M2 none → Bound (a created replicated volume's first line) | `core/host/master/services.go` `CreateVolume`; `core/authority/controller.go` `ExpectedSlotsPerVolume`, `validateVolumeTopology` | `TestAnRF2CreateOnAnRF3MasterIsRefusedAndFailoverContinues` (`core/host/master/create_rf_mismatch_test.go`) | — (an admission check). Limits: single-replica volumes are admitted at any slot count (they never reach the check); a cluster spec or topology file with a mismatched volume is not checked at start | 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` | `TestLayoutGrantedEpochIssuerSites`, `TestLayoutEpochEnumerationRejectsANewIssuer`, `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-RESTART-REISSUE-001` | A line records the primary process it was issued for (durable); a current primary reporting another process is re-issued its line at a new endpoint version, and a primary adopts no line issued for another process, so a restarted process never reuses the dead one's sessions. | M2 authority (RefreshEndpoint); M3 primary adoption | `core/authority/authority.go` `applyWithWorkspaceMove` (records the ask's or the source's incarnation); `core/authority/controller.go` `endpointStale`, `sameAsk`; `core/authority/workspace.go` `persistWorkspaceTimedLocked`; `core/authority/observation_store.go` `SlotFactAt`; `core/host/master/host.go` (the source); `core/host/volume/host.go` `applyFact` | `TestPublisher_RestartedPrimaryGetsANewEndpointVersion`, `TestPublisher_AskWithoutAProcessIsIssuedForTheReportedOne`, `TestTopologyController_RestartedPrimaryAtTheSameAddressIsReissued`, `TestTopologyController_QueuedRefreshIsReplacedForANewerProcess`, `TestTopologyController_UnnamedLineIsReissuedOnceForTheReportingProcess`, `TestWorkspaceLeaseWriteKeepsTheLinesIncarnationAcrossReload`, `TestObservationStore_SlotFactAtIsTheProcessAtThoseEndpoints` (`core/authority/restart_endpoint_version_test.go`); `TestLinesNameTheirPrimarysProcess`, `TestLineForTheTargetsEndpointsNamesTheTargetsProcess` (`core/host/master/line_incarnation_test.go`); `TestHost_ApplyFact_LineIssuedForAnotherProcessIsNotAdopted`, `TestHost_ApplyFact_UnnamedLineIsNotAdoptedWhereLinesNameTheirProcess` (`core/host/volume/line_incarnation_test.go`); `TestHostConfigAdoptsOnlyLinesNamingThisProcess` (`cmd/blockvolume/lines_name_their_process_test.go`); `TestRestartedPrimaryAtTheSameEpochIsAdmitted` (`core/replication/primary_restart_session_test.go`) | — | 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 | From 278dcc2eefc55dc619505e5f42abe043df33e40d Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 26 Nov 2026 04:15:30 -0800 Subject: [PATCH 04/14] fix(blockmaster): also refuse a cluster spec volume of another replication factor A replicated cluster-spec volume whose replication factor differs from --expected-slots-per-volume would make the controller refuse every decision (one slot count per cluster); blockmaster now refuses to start, naming the volume and both counts, also with the product loop on. Co-Authored-By: Claude Opus 5.5 --- seaweed-block/cmd/blockmaster/main.go | 2 +- .../cmd/blockmaster/product_loop_guard.go | 25 ++++++++++++++----- .../blockmaster/product_loop_guard_test.go | 23 ++++++++++++++--- seaweed-block/docs/design/invariants.md | 2 +- 4 files changed, 41 insertions(+), 11 deletions(-) diff --git a/seaweed-block/cmd/blockmaster/main.go b/seaweed-block/cmd/blockmaster/main.go index 17c501ce3c..9c06607159 100644 --- a/seaweed-block/cmd/blockmaster/main.go +++ b/seaweed-block/cmd/blockmaster/main.go @@ -227,7 +227,7 @@ func run(f flags) int { fmt.Fprintln(os.Stderr, "blockmaster:", err) return 2 } - if err := requireProductLoop(f.lifecycleLoop, clusterImport); err != nil { + if err := requireProductLoop(f.lifecycleLoop, f.expectedSlotsPerVol, clusterImport); err != nil { fmt.Fprintln(os.Stderr, "blockmaster:", err) return 2 } diff --git a/seaweed-block/cmd/blockmaster/product_loop_guard.go b/seaweed-block/cmd/blockmaster/product_loop_guard.go index 4d11c21803..3ad0c08b04 100644 --- a/seaweed-block/cmd/blockmaster/product_loop_guard.go +++ b/seaweed-block/cmd/blockmaster/product_loop_guard.go @@ -6,12 +6,25 @@ import ( ) // requireProductLoop refuses a start whose cluster spec holds a replicated -// volume (replication factor above 1) while the lifecycle product loop is -// off. On the cluster-spec path that loop alone binds a replicated volume's -// placement, mints its line and runs its promotion gate, so with the loop -// off the volume never gets a line. A static --topology (whose observation -// controller mints) and single-replica volumes are untouched. -func requireProductLoop(interval time.Duration, spec clusterSpecImport) error { +// volume (replication factor above 1) that the master could never decide: +// - one whose replication factor differs from --expected-slots-per-volume: +// the controller validates every replicated volume against that one +// count and refuses the whole decision when one differs, so it would +// stop every replicated volume's assignment and failover; +// - any, while the lifecycle product loop is off: on the cluster-spec path +// that loop alone binds a replicated volume's placement, mints its line +// and runs its promotion gate, so with the loop off it never gets a line. +// +// A static --topology (whose observation controller mints) and +// single-replica volumes are untouched. +func requireProductLoop(interval time.Duration, expectedSlots int, spec clusterSpecImport) error { + for _, v := range spec.Volumes { + if v.ReplicationFactor > 1 && v.ReplicationFactor != expectedSlots { + return fmt.Errorf("cluster spec volume %s has replication factor %d but --expected-slots-per-volume is %d: "+ + "the master decides replicated volumes of one slot count only (one replicated factor per cluster)", + v.VolumeID, v.ReplicationFactor, expectedSlots) + } + } if interval > 0 { return nil } diff --git a/seaweed-block/cmd/blockmaster/product_loop_guard_test.go b/seaweed-block/cmd/blockmaster/product_loop_guard_test.go index 96c15ae958..0d89195247 100644 --- a/seaweed-block/cmd/blockmaster/product_loop_guard_test.go +++ b/seaweed-block/cmd/blockmaster/product_loop_guard_test.go @@ -79,18 +79,35 @@ func TestTheProductLoopGuardPassesWhatItShould(t *testing.T) { if err != nil { t.Fatalf("%s: %v", name, err) } - if err := requireProductLoop(c.interval, spec); err != nil { + if err := requireProductLoop(c.interval, c.rf, spec); err != nil { t.Fatalf("%s: refused: %v", name, err) } } - if err := requireProductLoop(0, clusterSpecImport{}); err != nil { + if err := requireProductLoop(0, 3, clusterSpecImport{}); err != nil { t.Fatalf("no cluster spec (static topology): refused: %v", err) } spec, err := loadClusterSpec(clusterSpecWithRF(t, 2)) if err != nil { t.Fatal(err) } - if err := requireProductLoop(0, spec); err == nil { + if err := requireProductLoop(0, 2, spec); err == nil { t.Fatal("rf2 with the loop off passed") } } + +// A replicated cluster-spec volume whose replication factor differs from +// --expected-slots-per-volume is refused at start, naming the volume and +// both counts, also with the loop on; a matching one passes. +func TestAClusterSpecVolumeOfAnotherReplicationFactorIsRefused(t *testing.T) { + spec, err := loadClusterSpec(clusterSpecWithRF(t, 2)) + if err != nil { + t.Fatal(err) + } + err = requireProductLoop(100*time.Millisecond, 3, spec) + if err == nil || !strings.Contains(err.Error(), "v1") || !strings.Contains(err.Error(), "--expected-slots-per-volume is 3") { + t.Fatalf("an RF2 volume on an expected-3 master: %v; want a refusal naming v1 and both counts", err) + } + if err := requireProductLoop(100*time.Millisecond, 2, spec); err != nil { + t.Fatalf("an RF2 volume on an expected-2 master: refused: %v", err) + } +} diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 6129f629dc..45deac2d62 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -716,7 +716,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/frontend/chunkstore/layout/start.go` `Start`, `core/frontend/chunkstore/layout/claim.go` `Claim`; 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: with mutual TLS on, a node may act only for the server id bound to its certificate (`TERM-CALLER-001`; `auth.RequireNode` in `ReportHeartbeat`, `SubscribeAssignments`, `RenewWorkspaceLease`, `AckWorkspaceRevoked`, `QueryVolumeStatus`; `TestNodeActsOnlyForItsOwnServerID`, `core/host/master/auth_red_test.go`), and the registered-host check stays beside it (no NAT or proxy between volume and master in OSS); in development mode (plaintext on loopback, no role file) there is no 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-CALLER-ROLE-001` | With mutual TLS on, every blockmaster gRPC call (unary, and before every stream send) is decided by the caller's certificate and the current role file: an unknown caller is refused UNAUTHENTICATED, a role its method's rule does not admit PERMISSION_DENIED, a method without a rule always. | AUTHORITY: control API callers (people, tools, nodes) | `core/auth/identity.go` `Authenticator.PeerIdentity`, `Authenticator.Reload`; `core/auth/authorize.go` `Rule.Allows`, `UnaryInterceptor`, `StreamInterceptor`, `RequireNode`, `RequireRole`; `core/host/master/authz.go` `masterRules`, `serverAuth`; `core/rpc/link/tls.go` `ServerCredentials`, `ClientCredentials`; `cmd/blockmaster/auth.go` `authFlags.validate`, `authFlags.build` | `TestPeerIdentity`, `TestRoleFileReload` (`core/auth/identity_test.go`); `TestRuleAllows`, `TestRequireNodeAndRole`, `TestUnaryInterceptor`, `TestStreamEndsAtTheReloadThatRevokesItsCaller` (`core/auth/authorize_test.go`); `TestMasterAuthorizationTableCoversEveryMethod` (`core/host/master/authz_test.go`); `TestForcedMoveNeedsAnAdmin`, `TestNodeActsOnlyForItsOwnServerID` (`core/host/master/auth_red_test.go`); `TestMasterLinkMutualTLS` (`core/rpc/link/tls_test.go`); `TestAuthFlags` (`cmd/blockmaster/auth_flags_test.go`); `TestMasterTLSFlags` (`cmd/blockvolume/master_tls_test.go`). Also: a mutating operator or admin method writes its audit attempt before it runs or is refused as audit unavailable (`Rule.Strict`; `TestMasterOperatorMethodsAreStrict` (inverted: a new operator or admin method fails unless strict or named with its reason), `core/host/master/authz_test.go`; `TestStrictCallsNeedTheirAttemptLine`, `core/auth/strict_audit_test.go`), node calls never wait on the audit log; a reload that removes a caller, or changes its role so the method's rule no longer admits it, ends its open streams at the reload; a forced move needs an admin; plaintext listens only on loopback without a role file (development mode). Limits: the audit log records outcomes and decides nothing; the volume process's own HTTP routes stay loopback-only and unauthenticated. | `AuthLease` (exhaustive run pending) | ACTIVE | -| `INV-AUTH-REPLICATED-SPEC-NEEDS-LOOP-001` | blockmaster refuses to start when its cluster spec holds a replicated volume (replication factor above 1) while the lifecycle product loop is off: on that path only the loop binds, mints and promotes such a volume, so it would never get a line. | M2 none → Bound (a replicated cluster-spec volume's first line) | `cmd/blockmaster/product_loop_guard.go` `requireProductLoop`; `cmd/blockmaster/main.go` `run` | `TestReplicatedClusterSpecWithTheProductLoopOffIsRefused`, `TestTheProductLoopGuardPassesWhatItShould` (`cmd/blockmaster/product_loop_guard_test.go`) | — (a startup configuration check). Limits: static `--topology` is not refused (its observation controller mints), and has no automatic failover in v1 | ACTIVE | +| `INV-AUTH-REPLICATED-SPEC-NEEDS-LOOP-001` | blockmaster refuses to start when its cluster spec holds a replicated volume it could never decide: one whose replication factor differs from --expected-slots-per-volume, or any while the lifecycle product loop is off (only that loop binds, mints and promotes it). | M2 none → Bound (a replicated cluster-spec volume's first line) | `cmd/blockmaster/product_loop_guard.go` `requireProductLoop`; `cmd/blockmaster/main.go` `run` | `TestReplicatedClusterSpecWithTheProductLoopOffIsRefused`, `TestTheProductLoopGuardPassesWhatItShould`, `TestAClusterSpecVolumeOfAnotherReplicationFactorIsRefused` (`cmd/blockmaster/product_loop_guard_test.go`) | — (a startup configuration check). Limits: static `--topology` is not refused (its observation controller mints), and has no automatic failover in v1 | 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` | `TestLayoutGrantedEpochIssuerSites`, `TestLayoutEpochEnumerationRejectsANewIssuer`, `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-RESTART-REISSUE-001` | A line records the primary process it was issued for (durable); a current primary reporting another process is re-issued its line at a new endpoint version, and a primary adopts no line issued for another process, so a restarted process never reuses the dead one's sessions. | M2 authority (RefreshEndpoint); M3 primary adoption | `core/authority/authority.go` `applyWithWorkspaceMove` (records the ask's or the source's incarnation); `core/authority/controller.go` `endpointStale`, `sameAsk`; `core/authority/workspace.go` `persistWorkspaceTimedLocked`; `core/authority/observation_store.go` `SlotFactAt`; `core/host/master/host.go` (the source); `core/host/volume/host.go` `applyFact` | `TestPublisher_RestartedPrimaryGetsANewEndpointVersion`, `TestPublisher_AskWithoutAProcessIsIssuedForTheReportedOne`, `TestTopologyController_RestartedPrimaryAtTheSameAddressIsReissued`, `TestTopologyController_QueuedRefreshIsReplacedForANewerProcess`, `TestTopologyController_UnnamedLineIsReissuedOnceForTheReportingProcess`, `TestWorkspaceLeaseWriteKeepsTheLinesIncarnationAcrossReload`, `TestObservationStore_SlotFactAtIsTheProcessAtThoseEndpoints` (`core/authority/restart_endpoint_version_test.go`); `TestLinesNameTheirPrimarysProcess`, `TestLineForTheTargetsEndpointsNamesTheTargetsProcess` (`core/host/master/line_incarnation_test.go`); `TestHost_ApplyFact_LineIssuedForAnotherProcessIsNotAdopted`, `TestHost_ApplyFact_UnnamedLineIsNotAdoptedWhereLinesNameTheirProcess` (`core/host/volume/line_incarnation_test.go`); `TestHostConfigAdoptsOnlyLinesNamingThisProcess` (`cmd/blockvolume/lines_name_their_process_test.go`); `TestRestartedPrimaryAtTheSameEpochIsAdmitted` (`core/replication/primary_restart_session_test.go`) | — | 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 | From 97942ab998697d750c22a4625f922c64e0329907 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 26 Nov 2026 04:18:00 -0800 Subject: [PATCH 05/14] fix(blockmaster): the startup checks read every cluster-spec entry's placement A placement-only replicated entry (no size_bytes) has a placement intent and no volume spec, so checking the volume specs let it through both refusals. Both now read the placement intents (DesiredRF), which every entry has; red tests for a placement-only RF2 on an expected-3 master and a placement-only RF3 with the loop off. Co-Authored-By: Claude Opus 5.5 --- .../cmd/blockmaster/product_loop_guard.go | 15 +++++--- .../blockmaster/product_loop_guard_test.go | 38 ++++++++++++++++++- seaweed-block/docs/design/invariants.md | 2 +- 3 files changed, 46 insertions(+), 9 deletions(-) diff --git a/seaweed-block/cmd/blockmaster/product_loop_guard.go b/seaweed-block/cmd/blockmaster/product_loop_guard.go index 3ad0c08b04..cac699e81d 100644 --- a/seaweed-block/cmd/blockmaster/product_loop_guard.go +++ b/seaweed-block/cmd/blockmaster/product_loop_guard.go @@ -18,21 +18,24 @@ import ( // A static --topology (whose observation controller mints) and // single-replica volumes are untouched. func requireProductLoop(interval time.Duration, expectedSlots int, spec clusterSpecImport) error { - for _, v := range spec.Volumes { - if v.ReplicationFactor > 1 && v.ReplicationFactor != expectedSlots { + // Every cluster-spec volume has a placement intent (a placement-only + // entry, without size_bytes, has no volume spec), so the placements are + // what is read. + for _, p := range spec.Placements { + if p.DesiredRF > 1 && p.DesiredRF != expectedSlots { return fmt.Errorf("cluster spec volume %s has replication factor %d but --expected-slots-per-volume is %d: "+ "the master decides replicated volumes of one slot count only (one replicated factor per cluster)", - v.VolumeID, v.ReplicationFactor, expectedSlots) + p.VolumeID, p.DesiredRF, expectedSlots) } } if interval > 0 { return nil } - for _, v := range spec.Volumes { - if v.ReplicationFactor > 1 { + for _, p := range spec.Placements { + if p.DesiredRF > 1 { return fmt.Errorf("cluster spec volume %s has replication factor %d but --lifecycle-product-loop-interval is 0 (off): "+ "with --cluster-spec a replicated volume is bound and promoted only by that loop; set --lifecycle-product-loop-interval (for example 100ms)", - v.VolumeID, v.ReplicationFactor) + p.VolumeID, p.DesiredRF) } } return nil diff --git a/seaweed-block/cmd/blockmaster/product_loop_guard_test.go b/seaweed-block/cmd/blockmaster/product_loop_guard_test.go index 0d89195247..78da729187 100644 --- a/seaweed-block/cmd/blockmaster/product_loop_guard_test.go +++ b/seaweed-block/cmd/blockmaster/product_loop_guard_test.go @@ -11,14 +11,22 @@ import ( // clusterSpecWithRF writes a cluster spec of three nodes and one volume v1 // with the given replication factor (placements on the first rf nodes). -func clusterSpecWithRF(t *testing.T, rf int) string { +func clusterSpecWithRF(t *testing.T, rf int) string { return clusterSpecText(t, rf, true) } + +// clusterSpecText is clusterSpecWithRF with or without size_bytes (without: +// a placement-only entry, which has a placement intent and no volume spec). +func clusterSpecText(t *testing.T, rf int, sized bool) string { t.Helper() var b strings.Builder b.WriteString("nodes:\n") for i := 1; i <= 3; i++ { b.WriteString(" - server_id: s" + string(rune('0'+i)) + "\n data_addr: 127.0.0.1:1" + string(rune('0'+i)) + "601\n ctrl_addr: 127.0.0.1:1" + string(rune('0'+i)) + "602\n") } - b.WriteString("volumes:\n - id: v1\n size_bytes: 268435456\n replication_factor: " + string(rune('0'+rf)) + "\n placements:\n") + b.WriteString("volumes:\n - id: v1\n") + if sized { + b.WriteString(" size_bytes: 268435456\n") + } + b.WriteString(" replication_factor: " + string(rune('0'+rf)) + "\n placements:\n") for i := 1; i <= rf; i++ { b.WriteString(" - server_id: s" + string(rune('0'+i)) + "\n replica_id: r" + string(rune('0'+i)) + "\n") } @@ -111,3 +119,29 @@ func TestAClusterSpecVolumeOfAnotherReplicationFactorIsRefused(t *testing.T) { t.Fatalf("an RF2 volume on an expected-2 master: refused: %v", err) } } + +// A placement-only replicated entry (no size_bytes: no volume spec, only a +// placement intent) is checked the same way: RF2 on an expected-3 master is +// refused, and RF3 with the loop off is refused. +func TestAPlacementOnlyClusterSpecVolumeIsChecked(t *testing.T) { + for _, c := range []struct { + name string + rf int + interval time.Duration + want string + }{ + {"rf2 on expected 3", 2, 100 * time.Millisecond, "--expected-slots-per-volume is 3"}, + {"rf3 with the loop off", 3, 0, "--lifecycle-product-loop-interval is 0"}, + } { + spec, err := loadClusterSpec(clusterSpecText(t, c.rf, false)) + if err != nil { + t.Fatalf("%s: %v", c.name, err) + } + if len(spec.Volumes) != 0 || len(spec.Placements) != 1 { + t.Fatalf("%s: fixture: %d volume specs, %d placements; want a placement-only entry", c.name, len(spec.Volumes), len(spec.Placements)) + } + if err := requireProductLoop(c.interval, 3, spec); err == nil || !strings.Contains(err.Error(), c.want) { + t.Fatalf("%s: %v; want a refusal with %q", c.name, err, c.want) + } + } +} diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 45deac2d62..ef597774e1 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -716,7 +716,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/frontend/chunkstore/layout/start.go` `Start`, `core/frontend/chunkstore/layout/claim.go` `Claim`; 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: with mutual TLS on, a node may act only for the server id bound to its certificate (`TERM-CALLER-001`; `auth.RequireNode` in `ReportHeartbeat`, `SubscribeAssignments`, `RenewWorkspaceLease`, `AckWorkspaceRevoked`, `QueryVolumeStatus`; `TestNodeActsOnlyForItsOwnServerID`, `core/host/master/auth_red_test.go`), and the registered-host check stays beside it (no NAT or proxy between volume and master in OSS); in development mode (plaintext on loopback, no role file) there is no 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-CALLER-ROLE-001` | With mutual TLS on, every blockmaster gRPC call (unary, and before every stream send) is decided by the caller's certificate and the current role file: an unknown caller is refused UNAUTHENTICATED, a role its method's rule does not admit PERMISSION_DENIED, a method without a rule always. | AUTHORITY: control API callers (people, tools, nodes) | `core/auth/identity.go` `Authenticator.PeerIdentity`, `Authenticator.Reload`; `core/auth/authorize.go` `Rule.Allows`, `UnaryInterceptor`, `StreamInterceptor`, `RequireNode`, `RequireRole`; `core/host/master/authz.go` `masterRules`, `serverAuth`; `core/rpc/link/tls.go` `ServerCredentials`, `ClientCredentials`; `cmd/blockmaster/auth.go` `authFlags.validate`, `authFlags.build` | `TestPeerIdentity`, `TestRoleFileReload` (`core/auth/identity_test.go`); `TestRuleAllows`, `TestRequireNodeAndRole`, `TestUnaryInterceptor`, `TestStreamEndsAtTheReloadThatRevokesItsCaller` (`core/auth/authorize_test.go`); `TestMasterAuthorizationTableCoversEveryMethod` (`core/host/master/authz_test.go`); `TestForcedMoveNeedsAnAdmin`, `TestNodeActsOnlyForItsOwnServerID` (`core/host/master/auth_red_test.go`); `TestMasterLinkMutualTLS` (`core/rpc/link/tls_test.go`); `TestAuthFlags` (`cmd/blockmaster/auth_flags_test.go`); `TestMasterTLSFlags` (`cmd/blockvolume/master_tls_test.go`). Also: a mutating operator or admin method writes its audit attempt before it runs or is refused as audit unavailable (`Rule.Strict`; `TestMasterOperatorMethodsAreStrict` (inverted: a new operator or admin method fails unless strict or named with its reason), `core/host/master/authz_test.go`; `TestStrictCallsNeedTheirAttemptLine`, `core/auth/strict_audit_test.go`), node calls never wait on the audit log; a reload that removes a caller, or changes its role so the method's rule no longer admits it, ends its open streams at the reload; a forced move needs an admin; plaintext listens only on loopback without a role file (development mode). Limits: the audit log records outcomes and decides nothing; the volume process's own HTTP routes stay loopback-only and unauthenticated. | `AuthLease` (exhaustive run pending) | ACTIVE | -| `INV-AUTH-REPLICATED-SPEC-NEEDS-LOOP-001` | blockmaster refuses to start when its cluster spec holds a replicated volume it could never decide: one whose replication factor differs from --expected-slots-per-volume, or any while the lifecycle product loop is off (only that loop binds, mints and promotes it). | M2 none → Bound (a replicated cluster-spec volume's first line) | `cmd/blockmaster/product_loop_guard.go` `requireProductLoop`; `cmd/blockmaster/main.go` `run` | `TestReplicatedClusterSpecWithTheProductLoopOffIsRefused`, `TestTheProductLoopGuardPassesWhatItShould`, `TestAClusterSpecVolumeOfAnotherReplicationFactorIsRefused` (`cmd/blockmaster/product_loop_guard_test.go`) | — (a startup configuration check). Limits: static `--topology` is not refused (its observation controller mints), and has no automatic failover in v1 | ACTIVE | +| `INV-AUTH-REPLICATED-SPEC-NEEDS-LOOP-001` | blockmaster refuses to start when its cluster spec holds a replicated volume it could never decide: one whose replication factor differs from --expected-slots-per-volume, or any while the lifecycle product loop is off (only that loop binds, mints and promotes it). | M2 none → Bound (a replicated cluster-spec volume's first line) | `cmd/blockmaster/product_loop_guard.go` `requireProductLoop`; `cmd/blockmaster/main.go` `run` | `TestReplicatedClusterSpecWithTheProductLoopOffIsRefused`, `TestTheProductLoopGuardPassesWhatItShould`, `TestAClusterSpecVolumeOfAnotherReplicationFactorIsRefused`, `TestAPlacementOnlyClusterSpecVolumeIsChecked` (`cmd/blockmaster/product_loop_guard_test.go`) | — (a startup configuration check). Limits: static `--topology` is not refused (its observation controller mints), and has no automatic failover in v1 | 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` | `TestLayoutGrantedEpochIssuerSites`, `TestLayoutEpochEnumerationRejectsANewIssuer`, `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-RESTART-REISSUE-001` | A line records the primary process it was issued for (durable); a current primary reporting another process is re-issued its line at a new endpoint version, and a primary adopts no line issued for another process, so a restarted process never reuses the dead one's sessions. | M2 authority (RefreshEndpoint); M3 primary adoption | `core/authority/authority.go` `applyWithWorkspaceMove` (records the ask's or the source's incarnation); `core/authority/controller.go` `endpointStale`, `sameAsk`; `core/authority/workspace.go` `persistWorkspaceTimedLocked`; `core/authority/observation_store.go` `SlotFactAt`; `core/host/master/host.go` (the source); `core/host/volume/host.go` `applyFact` | `TestPublisher_RestartedPrimaryGetsANewEndpointVersion`, `TestPublisher_AskWithoutAProcessIsIssuedForTheReportedOne`, `TestTopologyController_RestartedPrimaryAtTheSameAddressIsReissued`, `TestTopologyController_QueuedRefreshIsReplacedForANewerProcess`, `TestTopologyController_UnnamedLineIsReissuedOnceForTheReportingProcess`, `TestWorkspaceLeaseWriteKeepsTheLinesIncarnationAcrossReload`, `TestObservationStore_SlotFactAtIsTheProcessAtThoseEndpoints` (`core/authority/restart_endpoint_version_test.go`); `TestLinesNameTheirPrimarysProcess`, `TestLineForTheTargetsEndpointsNamesTheTargetsProcess` (`core/host/master/line_incarnation_test.go`); `TestHost_ApplyFact_LineIssuedForAnotherProcessIsNotAdopted`, `TestHost_ApplyFact_UnnamedLineIsNotAdoptedWhereLinesNameTheirProcess` (`core/host/volume/line_incarnation_test.go`); `TestHostConfigAdoptsOnlyLinesNamingThisProcess` (`cmd/blockvolume/lines_name_their_process_test.go`); `TestRestartedPrimaryAtTheSameEpochIsAdmitted` (`core/replication/primary_restart_session_test.go`) | — | 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 | From 48e77c05b8ea2f6ad7a96f31752939c8bc7f9ee9 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 26 Nov 2026 04:19:30 -0800 Subject: [PATCH 06/14] fix(master): CreateVolume refuses a replicated volume while the product loop is off Only the lifecycle product loop binds, mints and promotes a replicated lifecycle volume. With --lifecycle-product-loop-interval at 0 a replicated create was admitted (its factor matching) and never got a primary. blockmaster now tells the master whether its loop runs (Config.LifecycleProductLoop), and CreateVolume refuses RF > 1 while it does not, naming the flag; RF1 creates are admitted either way. Co-Authored-By: Claude Opus 5.5 --- seaweed-block/cmd/blockmaster/main.go | 1 + .../host/master/create_rf_mismatch_test.go | 29 ++++++++++++++++++- seaweed-block/core/host/master/host.go | 12 ++++++-- .../host/master/lifecycle_service_test.go | 1 + seaweed-block/core/host/master/services.go | 5 ++++ seaweed-block/docs/design/invariants.md | 2 +- 6 files changed, 45 insertions(+), 5 deletions(-) diff --git a/seaweed-block/cmd/blockmaster/main.go b/seaweed-block/cmd/blockmaster/main.go index 20d4a3757f..8a969f1aa6 100644 --- a/seaweed-block/cmd/blockmaster/main.go +++ b/seaweed-block/cmd/blockmaster/main.go @@ -245,6 +245,7 @@ func run(f flags) int { ControllerConfig: authority.TopologyControllerConfig{ExpectedSlotsPerVolume: f.expectedSlotsPerVol}, WorkspaceMaxClockSkew: f.workspaceMaxClockSkew, FailbackRuntimeRPC: f.failbackRuntimeRPC, + LifecycleProductLoop: f.lifecycleLoop > 0, FrontendPublicationRuntimeHTTP: f.frontendPublicationRuntimeHTTP, FrontendPublicationRuntimeListen: f.frontendPublicationRuntimeListen, StrictJournalIsolation: f.strictJournalIsolation, diff --git a/seaweed-block/core/host/master/create_rf_mismatch_test.go b/seaweed-block/core/host/master/create_rf_mismatch_test.go index 9abb05bb75..d86109d5b0 100644 --- a/seaweed-block/core/host/master/create_rf_mismatch_test.go +++ b/seaweed-block/core/host/master/create_rf_mismatch_test.go @@ -2,6 +2,7 @@ package master import ( "context" + "strings" "testing" "time" @@ -16,7 +17,7 @@ import ( // RF3 and an RF1 create are admitted; and every existing volume keeps failing // over (no volume of another slot count can stop the controller's decisions). func TestAnRF2CreateOnAnRF3MasterIsRefusedAndFailoverContinues(t *testing.T) { - h := newBootGraceMaster(t, Config{ControllerConfig: authority.TopologyControllerConfig{PrimaryBootGrace: 200 * time.Millisecond}}) + h := newBootGraceMaster(t, Config{LifecycleProductLoop: true, ControllerConfig: authority.TopologyControllerConfig{PrimaryBootGrace: 200 * time.Millisecond}}) defer closeTestMaster(t, h) svc := newServices(h) _, err := svc.CreateVolume(context.Background(), &control.CreateVolumeRequest{VolumeId: "v-rf2", SizeBytes: 1 << 20, ReplicationFactor: 2}) @@ -38,3 +39,29 @@ func TestAnRF2CreateOnAnRF3MasterIsRefusedAndFailoverContinues(t *testing.T) { unsupportedTick(t, h, ineligible) expectFailoverToR2(t, h, "an existing RF3 volume after the refused RF2 create") } + +// The third door: a replicated volume created while the lifecycle product +// loop is off (which alone binds and promotes it) would never get a primary, +// so CreateVolume refuses it naming the flag; with the loop on the same +// create is admitted, and an RF1 create is admitted either way. +func TestAReplicatedCreateWithTheProductLoopOffIsRefused(t *testing.T) { + for _, loop := range []bool{false, true} { + h, err := New(Config{AuthorityStoreDir: t.TempDir(), LifecycleStoreDir: t.TempDir(), Listen: "127.0.0.1:0", LifecycleProductLoop: loop}) + if err != nil { + t.Fatal(err) + } + h.Start() + svc := newServices(h) + _, err = svc.CreateVolume(context.Background(), &control.CreateVolumeRequest{VolumeId: "v-rf3", SizeBytes: 1 << 20, ReplicationFactor: 3}) + if loop && err != nil { + t.Fatalf("RF3 create with the loop on: %v", err) + } + if !loop && (status.Code(err) != codes.FailedPrecondition || !strings.Contains(err.Error(), "--lifecycle-product-loop-interval")) { + t.Fatalf("RF3 create with the loop off: %v; want FailedPrecondition naming the flag", err) + } + if _, err := svc.CreateVolume(context.Background(), &control.CreateVolumeRequest{VolumeId: "v-rf1", SizeBytes: 1 << 20, ReplicationFactor: 1}); err != nil { + t.Fatalf("RF1 create (loop %v): %v", loop, err) + } + closeTestMaster(t, h) + } +} diff --git a/seaweed-block/core/host/master/host.go b/seaweed-block/core/host/master/host.go index 0b0aedd3aa..42493cafcd 100644 --- a/seaweed-block/core/host/master/host.go +++ b/seaweed-block/core/host/master/host.go @@ -68,6 +68,12 @@ type Config struct { // ControllerConfig tunes controller knobs (retry window etc). ControllerConfig authority.TopologyControllerConfig + // LifecycleProductLoop reports that the host's lifecycle product loop + // runs (blockmaster --lifecycle-product-loop-interval above 0). Only + // that loop binds, mints and promotes a replicated lifecycle volume, so + // CreateVolume refuses a replicated volume while it is off. + LifecycleProductLoop bool + // LifecycleStoreDir, when non-empty, opens product lifecycle // registration stores (desired volumes, node inventory, placement // intents). This is read-only composition for G9D: these stores do @@ -135,7 +141,7 @@ type Host struct { probeSlots slotServers // replica -> server, for the round cfg Config attest *storeAttestations // primaries' attested write-ACK stores - healthMu sync.Mutex // orders replica health events with their accepted heartbeats (#128 rule 6) + healthMu sync.Mutex // orders replica health events with their accepted heartbeats (#128 rule 6) log *log.Logger boot *bootstrap.DurableAuthorityBootstrap ctrl *authority.TopologyController @@ -159,8 +165,8 @@ type Host struct { // without a line being published there. Until the line reaches it, those // survivors refuse the primary, so the gate keeps trying to heal it. fencePending map[string]uint64 - cancel context.CancelFunc - wg sync.WaitGroup + cancel context.CancelFunc + wg sync.WaitGroup started atomic.Bool } diff --git a/seaweed-block/core/host/master/lifecycle_service_test.go b/seaweed-block/core/host/master/lifecycle_service_test.go index 6fa79e0c42..491785d2ba 100644 --- a/seaweed-block/core/host/master/lifecycle_service_test.go +++ b/seaweed-block/core/host/master/lifecycle_service_test.go @@ -92,6 +92,7 @@ func TestRestoreCreateVolumePersistsRequestBeforeTargetAndHealsRetry(t *testing. if _, ok := h.Lifecycle().Volumes.GetVolume("net-target"); ok { t.Fatal("RF2 restore created a target record") } + h.cfg.LifecycleProductLoop = true // a replicated create needs the product loop if _, err := svc.CreateVolume(context.Background(), &control.CreateVolumeRequest{VolumeId: "net-source", SizeBytes: 1 << 20, ReplicationFactor: 3}); err != nil { t.Fatal(err) } diff --git a/seaweed-block/core/host/master/services.go b/seaweed-block/core/host/master/services.go index 60050718d5..5356b879ce 100644 --- a/seaweed-block/core/host/master/services.go +++ b/seaweed-block/core/host/master/services.go @@ -75,6 +75,11 @@ func (s *services) CreateVolume(ctx context.Context, req *control.CreateVolumeRe // refuses the whole decision when one differs, so a volume of another // replication factor would stop every replicated volume's assignment and // failover. Single-replica volumes never reach that check. + // A replicated lifecycle volume is bound, minted and promoted only by the + // lifecycle product loop: with it off the volume never gets a primary. + if spec.ReplicationFactor > 1 && !s.host.cfg.LifecycleProductLoop { + return nil, status.Errorf(codes.FailedPrecondition, "create volume: %s has replication factor %d but --lifecycle-product-loop-interval is 0 (off): a replicated volume is bound and promoted only by that loop; set --lifecycle-product-loop-interval (for example 100ms)", spec.VolumeID, spec.ReplicationFactor) + } if c := s.host.ctrl; c != nil && spec.ReplicationFactor > 1 && spec.ReplicationFactor != c.ExpectedSlotsPerVolume() { return nil, status.Errorf(codes.FailedPrecondition, "create volume: %s has replication factor %d, but this master decides replicated volumes of %d replicas (--expected-slots-per-volume); one replicated factor per cluster", spec.VolumeID, spec.ReplicationFactor, c.ExpectedSlotsPerVolume()) } diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 3bf9e3e97f..dfce6f9167 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -716,7 +716,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/frontend/chunkstore/layout/start.go` `Start`, `core/frontend/chunkstore/layout/claim.go` `Claim`; 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: with mutual TLS on, a node may act only for the server id bound to its certificate (`TERM-CALLER-001`; `auth.RequireNode` in `ReportHeartbeat`, `SubscribeAssignments`, `RenewWorkspaceLease`, `AckWorkspaceRevoked`, `QueryVolumeStatus`; `TestNodeActsOnlyForItsOwnServerID`, `core/host/master/auth_red_test.go`), and the registered-host check stays beside it (no NAT or proxy between volume and master in OSS); in development mode (plaintext on loopback, no role file) there is no 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-CALLER-ROLE-001` | With mutual TLS on, every blockmaster gRPC call (unary, and before every stream send) is decided by the caller's certificate and the current role file: an unknown caller is refused UNAUTHENTICATED, a role its method's rule does not admit PERMISSION_DENIED, a method without a rule always. | AUTHORITY: control API callers (people, tools, nodes) | `core/auth/identity.go` `Authenticator.PeerIdentity`, `Authenticator.Reload`; `core/auth/authorize.go` `Rule.Allows`, `UnaryInterceptor`, `StreamInterceptor`, `RequireNode`, `RequireRole`; `core/host/master/authz.go` `masterRules`, `serverAuth`; `core/rpc/link/tls.go` `ServerCredentials`, `ClientCredentials`; `cmd/blockmaster/auth.go` `authFlags.validate`, `authFlags.build` | `TestPeerIdentity`, `TestRoleFileReload` (`core/auth/identity_test.go`); `TestRuleAllows`, `TestRequireNodeAndRole`, `TestUnaryInterceptor`, `TestStreamEndsAtTheReloadThatRevokesItsCaller` (`core/auth/authorize_test.go`); `TestMasterAuthorizationTableCoversEveryMethod` (`core/host/master/authz_test.go`); `TestForcedMoveNeedsAnAdmin`, `TestNodeActsOnlyForItsOwnServerID` (`core/host/master/auth_red_test.go`); `TestMasterLinkMutualTLS` (`core/rpc/link/tls_test.go`); `TestAuthFlags` (`cmd/blockmaster/auth_flags_test.go`); `TestMasterTLSFlags` (`cmd/blockvolume/master_tls_test.go`). Also: a mutating operator or admin method writes its audit attempt before it runs or is refused as audit unavailable (`Rule.Strict`; `TestMasterOperatorMethodsAreStrict` (inverted: a new operator or admin method fails unless strict or named with its reason), `core/host/master/authz_test.go`; `TestStrictCallsNeedTheirAttemptLine`, `core/auth/strict_audit_test.go`), node calls never wait on the audit log; a reload that removes a caller, or changes its role so the method's rule no longer admits it, ends its open streams at the reload; a forced move needs an admin; plaintext listens only on loopback without a role file (development mode). Limits: the audit log records outcomes and decides nothing; the volume process's own HTTP routes stay loopback-only and unauthenticated. | `AuthLease` (exhaustive run pending) | ACTIVE | -| `INV-AUTH-ONE-REPLICATED-FACTOR-001` | A replicated volume is created only with the master's one replica-slot count (--expected-slots-per-volume): CreateVolume refuses another replication factor above 1, since one mismatched volume would stop the controller's decisions for every volume. | M2 none → Bound (a created replicated volume's first line) | `core/host/master/services.go` `CreateVolume`; `core/authority/controller.go` `ExpectedSlotsPerVolume`, `validateVolumeTopology` | `TestAnRF2CreateOnAnRF3MasterIsRefusedAndFailoverContinues` (`core/host/master/create_rf_mismatch_test.go`) | — (an admission check). Limits: single-replica volumes are admitted at any slot count (they never reach the check); a cluster spec or topology file with a mismatched volume is not checked at start | ACTIVE | +| `INV-AUTH-ONE-REPLICATED-FACTOR-001` | CreateVolume admits a replicated volume only if the master can decide it: its replication factor equals the master's one slot count (--expected-slots-per-volume) and the lifecycle product loop runs (only that loop binds, mints and promotes it). | M2 none → Bound (a created replicated volume's first line) | `core/host/master/services.go` `CreateVolume`; `core/host/master/host.go` `Config.LifecycleProductLoop`; `core/authority/controller.go` `ExpectedSlotsPerVolume`, `validateVolumeTopology` | `TestAnRF2CreateOnAnRF3MasterIsRefusedAndFailoverContinues`, `TestAReplicatedCreateWithTheProductLoopOffIsRefused` (`core/host/master/create_rf_mismatch_test.go`) | — (an admission check). Limits: single-replica volumes are admitted at any slot count (they never reach the check); a cluster spec or topology file with a mismatched volume is not checked at start | 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` | `TestLayoutGrantedEpochIssuerSites`, `TestLayoutEpochEnumerationRejectsANewIssuer`, `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-RESTART-REISSUE-001` | A line records the primary process it was issued for (durable); a current primary reporting another process is re-issued its line at a new endpoint version, and a primary adopts no line issued for another process, so a restarted process never reuses the dead one's sessions. | M2 authority (RefreshEndpoint); M3 primary adoption | `core/authority/authority.go` `applyWithWorkspaceMove` (records the ask's or the source's incarnation); `core/authority/controller.go` `endpointStale`, `sameAsk`; `core/authority/workspace.go` `persistWorkspaceTimedLocked`; `core/authority/observation_store.go` `SlotFactAt`; `core/host/master/host.go` (the source); `core/host/volume/host.go` `applyFact` | `TestPublisher_RestartedPrimaryGetsANewEndpointVersion`, `TestPublisher_AskWithoutAProcessIsIssuedForTheReportedOne`, `TestTopologyController_RestartedPrimaryAtTheSameAddressIsReissued`, `TestTopologyController_QueuedRefreshIsReplacedForANewerProcess`, `TestTopologyController_UnnamedLineIsReissuedOnceForTheReportingProcess`, `TestWorkspaceLeaseWriteKeepsTheLinesIncarnationAcrossReload`, `TestObservationStore_SlotFactAtIsTheProcessAtThoseEndpoints` (`core/authority/restart_endpoint_version_test.go`); `TestLinesNameTheirPrimarysProcess`, `TestLineForTheTargetsEndpointsNamesTheTargetsProcess` (`core/host/master/line_incarnation_test.go`); `TestHost_ApplyFact_LineIssuedForAnotherProcessIsNotAdopted`, `TestHost_ApplyFact_UnnamedLineIsNotAdoptedWhereLinesNameTheirProcess` (`core/host/volume/line_incarnation_test.go`); `TestHostConfigAdoptsOnlyLinesNamingThisProcess` (`cmd/blockvolume/lines_name_their_process_test.go`); `TestRestartedPrimaryAtTheSameEpochIsAdmitted` (`core/replication/primary_restart_session_test.go`) | — | 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 | From 29927c478cca8c8333116106d33a206082307c62 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 26 Nov 2026 04:25:57 -0800 Subject: [PATCH 07/14] test(blockmaster): the start refusal runs blockmaster as a bounded child The refusal test ran run() in a goroutine and could leave it serving on a hang. It now re-executes the test binary as a helper process under a 10 s context (killed at the deadline and joined; exec closes its pipes). Co-Authored-By: Claude Opus 5.5 --- .../blockmaster/product_loop_guard_test.go | 67 ++++++++++++------- 1 file changed, 42 insertions(+), 25 deletions(-) diff --git a/seaweed-block/cmd/blockmaster/product_loop_guard_test.go b/seaweed-block/cmd/blockmaster/product_loop_guard_test.go index 78da729187..3d201b78c4 100644 --- a/seaweed-block/cmd/blockmaster/product_loop_guard_test.go +++ b/seaweed-block/cmd/blockmaster/product_loop_guard_test.go @@ -1,8 +1,11 @@ package main import ( - "io" + "context" + "errors" + "fmt" "os" + "os/exec" "path/filepath" "strings" "testing" @@ -37,39 +40,53 @@ func clusterSpecText(t *testing.T, rf int, sized bool) string { return p } +// guardHelperEnv carries a blockmaster command line (fields separated by +// guardHelperSep) to the helper process below. +const ( + guardHelperEnv = "SWB_BLOCKMASTER_GUARD_HELPER_ARGS" + guardHelperSep = "\x1f" +) + +// TestGuardHelperProcess is not a test on its own: re-executed by +// TestReplicatedClusterSpecWithTheProductLoopOffIsRefused, it runs +// blockmaster's run with the given arguments and exits with its code. +func TestGuardHelperProcess(t *testing.T) { + args := os.Getenv(guardHelperEnv) + if args == "" { + t.Skip("helper process only") + } + f, err := parseFlags(strings.Split(args, guardHelperSep)) + if err != nil { + fmt.Fprintln(os.Stderr, err) + os.Exit(64) + } + os.Exit(run(f)) +} + // A replicated cluster-spec volume with the product loop off is refused at -// start, naming the flag, before anything is opened (run returns 2). +// start, naming the flag, before anything is opened (exit 2). blockmaster +// runs as a bounded child: without the guard it would start and serve, so +// the child is killed at the deadline and joined (exec closes its pipes). func TestReplicatedClusterSpecWithTheProductLoopOffIsRefused(t *testing.T) { - f, err := parseFlags([]string{ + args := []string{ "--authority-store", filepath.Join(t.TempDir(), "authority"), "--lifecycle-store", filepath.Join(t.TempDir(), "lifecycle"), "--cluster-spec", clusterSpecWithRF(t, 3), "--expected-slots-per-volume", "3", "--listen", "127.0.0.1:0", - }) - if err != nil { - t.Fatal(err) } - r, w, err := os.Pipe() - if err != nil { - t.Fatal(err) + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + t.Cleanup(cancel) + cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestGuardHelperProcess$") + cmd.Env = append(os.Environ(), guardHelperEnv+"="+strings.Join(args, guardHelperSep)) + cmd.WaitDelay = 5 * time.Second + out, err := cmd.CombinedOutput() // returns once the child exited (or was killed) and its pipes closed + if ctx.Err() != nil { + t.Fatalf("blockmaster started with a replicated cluster spec and the product loop off (killed at the deadline):\n%s", out) } - saved := os.Stderr - os.Stderr = w - done := make(chan int, 1) - go func() { done <- run(f) }() // without the guard run starts and serves - var code int - select { - case code = <-done: - case <-time.After(10 * time.Second): - os.Stderr = saved - t.Fatal("blockmaster started with a replicated cluster spec and the product loop off") - } - os.Stderr = saved - w.Close() - out, _ := io.ReadAll(r) - if code != 2 || !strings.Contains(string(out), "--lifecycle-product-loop-interval") || !strings.Contains(string(out), "v1") { - t.Fatalf("run=%d, stderr %q; want 2 and the flag named", code, out) + var exit *exec.ExitError + if !errors.As(err, &exit) || exit.ExitCode() != 2 || !strings.Contains(string(out), "--lifecycle-product-loop-interval") || !strings.Contains(string(out), "v1") { + t.Fatalf("exit %v, output %q; want exit 2 and the flag named", err, out) } } From 49389c8bd5118f2f4f687a8cae9e797fe9703258 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 26 Nov 2026 04:41:21 -0800 Subject: [PATCH 08/14] test(master): the G15c create test runs on a master that decides RF2 volumes with its loop on Co-Authored-By: Claude Opus 5.5 --- seaweed-block/core/host/master/lifecycle_service_test.go | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/seaweed-block/core/host/master/lifecycle_service_test.go b/seaweed-block/core/host/master/lifecycle_service_test.go index 491785d2ba..f2ee6b0695 100644 --- a/seaweed-block/core/host/master/lifecycle_service_test.go +++ b/seaweed-block/core/host/master/lifecycle_service_test.go @@ -6,6 +6,7 @@ import ( "reflect" "testing" + "github.com/seaweedfs/seaweed-block/core/authority" "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" "github.com/seaweedfs/seaweed-block/core/lifecycle" control "github.com/seaweedfs/seaweed-block/core/rpc/control" @@ -139,8 +140,11 @@ func TestCreateVolumeRetriesFilerCreateBeforeStoreReady(t *testing.T) { } func TestG15c_LifecycleService_CreateVolumePersistsDesiredIntent(t *testing.T) { - h := newTestMaster(t, t.TempDir()) + // An RF2 volume is admitted by a master that decides RF2 volumes and + // runs its product loop (#646). + h := newTestMasterWithControllerConfig(t, t.TempDir(), authority.TopologyControllerConfig{ExpectedSlotsPerVolume: 2}) defer closeTestMaster(t, h) + h.cfg.LifecycleProductLoop = true svc := newServices(h) resp, err := svc.CreateVolume(context.Background(), &control.CreateVolumeRequest{ From a6a2d4433ce572402d1ee6fc719dd083caeec163 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 26 Nov 2026 05:42:55 -0800 Subject: [PATCH 09/14] fix(chunkstore): a volume delete re-run completes on a deleted or interrupted volume BCatalog.DeleteVolume finds the volumes to release by reading every root the volume's HEAD names (foreignOwners). A deleted HEAD still names its roots, whose objects the first run deleted, so the documented re-run ("a re-run on a deleted volume sweeps any object that landed late") failed with "layout: object missing"; so did the re-run of a delete interrupted after it began deleting objects. layout.DeleteVolume deletes a volume's objects only after it released the volume from every source, so on a deleting or deleted HEAD a root whose objects are gone has nothing left to release. foreignOwners now skips exactly that: layout.ErrMissing on a deleting or deleted HEAD. A corrupt object, an I/O error, and a missing root of a live HEAD stay errors. The skipped roots are returned, and volume-delete reports them (already_deleted_roots). Co-Authored-By: Claude Opus 5.5 --- .../cmd/sw-block/chunk_volume_delete.go | 15 +- .../core/frontend/chunkstore/catalog_b.go | 41 ++-- .../frontend/chunkstore/catalog_b_test.go | 2 +- .../chunkstore/catalog_delete_rerun_test.go | 180 ++++++++++++++++++ .../core/frontend/chunkstore/fake_test.go | 8 + .../frontend/chunkstore/head_readers_test.go | 2 +- .../layout_objects_integration_test.go | 2 +- seaweed-block/docs/design/invariants.md | 2 +- 8 files changed, 234 insertions(+), 18 deletions(-) create mode 100644 seaweed-block/core/frontend/chunkstore/catalog_delete_rerun_test.go diff --git a/seaweed-block/cmd/sw-block/chunk_volume_delete.go b/seaweed-block/cmd/sw-block/chunk_volume_delete.go index da2f042e2d..bfcb66490c 100644 --- a/seaweed-block/cmd/sw-block/chunk_volume_delete.go +++ b/seaweed-block/cmd/sw-block/chunk_volume_delete.go @@ -44,10 +44,21 @@ func chunkVolumeDelete(args []string, stdout, stderr io.Writer) int { } defer conn.Close() auth := &masterAuthority{lc: control.NewLifecycleServiceClient(conn), req: &control.MarkVolumeDeletingRequest{VolumeId: ref.Name, Token: requestID}} - if err := cat.DeleteVolume(ctx, ref, auth); err != nil { + skipped, err := cat.DeleteVolume(ctx, ref, auth) + if err != nil { return nil, err } - return map[string]string{"volume": ref.Dir(), "state": "deleted"}, nil + out := map[string]any{"volume": ref.Dir(), "state": "deleted"} + if len(skipped) > 0 { + // Roots HEAD names whose objects an earlier run already deleted + // (after releasing every source): reported, not read. + names := make([]string, 0, len(skipped)) + for _, rn := range skipped { + names = append(names, rn.String()) + } + out["already_deleted_roots"] = names + } + return out, nil }) } diff --git a/seaweed-block/core/frontend/chunkstore/catalog_b.go b/seaweed-block/core/frontend/chunkstore/catalog_b.go index c10d8e7462..29545e8ed3 100644 --- a/seaweed-block/core/frontend/chunkstore/catalog_b.go +++ b/seaweed-block/core/frontend/chunkstore/catalog_b.go @@ -187,38 +187,48 @@ func (c *BCatalog) ReleaseTarget(ctx context.Context, src, target VolumeRef) (la // released from are the volumes its roots name chunks of (read from its // references, never from a name given); its objects are every pool, // segment and root entry in its directory, listed after HEAD is deleting. -// A re-run on a deleted volume sweeps any object that landed late. -func (c *BCatalog) DeleteVolume(ctx context.Context, v VolumeRef, auth layout.DeleteAuthority) error { +// A re-run on a deleted volume sweeps any object that landed late, and a +// re-run after an interruption at any step completes it. It returns the +// roots HEAD names that were already deleted and so were not read (see +// foreignOwners). +func (c *BCatalog) DeleteVolume(ctx context.Context, v VolumeRef, auth layout.DeleteAuthority) ([]layout.RootName, error) { s, r, err := c.open(v) if err != nil { - return err + return nil, err } h, found, err := s.ReadHead(ctx) if err != nil { - return err + return nil, err } if !found { - return layout.ErrHeadAbsent + return nil, layout.ErrHeadAbsent } - owners, err := foreignOwners(ctx, r, h) + owners, skipped, err := foreignOwners(ctx, r, h) if err != nil { - return err + return nil, err } var sources []layout.HeadStore for _, o := range owners { ss, err := c.Store(o) if err != nil { - return err + return nil, err } sources = append(sources, ss) } list := func(ctx context.Context) ([]string, error) { return c.listObjects(ctx, v) } - return layout.DeleteVolume(ctx, s, auth, v.ID, sources, s, list) + return skipped, layout.DeleteVolume(ctx, s, auth, v.ID, sources, s, list) } // foreignOwners returns the volumes, other than h's own, whose chunks a // root in h names, from the references themselves. -func foreignOwners(ctx context.Context, r *layout.Reader, h layout.Head) ([]VolumeRef, error) { +// +// A delete removes a volume's root objects only after it released the +// volume from every source (layout.DeleteVolume's order), so on a HEAD that +// is deleting or deleted a root whose objects are already gone +// (layout.ErrMissing) has nothing left to release: it is skipped and +// returned. Anything else (a corrupt object, an I/O error), and a missing +// root of a live HEAD, is an error. +func foreignOwners(ctx context.Context, r *layout.Reader, h layout.Head) ([]VolumeRef, []layout.RootName, error) { roots := map[layout.RootName]bool{} if h.Current != nil { roots[*h.Current] = true @@ -226,11 +236,17 @@ func foreignOwners(ctx context.Context, r *layout.Reader, h layout.Head) ([]Volu for _, s := range h.Snapshots { roots[s.Root] = true } + deleting := h.State == layout.StateDeleting || h.State == layout.StateDeleted seen := map[VolumeRef]bool{} + var skipped []layout.RootName for rn := range roots { refs, err := rootRefs(ctx, r, rn) if err != nil { - return nil, err + if deleting && errors.Is(err, layout.ErrMissing) { + skipped = append(skipped, rn) + continue + } + return nil, nil, err } for _, ref := range refs { if ref.OwnerID != h.VolumeID { @@ -243,7 +259,8 @@ func foreignOwners(ctx context.Context, r *layout.Reader, h layout.Head) ([]Volu out = append(out, o) } sort.Slice(out, func(a, b int) bool { return out[a].Dir() < out[b].Dir() }) - return out, nil + sort.Slice(skipped, func(a, b int) bool { return skipped[a].String() < skipped[b].String() }) + return out, skipped, nil } // rootRefs returns every chunk reference the root names. diff --git a/seaweed-block/core/frontend/chunkstore/catalog_b_test.go b/seaweed-block/core/frontend/chunkstore/catalog_b_test.go index 9e5c030e29..5dfcf447e9 100644 --- a/seaweed-block/core/frontend/chunkstore/catalog_b_test.go +++ b/seaweed-block/core/frontend/chunkstore/catalog_b_test.go @@ -112,7 +112,7 @@ func TestBCatalog_RestoreThenDeleteTheTarget(t *testing.T) { t.Fatalf("delete a depended-on snapshot: %v; want ErrHasDependents", err) } - if err := c.DeleteVolume(ctx, tgt, okDeleteAuthority{}); err != nil { + if _, err := c.DeleteVolume(ctx, tgt, okDeleteAuthority{}); err != nil { t.Fatalf("delete the target: %v", err) } if h, _, err := ts.ReadHead(ctx); err != nil || h.State != layout.StateDeleted { diff --git a/seaweed-block/core/frontend/chunkstore/catalog_delete_rerun_test.go b/seaweed-block/core/frontend/chunkstore/catalog_delete_rerun_test.go new file mode 100644 index 0000000000..3d1692b5eb --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/catalog_delete_rerun_test.go @@ -0,0 +1,180 @@ +package chunkstore + +import ( + "context" + "errors" + "strings" + "testing" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" +) + +// rerunFixture is a source with a snapshot and a restore target that +// depends on it (so the target's delete releases a source), on fresh fakes. +func rerunFixture(t *testing.T) (*BCatalog, *fakeFiler, *fakeBlobs, VolumeRef, VolumeRef) { + t.Helper() + ctx := context.Background() + f, b := newFakeFiler(), newFakeBlobs() + c, err := NewBCatalog(f, b, "/blocks") + if err != nil { + t.Fatal(err) + } + src, tgt := newRef(t, "src"), newRef(t, "t") + if _, err := c.CreateVolume(ctx, src, layout.Geometry{SizeBytes: 64 * 4096, BlockSize: 4096, ChunkBytes: 4 * 4096}); err != nil { + t.Fatal(err) + } + commitSnapshot(t, c, src, []byte("source chunk"), "daily") + if _, err := c.Restore(ctx, src, "daily", tgt); err != nil { + t.Fatalf("restore: %v", err) + } + return c, f, b, src, tgt +} + +// requireDeletedAndReleased: the target's HEAD is deleted, none of its +// objects is left, and the source's snapshot no longer has it as a dependent. +func requireDeletedAndReleased(t *testing.T, c *BCatalog, src, tgt VolumeRef) { + t.Helper() + ctx := context.Background() + ts, _, err := c.open(tgt) + if err != nil { + t.Fatal(err) + } + if h, _, err := ts.ReadHead(ctx); err != nil || h.State != layout.StateDeleted { + t.Fatalf("target HEAD %+v %v; want deleted", h, err) + } + if objs, err := c.listObjects(ctx, tgt); err != nil || len(objs) != 0 { + t.Fatalf("target objects %v %v; want none", objs, err) + } + if _, err := c.DeleteSnapshot(ctx, src, "daily"); err != nil { + t.Fatalf("the source's snapshot is still held: %v", err) + } +} + +// A re-run of a completed delete succeeds: HEAD stays deleted, and the roots +// HEAD still names (whose objects the first run deleted) are reported. +func TestBCatalog_DeleteRerunOnADeletedVolumeSucceeds(t *testing.T) { + ctx := context.Background() + c, _, _, src, tgt := rerunFixture(t) + if skipped, err := c.DeleteVolume(ctx, tgt, okDeleteAuthority{}); err != nil || len(skipped) != 0 { + t.Fatalf("first delete: skipped=%v err=%v", skipped, err) + } + skipped, err := c.DeleteVolume(ctx, tgt, okDeleteAuthority{}) + if err != nil { + t.Fatalf("re-run on a deleted volume: %v", err) + } + if len(skipped) == 0 { + t.Fatal("the re-run read every root of the deleted HEAD; want the deleted ones reported") + } + requireDeletedAndReleased(t, c, src, tgt) +} + +// The delete interrupted at each of its mutations (HEAD deleting, the +// source's release, each object, HEAD deleted), before that mutation +// applies, completes when re-run. +func TestBCatalog_DeleteInterruptedAtEachStepCompletesOnRerun(t *testing.T) { + ctx := context.Background() + interrupted := 0 + for k := 1; ; k++ { + c, f, _, src, tgt := rerunFixture(t) + n := 0 + fail := func(p string) error { + n++ + if n == k { + return errors.New("injected: interrupted") + } + return nil + } + f.mu.Lock() + f.failUpdate, f.failDelete = fail, fail + f.mu.Unlock() + _, err := c.DeleteVolume(ctx, tgt, okDeleteAuthority{}) + f.mu.Lock() + f.failUpdate, f.failDelete = nil, nil + f.mu.Unlock() + if err == nil { + if interrupted < 3 { + t.Fatalf("only %d mutations were interrupted; the fixture does not reach every step", interrupted) + } + requireDeletedAndReleased(t, c, src, tgt) + return + } + interrupted++ + if _, err := c.DeleteVolume(ctx, tgt, okDeleteAuthority{}); err != nil { + t.Fatalf("interrupted at mutation %d, the re-run failed: %v", k, err) + } + requireDeletedAndReleased(t, c, src, tgt) + } +} + +// Only a missing object of a deleting or deleted HEAD is skipped: a corrupt +// root of a deleting HEAD, and a missing root of a live HEAD, are errors. +func TestBCatalog_DeleteRerunSkipsOnlyMissingRootsOfADeletingVolume(t *testing.T) { + ctx := context.Background() + rootOf := func(t *testing.T, f *fakeFiler, tgt VolumeRef) string { + t.Helper() + f.mu.Lock() + defer f.mu.Unlock() + for p := range f.entries { + if strings.Contains(p, "/"+tgt.Dir()+"/"+layout.RootDir+"/") { + return p + } + } + t.Fatal("fixture: the target has no root object") + return "" + } + + t.Run("corrupt root of a deleting HEAD", func(t *testing.T) { + c, f, b, _, tgt := rerunFixture(t) + // Interrupt right after HEAD deleting (at the source's release): HEAD + // is deleting and every root is still there. + n := 0 + f.mu.Lock() + f.failUpdate = func(string) error { + n++ + if n == 2 { + return errors.New("injected: interrupted") + } + return nil + } + f.mu.Unlock() + if _, err := c.DeleteVolume(ctx, tgt, okDeleteAuthority{}); err == nil { + t.Fatal("fixture: the delete was not interrupted") + } + f.mu.Lock() + f.failUpdate = nil + f.mu.Unlock() + root := rootOf(t, f, tgt) + f.mu.Lock() + e := f.entries[root] + if len(e.Content) > 0 { + e.Content = append([]byte("corrupt"), e.Content...) + } + for _, ch := range e.Chunks { + b.mu.Lock() + b.data[ch.FileId] = append([]byte("corrupt"), b.data[ch.FileId]...) + b.mu.Unlock() + } + f.mu.Unlock() + if _, err := c.DeleteVolume(ctx, tgt, okDeleteAuthority{}); !errors.Is(err, layout.ErrCorrupt) { + t.Fatalf("re-run with a corrupt root: %v; want ErrCorrupt", err) + } + }) + + t.Run("missing root of a live HEAD", func(t *testing.T) { + c, f, _, _, tgt := rerunFixture(t) + root := rootOf(t, f, tgt) + f.mu.Lock() + delete(f.entries, root) + f.mu.Unlock() + if _, err := c.DeleteVolume(ctx, tgt, okDeleteAuthority{}); !errors.Is(err, layout.ErrMissing) { + t.Fatalf("delete of a live volume with a missing root: %v; want ErrMissing", err) + } + ts, _, err := c.open(tgt) + if err != nil { + t.Fatal(err) + } + if h, _, err := ts.ReadHead(ctx); err != nil || h.State == layout.StateDeleting || h.State == layout.StateDeleted { + t.Fatalf("target HEAD %+v %v; want it left as it was", h, err) + } + }) +} diff --git a/seaweed-block/core/frontend/chunkstore/fake_test.go b/seaweed-block/core/frontend/chunkstore/fake_test.go index adfcc42ed1..da25da9b49 100644 --- a/seaweed-block/core/frontend/chunkstore/fake_test.go +++ b/seaweed-block/core/frontend/chunkstore/fake_test.go @@ -32,6 +32,9 @@ type fakeFiler struct { failUpdateAfterApply func(p string) error updates int deletes int + // failDelete, if set, is called before a DeleteEntry is applied; a + // non-nil return fails the call and the entry is NOT deleted. + failDelete func(p string) error // beforeCreate, if set, runs under the lock just before an entry is // created (it may read f.entries but must not call f's methods). beforeCreate func(p string) @@ -170,6 +173,11 @@ func (f *fakeFiler) DeleteEntry(_ context.Context, dir, name string, expected ma f.mu.Lock() defer f.mu.Unlock() p := path.Join(dir, name) + if f.failDelete != nil { + if err := f.failDelete(p); err != nil { + return err + } + } cur, ok := f.entries[p] if len(expected) > 0 { if !ok { diff --git a/seaweed-block/core/frontend/chunkstore/head_readers_test.go b/seaweed-block/core/frontend/chunkstore/head_readers_test.go index a4cf3b8e48..665ee0b7fc 100644 --- a/seaweed-block/core/frontend/chunkstore/head_readers_test.go +++ b/seaweed-block/core/frontend/chunkstore/head_readers_test.go @@ -187,7 +187,7 @@ func TestHeadReaders_AbsentHeadProbes(t *testing.T) { if err := c.SetRetention(ctx, v, retain.DefaultPolicy()); !errors.Is(err, layout.ErrHeadAbsent) || len(f.written) != 0 { t.Fatalf("policy of an absent HEAD: %v (%d writes); want ErrHeadAbsent and none", err, len(f.written)) } - if err := c.DeleteVolume(ctx, v, okDeleteAuthority{}); !errors.Is(err, layout.ErrHeadAbsent) || len(f.written) != 0 { + if _, err := c.DeleteVolume(ctx, v, okDeleteAuthority{}); !errors.Is(err, layout.ErrHeadAbsent) || len(f.written) != 0 { t.Fatalf("delete of an absent HEAD: %v (%d writes); want ErrHeadAbsent and none", err, len(f.written)) } }) diff --git a/seaweed-block/core/frontend/chunkstore/layout_objects_integration_test.go b/seaweed-block/core/frontend/chunkstore/layout_objects_integration_test.go index a10f9f05a1..1c252c06c3 100644 --- a/seaweed-block/core/frontend/chunkstore/layout_objects_integration_test.go +++ b/seaweed-block/core/frontend/chunkstore/layout_objects_integration_test.go @@ -120,7 +120,7 @@ func TestIntegration_CatalogRestoreAndDelete(t *testing.T) { if _, err := cat.DeleteSnapshot(ctx, src, "daily"); !errors.Is(err, layout.ErrHasDependents) { t.Fatalf("delete a depended-on snapshot: %v", err) } - if err := cat.DeleteVolume(ctx, tgt, okDeleteAuthority{}); err != nil { + if _, err := cat.DeleteVolume(ctx, tgt, okDeleteAuthority{}); err != nil { t.Fatalf("delete the target: %v", err) } if objs, err := cat.listObjects(ctx, tgt); err != nil || len(objs) != 0 { diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index dfce6f9167..1d4874fd19 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -1076,7 +1076,7 @@ Notes: | `INV-SNAPK-REF-ID-001` | Every chunk reference in a segment carries its owner's volume id; a read checks it against the owner's VOLUME before fetching (another id is ErrIdentity), and the remover tells its own chunks by its VOLUME id. | Content-named layout | `core/frontend/chunkstore/layout` `layout.go` `Segment.Encode`; `read.go` `Image.Chunk`; `remove.go` | `TestSegment_EncodeRefusals`, `TestRead_ForeignChunkNeedsTheOwnersVolumeID`, `TestRemoveUnreachable_NeedsItsOwnVolumeID` | — (the snapshot kernel model is not in this repository) | ACTIVE | | `INV-SNAPK-DEP-ID-001` | Every dependent records the target's volume id and the root of the snapshot it depends on; a dependent without the id, or of another root, is refused. | M9 snapshots and dependents | `core/frontend/chunkstore/layout` `head.go` `Head.check` | `TestHead_Refusals`, `TestHead_GoldenEncodingRoundTrip` | — (the snapshot kernel model is not in this repository) | ACTIVE | | `INV-SNAPK-CLAIM-ID-001` | A holder is its epoch, its server and the claim id its claim wrote into HEAD; every transition refuses the same server at the same epoch with another claim id. | M9 every transition | `core/frontend/chunkstore/layout` `head.go` `heldBy`; `claim.go` `Head.Claim` | `TestClaim_WritesItsClaimID`, `TestTransitions_RefuseAStaleHolder`, `TestHolderFunctions_RefuseAStaleHolder` | — (the snapshot kernel model is not in this repository) | ACTIVE | -| `INV-SNAPK-DELETE-ORDER-001` | A volume delete runs in its order, each prefix safe and the whole re-runnable: HEAD deleting, this volume released from every source, its objects deleted, HEAD deleted. | M9 idle → deleting → deleted | `core/frontend/chunkstore/layout` `delete.go` `DeleteVolume` | `TestDeleteVolume`, `TestDeleteVolume_InterruptAtEveryStep`, `TestRunMarkDeleting_InterruptAtEveryStep`, `TestRunMarkDeleted_InterruptAtEveryStep` | — (the snapshot kernel model is not in this repository) | ACTIVE | +| `INV-SNAPK-DELETE-ORDER-001` | A volume delete runs in its order, each prefix safe and the whole re-runnable: HEAD deleting, this volume released from every source, its objects deleted, HEAD deleted. | M9 idle → deleting → deleted | `core/frontend/chunkstore/layout` `delete.go` `DeleteVolume`; `core/frontend/chunkstore/catalog_b.go` `BCatalog.DeleteVolume`, `foreignOwners` | `TestDeleteVolume`, `TestDeleteVolume_InterruptAtEveryStep`, `TestRunMarkDeleting_InterruptAtEveryStep`, `TestRunMarkDeleted_InterruptAtEveryStep`; `TestBCatalog_DeleteRerunOnADeletedVolumeSucceeds`, `TestBCatalog_DeleteInterruptedAtEachStepCompletesOnRerun`, `TestBCatalog_DeleteRerunSkipsOnlyMissingRootsOfADeletingVolume` (`core/frontend/chunkstore/catalog_delete_rerun_test.go`) | — (the snapshot kernel model is not in this repository) | ACTIVE | | `INV-SNAPK-DELETE-OWNED-001` | Every object entry carries the id of its volume; a volume delete removes an object only if it carries that id, so a late delete of a finished run never removes the object of a volume created again under the name. | M9 deleting → deleted | `core/frontend/chunkstore/layout` `delete.go` `DeleteVolume`; `objects.go` `ObjectStore.DeleteOfVolume` | `TestDeleteVolume_ALateDeleteSparesTheNameReused`, `TestDeleteVolume` | — (the snapshot kernel model is not in this repository) | ACTIVE | | `INV-SNAPK-DELETE-GATE-001` | HEAD becomes deleting only with a committed deletion reservation, no live lease (unclaimed grants included), no open activity and no snapshot with dependents; from deleting on, no holder transition, claim or removal applies. | M2 any → DeleteReserved; M9 idle → deleting | `core/frontend/chunkstore/layout` `delete.go` `Head.MarkDeleting`; `head.go` `holderErr`; `core/authority/workspace_delete_reservation.go`; `core/host/master/volume_delete_authority.go` `ReserveVolumeDeletion`, `CheckVolumeNoLiveLease`; `cmd/sw-block/chunk_volume_delete.go` `masterAuthority` | `TestMarkDeleting_Closure`, `TestMarkDeleted_Closure`, `TestDeleting_RefusesEveryHolderStep`, `TestDeleteVolume`; `TestCommittedDeleteStopsGrantsAndWaitsForTheWholeLease`, `TestDeleteReservationClosesPausedGrantWriters`, `TestDeleteReservationMustBeDurableBeforeItCanProveNoLease`, `TestDeleteReservationContextAndPersistenceFailuresStayUnknown`, `TestDeleteOfALiveVolumeIsRefusedBeforePersisting`, `TestDeleteReservationReplayAndRestart`, `TestDeletionReservationGuardSites` (`core/authority`); `TestVolumeDeleteAuthorityReservationSurvivesRestart`, `TestVolumeDeleteAuthorityRPCs` (`core/host/master`; durable RPC/restart probes run on Linux); `TestOpsChunkVolumeDeleteRequiresTheMastersLeaseProof`, `TestOpsChunkVolumeDeleteClosesAPausedFirstGrant`, `TestChunkVolumeDeleteAuthorityRPCSites` (`cmd/sw-block`) | The reservation makes no-live-lease stable; a claim racing the conditional HEAD update still fails its generation check. The snapshot kernel model is external; composed model review pending. | ACTIVE | | `INV-WS-DELETE-WITHOUT-ACK-001` | A delete without the holder's acknowledgement is admitted only while the master's record still awaits a replica store (stage 1), marked durably first; the mark freezes the wait, so the primary never serves. Past stage 1 the live-lease refusal stays. | M2 any authority line, stores still awaited → DeleteReserved without the holder's acknowledgement | `core/host/master/volume_delete_authority.go` `Reserve`; `core/host/master/store_attestation.go` `markDeleteWithoutAck`, `awaited` | `TestANeverCreatedVolumeIsDeletedWithoutItsHolder`, `TestAnEstablishedVolumeIsNotDeletedUnderALiveLease` (`core/host/master/workspace_delete_never_created_test.go`); `TestAStage2VolumeKeepsTheLiveLeaseRefusal`, `TestTheDeleteMarkFreezesTheStoreWait`, `TestAStage2VolumeIsNotMarkedForADeleteWithoutAck` (`core/host/master/workspace_delete_proof_test.go`); `TestDeleteMarkWriterCensus`, `TestDeleteMarkWriterCensusControls` (`core/host/master/store_attestation_census_test.go`) | CreateEvid2 model rows `mut_delete_on_flag_only`, `mut_no_horizon` | ACTIVE | From c8b47542587fed9af37dd8f60f2d984a16513478 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 26 Nov 2026 05:45:37 -0800 Subject: [PATCH 10/14] fix(volume): the revocation ACK's bound exceeds what the master spends on it The holder gave its revocation ACK call 2 s and the closeout 3 s, while the master's handler spends up to 2 s on its bounded HEAD read and then writes the ACK and reconciles the bindings (about 0.3 s, measured), behind its workspace lock. A slow but successful ACK could fail at the holder (exit 75), also after the master recorded it. WorkspaceAckTimeout (5 s, about 2.7 s above the master's measured steps, stated in its comment) bounds the ACK call, still within the lease deadline; the post-drain closeout is that plus 1 s. Constants only. Co-Authored-By: Claude Opus 5.5 --- seaweed-block/cmd/blockvolume/process_exit.go | 6 +- .../host/volume/workspace_ack_budget_test.go | 55 +++++++++++++++++++ .../core/host/volume/workspace_lease.go | 11 +++- seaweed-block/docs/design/invariants.md | 6 +- 4 files changed, 72 insertions(+), 6 deletions(-) create mode 100644 seaweed-block/core/host/volume/workspace_ack_budget_test.go diff --git a/seaweed-block/cmd/blockvolume/process_exit.go b/seaweed-block/cmd/blockvolume/process_exit.go index cfc02d45a3..b9ad6a0096 100644 --- a/seaweed-block/cmd/blockvolume/process_exit.go +++ b/seaweed-block/cmd/blockvolume/process_exit.go @@ -16,8 +16,10 @@ import ( const ( exitWorkspaceRetry = 75 exitWorkspaceSuperseded = 78 - // Existing post-drain ACK wait; M2 Revoking -> Revoked, Part D. - workspaceLeaseCloseoutTimeout = 3 * time.Second + // Post-drain ACK wait; M2 Revoking -> Revoked, Part D. It covers the + // guard's stop reply (the resource owner has drained by then) and its + // ACK call, so it exceeds the ACK's own bound by 1 s. + workspaceLeaseCloseoutTimeout = volume.WorkspaceAckTimeout + time.Second ) type workspaceExit struct { diff --git a/seaweed-block/core/host/volume/workspace_ack_budget_test.go b/seaweed-block/core/host/volume/workspace_ack_budget_test.go new file mode 100644 index 0000000000..899ca755f6 --- /dev/null +++ b/seaweed-block/core/host/volume/workspace_ack_budget_test.go @@ -0,0 +1,55 @@ +package volume + +import ( + "context" + "testing" + "time" + + control "github.com/seaweedfs/seaweed-block/core/rpc/control" + "google.golang.org/grpc" +) + +// slowAckClient is a master that answers the revocation ACK after delay +// (its bounded HEAD read and write), honouring the call's deadline. +type slowAckClient struct { + delay time.Duration + acked chan struct{} +} + +func (c slowAckClient) RenewWorkspaceLease(context.Context, *control.WorkspaceIdentity, ...grpc.CallOption) (*control.WorkspaceLeaseFact, error) { + return &control.WorkspaceLeaseFact{VolumeId: "v", ReplicaId: "r", Epoch: 1, ValidForNs: int64(30 * time.Second), Revoking: true}, nil +} + +func (c slowAckClient) AckWorkspaceRevoked(ctx context.Context, _ *control.WorkspaceRevocationAck, _ ...grpc.CallOption) (*control.WorkspaceEmpty, error) { + select { + case <-time.After(c.delay): + close(c.acked) + return &control.WorkspaceEmpty{}, nil + case <-ctx.Done(): + return nil, ctx.Err() + } +} + +// A master that takes 2.5 s to answer the ACK (above its 2 s HEAD read +// alone, still inside its bounded steps) gets a completed ACK: the holder's +// ACK bound exceeds the master's. +func TestWorkspaceRevocationAckOutlastsTheMastersBoundedSteps(t *testing.T) { + if WorkspaceAckTimeout <= 2*time.Second+500*time.Millisecond { + t.Fatalf("WorkspaceAckTimeout %v does not exceed the master's 2 s HEAD read plus its write and reconcile", WorkspaceAckTimeout) + } + client := slowAckClient{delay: 2500 * time.Millisecond, acked: make(chan struct{})} + g, err := NewWorkspaceLeaseGuard(workspaceTestView{}, client, &control.WorkspaceIdentity{VolumeId: "v", ReplicaId: "r", Epoch: 1}, func(context.Context) (uint64, error) { return 7, nil }, nil) + if err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) + defer cancel() + if err := g.Run(ctx); err != nil { + t.Fatalf("a 2.5 s ACK answer failed the revocation: %v", err) + } + select { + case <-client.acked: + default: + t.Fatal("the master's ACK answer was not awaited") + } +} diff --git a/seaweed-block/core/host/volume/workspace_lease.go b/seaweed-block/core/host/volume/workspace_lease.go index 70dd913e00..25e0eccc05 100644 --- a/seaweed-block/core/host/volume/workspace_lease.go +++ b/seaweed-block/core/host/volume/workspace_lease.go @@ -68,6 +68,15 @@ type WorkspaceLeaseGuard struct { // revocation to its ACK also includes that renewal, the drain and the ACK. const stopPendingPoll = 250 * time.Millisecond +// WorkspaceAckTimeout bounds the holder's revocation ACK call (within the +// lease deadline). It must exceed what the master spends before it answers +// (core/host/master AckWorkspaceRevoked): its 2 s bounded HEAD read, then the +// ACK's durable write and the bindings' reconcile (about 0.3 s together, +// measured), behind its workspace lock. 5 s leaves about 2.7 s for that lock +// and for slower disks. A shorter bound lets a slow but successful ACK fail +// here (the holder exits 75 although the master may have recorded it). +const WorkspaceAckTimeout = 5 * time.Second + // WorkspaceDrainTimeout is the existing fail-closed lease drain bound. // INV-WS-STARTUP-RETRY-001 also bounds the process cleanup by this duration. const WorkspaceDrainTimeout = 5 * time.Second @@ -398,7 +407,7 @@ func (g *WorkspaceLeaseGuard) drain(parent context.Context, ack bool) error { } leaseCtx, leaseCancel := context.WithDeadline(parent, until) defer leaseCancel() - ctx, cancel := context.WithTimeout(leaseCtx, 2*time.Second) + ctx, cancel := context.WithTimeout(leaseCtx, WorkspaceAckTimeout) defer cancel() _, err := g.client.AckWorkspaceRevoked(ctx, &control.WorkspaceRevocationAck{Identity: &g.id, HeadGen: g.headGen}) return err diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index dfce6f9167..1bc17b76ae 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -801,7 +801,7 @@ Notes: | `INV-WS-SINGLE-FILER-001` | A chunk volume starts only when `--chunk-filer` is the only filer of its group: a master listing another filer or several refuses at once, whichever master answers first; a filer no master lists within 60 s is refused. A startup census, not a fence: a filer added to the group later is not detected. | M4 (startup) → Refused | `core/frontend/chunkstore/single_filer.go` `CheckSingleFiler`; `cmd/blockvolume/chunk_remote.go` `newChunkWiring`; `cmd/sw-block/chunk.go` `refuseUnlessSingleFiler` | `TestCheckSingleFilerRefusesAnotherOrSeveralFilers`, `TestCheckSingleFilerFailsClosed`, `TestCheckSingleFilerFavourableThenStalledRefuses`, `TestIsTargetComparesScopedAddresses`, `TestCheckSingleFilerPasses` (`core/frontend/chunkstore/single_filer_test.go`), `TestChunkWiringRefusesAMultiFilerGroup` (`cmd/blockvolume/single_filer_test.go`), `TestOpsChunk_WritingCommandsRunTheSingleFilerCheck` (`cmd/sw-block/chunk_start_check_test.go`), `TestOpsChunk_VerifyRunsTheSingleFilerCheck` (`cmd/sw-block/chunk_verify_test.go`) | — | ACTIVE | | `INV-WS-LEASE-REGRANT-001` | Re-grant after expiry keeps the same holder and epoch, with no pending move or revocation, a certain store, and one durable write after the horizon/deadline plus skew barrier. Restart begins a new session and voids the old; ordinary reopen keeps HEAD identity (epoch, holder, claim) unchanged. | M2 Expired → Granted; M9 Start | `core/authority/workspace_lease_view.go` `regrantWorkspaceLease`; `core/authority/workspace.go` `forcedMoveBarrierLocked`; `core/frontend/chunkstore/layout/start.go` `Start` | `TestWorkspaceLeaseExpiredSameHolderRegrantIsDurable`, `TestWorkspaceLeaseRegrantWaitsForFullSkew`, `TestWorkspaceLeaseRegrantDefeatsAlreadyPassedForcedPreflight`, `TestWorkspaceLeaseForcedIssueDefeatsOldHolderRegrant`, `TestWorkspaceLeaseRegrantWaitsForDurabilityAndLatchesFailure` (`core/authority/workspace_regrant_test.go`); `TestWorkspaceLeaseRegrantPreservesLocalLogThroughFirstCut` (`core/authority/workspace_regrant_storage_test.go`); `TestStart_OwnEpochFreshRootRefusedBeforeClaim`, `TestStart_OwnEpochSameRootContinues` (`core/frontend/chunkstore/layout/start_test.go`); `TestClaim_WritesItsClaimID`, `TestRunClaim_VoidsTheOldSession` (`core/frontend/chunkstore/layout/claim_test.go`); `TestLocalReopenClaimsBeforeServing` (`core/frontend/durable/provider_reopen_belt_test.go`) | `WorkspaceRegrant` `NoDualServingInc`, `RegrantNoLoss`, `DiskCoversMemory`; `INV-SNAPK-START-ROOT-001` | ACTIVE | | `INV-WS-LEASE-001` | A host admits frontend I/O and cuts only under an unexpired lease for its exact `{volume, replica, epoch}`; a fenced guard never reopens, even on a late renewal reply. | M4 lease guard: Valid → Fenced | `core/host/volume/workspace_lease.go` `permits`, `Refresh` | `TestWorkspaceLeaseExpiryFencesWithoutTimerAndCannotReopen`, `TestWorkspaceDelayedRenewalCannotUndoExpiry` (`core/host/volume/workspace_lease_test.go`); `TestWorkspaceHostRequiresLeaseBeforeFrontendAndCut` (`core/host/volume/workspace_runtime_test.go`); `TestWorkspacePausedGranteeRefusedAtAttach` (`core/host/master/workspace_paused_grantee_test.go`) | `WorkspaceTakeover` `NoDualServing` | ACTIVE | -| `INV-WS-REVOKE-ACK-001` | A host acknowledges a revocation only after its frontend and cuts have stopped; a cancelled or expired drain sends no acknowledgement. | M4 lease guard: Revoking → Acked | `core/host/volume/workspace_lease.go` `drain` | `TestWorkspaceRevocationAckOnlyAfterFrontendAndCutsStop` (`core/host/volume/workspace_lease_test.go`); `TestWorkspaceHostCancelOrExpiryDuringRevokeDrainNeverACKs` (`core/host/volume/workspace_runtime_test.go`) | `WorkspaceTakeover` `CleanNoLoss` | ACTIVE | +| `INV-WS-REVOKE-ACK-001` | A host acknowledges a revocation only after its frontend and cuts have stopped; a cancelled or expired drain sends no acknowledgement. | M4 lease guard: Revoking → Acked | `core/host/volume/workspace_lease.go` `drain` | `TestWorkspaceRevocationAckOnlyAfterFrontendAndCutsStop` (`core/host/volume/workspace_lease_test.go`); `TestWorkspaceHostCancelOrExpiryDuringRevokeDrainNeverACKs` (`core/host/volume/workspace_runtime_test.go`); `TestWorkspaceRevocationAckOutlastsTheMastersBoundedSteps` (`core/host/volume/workspace_ack_budget_test.go`) | `WorkspaceTakeover` `CleanNoLoss` | ACTIVE | | `INV-WS-STOP-PENDING-001` | From when the detach hook of a chunk detach runs until the lease guard fences, or until that detach's resume clears stop-pending, each sleep of the guard after a completed renewal is at most 250 ms on the local monotonic clock. | M4 lease guard: Valid → StopPending → Valid \| Fenced | `core/host/volume/workspace_lease.go` `StopPending`, `ClearStopPending`, `renewDelay`, `Run`; `core/host/volume/workspace_runtime.go` `WorkspaceStopPending`, `WorkspaceStopResumed`; `core/frontend/durable/provider_chunk.go` `DetachVolume`, `detachVolume`, `resumeAfterDetach`; `cmd/blockvolume/main.go` `run` (wiring) | `TestWorkspaceLeaseStopPendingSchedule`, `TestWorkspaceHostStopResumedClearsOnlyTheLatestAttempt`, `TestWorkspaceHostFailedDetachStopPendingByOutcome`, `TestWorkspaceHostDetachHookFencesWithinPoll`, `TestWorkspaceLeaseStopPendingNeverBlocks` (`core/host/volume/workspace_lease_stop_pending_test.go`); `TestWALStoreChunk_DetachHookPrecedesDrain`, `TestWALStoreChunk_DetachResumeHookOnlyOnProvenAbort`, `TestWALStoreChunk_DetachCallsStopHook` (`core/frontend/durable/provider_chunk_detach_hook_test.go`) | — | ACTIVE | | `INV-WS-SAME-HOST-CLEAN-MOVE-001` | A same-host move issues a higher epoch: a clean move needs the current holder's sealed HEAD and its recorded epoch/holder/position ACK, and the successor reads that sealed image; a forced move needs the normal lease barrier and a durable lost-range record. | M2 Acked or Expired → Moved; M9 detached → higher-epoch idle | `core/authority/workspace.go` `validateWorkspaceMoveRequest`, `prepareWorkspaceMoveLocked`; `core/host/master/workspace_service.go` `workspaceMoveCheckLocked`; `core/frontend/chunkstore/layout/start.go` `Start`, `core/frontend/chunkstore/layout/claim.go` `Claim` | `TestWorkspaceSameHostForcedMoveRecordsLostRange` (`core/authority/workspace_same_host_forced_test.go`); `TestWorkspaceRPCSameHostForcedRecoveryRecordsLoss` (`core/host/master/workspace_same_host_forced_test.go`); `TestWorkspaceSameHostCleanMoveUsesOvernightSeal` (`core/authority/workspace_same_host_clean_test.go`); `TestWorkspaceRPCSameHostCleanMoveKeepsRepreparedBinding` (`core/host/master/workspace_same_host_clean_test.go`); `TestLayoutSameHostCleanSuccessorReadsSealedImage` (`core/frontend/durable/provider_layout_same_host_clean_test.go`) | `WorkspaceRegrant` `SameHostLoadsSealed`; `INV-SNAPK-DETACHED-001`. The B provider test performs a real plain detach, same-host higher-epoch fresh-root Start, and reads the sealed bytes. | ACTIVE | | `INV-WS-DELETE-NO-LIVE-HOLDER-001` | A workspace volume is marked deleting only with no live holder (`TERM-LIVE-HOLDER-001`): no line, a clean revocation ACK for the line, or HEAD below the line's epoch. A sealed HEAD without an ACK, a live or unreadable one is refused; the HEAD compare-and-swap to deleting fences a later claim. | M2 none/Granted/Revoking/Expired → Deleting | `core/authority/workspace_holder_state.go` `WorkspaceHolderState`; `core/authority/workspace.go` `RecordWorkspaceDeletion`; `core/host/master/services.go` `MarkVolumeDeleting`, `deleteHolderEvidence` | `TestWorkspaceHolderState` (`core/authority/workspace_holder_state_test.go`); `TestDeleteAdmitsANeverStartedLine` (`core/host/master/workspace_delete_never_started_test.go`); `TestDeleteAdmissionVerdicts` (`core/authority/workspace_delete_admission_test.go`); `TestMarkVolumeDeleting_RefusedWhileAssigned` (`core/host/master/volume_deleting_test.go`) | NeverStarted r2 `DeleteNeverStrandsALiveHolder`, `NoServedWriteLost`, re-run can finish, re-run can settle (exhaustive, 21 of 21 configurations as expected). Not modelled: two delete processes at the same instant; the gap between HEAD deleted and the volume marked deleted | ACTIVE | @@ -833,7 +833,7 @@ Notes: - Part T fence ownership: `Host.FenceWorkspaceLease` uses `WorkspaceLeaseGuard.fenceLocked`, including before runtime publication; the zero-validity terminal guard preserves the first cause through installation and can grant no I/O. No second host fence latch exists. `TestWorkspaceHostFencePublishesOneTerminalCause`, `TestWorkspaceInstalledHostFenceRecordsCause`, `TestWorkspaceFenceBeforeHeldInstallIsTerminal` (`core/host/volume/workspace_terminal_test.go`). - Startup arbitration: sealed-replay/stale-local-root dispositions suppress the same wait's deadline defer (`TestChunkStartupRetainedDispositionWinsExpiredAttachContext`, `core/frontend/durable/provider_startup_outcome_test.go`). A stop request retires startup monitoring and its atomic-choice callback before resource cleanup; success is chosen only after the guard's ACK (`TestWorkspacePlannedDrainOwnsStartupExpiryUntilAck`, `cmd/blockvolume/process_exit_authority_test.go`). Provider-validated startup selection briefly takes the process startup mutex; cancellation takes only that mutex. No reverse provider-lock acquisition or remote call occurs. -- ACK closeout: the guard sets `revoked` under its mutex before calling `drain` and invoking the stop callback. After a drain reply, its ACK call is bounded by the original lease deadline and 2 s RPC timeout. The existing 3 s closeout wait therefore expires before a newly selected retry's 5 s supervisor bound starts; a prior nonzero decision remains immutable. A restart can ACK the sealed HEAD only while the original revoking lease is still valid. Once it expires, re-grant refuses revoking/ACKed leases: repeated 75 is not recovery of an unconfirmed ACK, and operator recovery is required; no lease or ACK gate is bypassed. +- ACK closeout: the guard sets `revoked` under its mutex before calling `drain` and invoking the stop callback. After a drain reply, its ACK call is bounded by the original lease deadline and the 5 s `WorkspaceAckTimeout` (above the master's 2 s HEAD read plus its ACK write and reconcile). The existing 3 s closeout wait therefore expires before a newly selected retry's 5 s supervisor bound starts; a prior nonzero decision remains immutable. A restart can ACK the sealed HEAD only while the original revoking lease is still valid. Once it expires, re-grant refuses revoking/ACKed leases: repeated 75 is not recovery of an unconfirmed ACK, and operator recovery is required; no lease or ACK gate is bypassed. Notes: @@ -1148,7 +1148,7 @@ Format v3 row 4 runs in production recovery (`WALStore.recoverV3`). Its typed sc | Wait | Machine / invariant | Bound | Release and cancellation | Locks / remote work | |---|---|---|---|---| -| Workspace revocation ACK closeout | M2 Revoking → Revoked; `INV-WS-STARTUP-RETRY-001` | Existing `workspaceLeaseCloseoutTimeout` (3 s), after the resource owner replies to the guard | `finishWorkspaceLease` owns the wait. ACK success selects normal exit; error/expiry selects 75 with `revoke_ack_unconfirmed`. The 5 s supervisor cleanup clock starts only after a nonzero outcome is selected. | No provider/storage lock held. | +| Workspace revocation ACK closeout | M2 Revoking → Revoked; `INV-WS-STARTUP-RETRY-001` | `workspaceLeaseCloseoutTimeout` (`WorkspaceAckTimeout` + 1 s = 6 s), after the resource owner replies to the guard | `finishWorkspaceLease` owns the wait. ACK success selects normal exit; error/expiry selects 75 with `revoke_ack_unconfirmed`. The 5 s supervisor cleanup clock starts only after a nonzero outcome is selected. | No provider/storage lock held. | | Workspace primary retry cleanup | M2 restart; `INV-WS-STARTUP-RETRY-001` | Existing `WorkspaceDrainTimeout` (5 s) after retry/no-retry outcome selection | Process supervisor owns the deadline and returns 75 or 78 even if resource-owner cleanup blocks; first outcome stays latched. Signal and ACKed revocation retain normal exit. | Provider latches by recovery generation under p.mu; wake is nonblocking; the supervisor holds no provider/storage lock. | | Workspace primary supervisor retries | M2 restart; `INV-WS-STARTUP-RETRY-001` | Shipped systemd units: `StartLimitIntervalSec=600`, `StartLimitBurst=10`, `RestartSec=5s`. While the master answers, each cycle is the assignment wait (30 s from contact) + 5 s, reaching the limit in about 6 minutes; while it gives no reply the process waits without exiting, so an outage costs one start (the fence), not the limit. If the assignment wait exceeds about 55 s, raise the interval too or the window never fills | systemd owns the restart window: after 10 starts in 600 s, another start within the window is refused and the unit fails; operator reset/start follows remediation. Exit 78 and ACKed exit 0 do not restart. | No application lock; `TestBlockvolumeUnitsBoundStartupRetries` (`internal/testops/blockvolume_systemd_test.go`) checks both shipped units. | | Offline seal | M5 PlainStop -> Quiesce; `INV-CUT-PLAIN-DETACH-001` | Caller context; positive HTTP timeoutMs. Completed uploads resume only within one blockvolume process and matching owner/HEAD/chunk versions; after restart the seal must fit seal_timeout_ms. | Provider owns drain, detached cut and settlement. Cancellation preserves unknown/fenced outcome safety; a closed frontend stays closed. | No admission lock held during store or remote I/O. | From a9dbdd756c98bf894870d66eb789ee76cf525c87 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 26 Nov 2026 05:48:57 -0800 Subject: [PATCH 11/14] test(chunkstore): a read failure of a deleting volume's root is returned, not skipped A root whose read fails with an ordinary error (not missing, not corrupt) on a deleting HEAD makes the re-run return that error, skip nothing and leave HEAD unchanged; the fake filer gains a failLookup hook (test only). Skipping every error on a deleting HEAD fails it. Co-Authored-By: Claude Opus 5.5 --- .../chunkstore/catalog_delete_rerun_test.go | 47 +++++++++++++++++++ .../core/frontend/chunkstore/fake_test.go | 8 ++++ 2 files changed, 55 insertions(+) diff --git a/seaweed-block/core/frontend/chunkstore/catalog_delete_rerun_test.go b/seaweed-block/core/frontend/chunkstore/catalog_delete_rerun_test.go index 3d1692b5eb..e862b5384f 100644 --- a/seaweed-block/core/frontend/chunkstore/catalog_delete_rerun_test.go +++ b/seaweed-block/core/frontend/chunkstore/catalog_delete_rerun_test.go @@ -160,6 +160,53 @@ func TestBCatalog_DeleteRerunSkipsOnlyMissingRootsOfADeletingVolume(t *testing.T } }) + t.Run("read failure of a root of a deleting HEAD", func(t *testing.T) { + c, f, _, _, tgt := rerunFixture(t) + // Interrupt at the source's release: HEAD is deleting, roots intact. + n := 0 + f.mu.Lock() + f.failUpdate = func(string) error { + n++ + if n == 2 { + return errors.New("injected: interrupted") + } + return nil + } + f.mu.Unlock() + if _, err := c.DeleteVolume(ctx, tgt, okDeleteAuthority{}); err == nil { + t.Fatal("fixture: the delete was not interrupted") + } + ts, _, err := c.open(tgt) + if err != nil { + t.Fatal(err) + } + before, _, err := ts.ReadHead(ctx) + if err != nil || before.State != layout.StateDeleting { + t.Fatalf("fixture: HEAD %+v %v; want deleting", before, err) + } + root := rootOf(t, f, tgt) + sentinel := errors.New("injected: filer read failed") + f.mu.Lock() + f.failUpdate = nil + f.failLookup = func(p string) error { + if p == root { + return sentinel + } + return nil + } + f.mu.Unlock() + skipped, err := c.DeleteVolume(ctx, tgt, okDeleteAuthority{}) + f.mu.Lock() + f.failLookup = nil + f.mu.Unlock() + if !errors.Is(err, sentinel) || len(skipped) != 0 { + t.Fatalf("re-run with a root read failure: skipped=%v err=%v; want the read error and nothing skipped", skipped, err) + } + if after, _, err := ts.ReadHead(ctx); err != nil || after.Gen != before.Gen || after.State != layout.StateDeleting { + t.Fatalf("HEAD after the failed re-run %+v %v; want it unchanged (gen %d, deleting)", after, err, before.Gen) + } + }) + t.Run("missing root of a live HEAD", func(t *testing.T) { c, f, _, _, tgt := rerunFixture(t) root := rootOf(t, f, tgt) diff --git a/seaweed-block/core/frontend/chunkstore/fake_test.go b/seaweed-block/core/frontend/chunkstore/fake_test.go index da25da9b49..93dfc985b5 100644 --- a/seaweed-block/core/frontend/chunkstore/fake_test.go +++ b/seaweed-block/core/frontend/chunkstore/fake_test.go @@ -35,6 +35,9 @@ type fakeFiler struct { // failDelete, if set, is called before a DeleteEntry is applied; a // non-nil return fails the call and the entry is NOT deleted. failDelete func(p string) error + // failLookup, if set, is called before a LookupEntry reads p; a non-nil + // return is the lookup's error (a read or transport failure). + failLookup func(p string) error // beforeCreate, if set, runs under the lock just before an entry is // created (it may read f.entries but must not call f's methods). beforeCreate func(p string) @@ -65,6 +68,11 @@ func (f *fakeFiler) LookupEntry(_ context.Context, dir, name string) (*filerpb.E f.mu.Lock() defer f.mu.Unlock() p := path.Join(dir, name) + if f.failLookup != nil { + if err := f.failLookup(p); err != nil { + return nil, err + } + } e, ok := f.entries[p] var out *filerpb.Entry if ok { From 043aee64901d614945431c42a926ae8753d04919 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 26 Nov 2026 05:51:22 -0800 Subject: [PATCH 12/14] test(volume): the lease deadline still cuts a slow ACK; the closeout note says 6 s A revoking lease valid for 1 s and a master answering after 3 s: the ACK call is cancelled at the lease deadline (about 1 s), not at the 5 s ACK bound, and nothing is reported acknowledged; an ACK bound by the parent context alone fails it. The invariants note now names the 6 s closeout. Co-Authored-By: Claude Opus 5.5 --- .../host/volume/workspace_ack_budget_test.go | 35 ++++++++++++++++++- seaweed-block/docs/design/invariants.md | 4 +-- 2 files changed, 36 insertions(+), 3 deletions(-) diff --git a/seaweed-block/core/host/volume/workspace_ack_budget_test.go b/seaweed-block/core/host/volume/workspace_ack_budget_test.go index 899ca755f6..f2fa19b775 100644 --- a/seaweed-block/core/host/volume/workspace_ack_budget_test.go +++ b/seaweed-block/core/host/volume/workspace_ack_budget_test.go @@ -14,10 +14,15 @@ import ( type slowAckClient struct { delay time.Duration acked chan struct{} + valid time.Duration // the revoking lease's validity (default 30 s) } func (c slowAckClient) RenewWorkspaceLease(context.Context, *control.WorkspaceIdentity, ...grpc.CallOption) (*control.WorkspaceLeaseFact, error) { - return &control.WorkspaceLeaseFact{VolumeId: "v", ReplicaId: "r", Epoch: 1, ValidForNs: int64(30 * time.Second), Revoking: true}, nil + valid := c.valid + if valid == 0 { + valid = 30 * time.Second + } + return &control.WorkspaceLeaseFact{VolumeId: "v", ReplicaId: "r", Epoch: 1, ValidForNs: int64(valid), Revoking: true}, nil } func (c slowAckClient) AckWorkspaceRevoked(ctx context.Context, _ *control.WorkspaceRevocationAck, _ ...grpc.CallOption) (*control.WorkspaceEmpty, error) { @@ -53,3 +58,31 @@ func TestWorkspaceRevocationAckOutlastsTheMastersBoundedSteps(t *testing.T) { t.Fatal("the master's ACK answer was not awaited") } } + +// The lease deadline still bounds the ACK: with the revoking lease valid for +// 1 s and a master that answers after 3 s, the ACK call is cancelled at the +// lease deadline (about 1 s), not at WorkspaceAckTimeout (5 s), and the +// revocation is not reported as acknowledged. +func TestWorkspaceRevocationAckIsCutAtTheLeaseDeadline(t *testing.T) { + client := slowAckClient{delay: 3 * time.Second, acked: make(chan struct{}), valid: time.Second} + g, err := NewWorkspaceLeaseGuard(workspaceTestView{}, client, &control.WorkspaceIdentity{VolumeId: "v", ReplicaId: "r", Epoch: 1}, func(context.Context) (uint64, error) { return 7, nil }, nil) + if err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) + defer cancel() + start := time.Now() + err = g.Run(ctx) + elapsed := time.Since(start) + if err == nil { + t.Fatal("an ACK the master answered after the lease ended was reported as acknowledged") + } + if elapsed >= 2500*time.Millisecond { + t.Fatalf("the ACK ran %v: it was not cut at the 1 s lease deadline (err %v)", elapsed, err) + } + select { + case <-client.acked: + t.Fatal("the master's late answer was awaited past the lease deadline") + default: + } +} diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 1bc17b76ae..6c73ca3589 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -801,7 +801,7 @@ Notes: | `INV-WS-SINGLE-FILER-001` | A chunk volume starts only when `--chunk-filer` is the only filer of its group: a master listing another filer or several refuses at once, whichever master answers first; a filer no master lists within 60 s is refused. A startup census, not a fence: a filer added to the group later is not detected. | M4 (startup) → Refused | `core/frontend/chunkstore/single_filer.go` `CheckSingleFiler`; `cmd/blockvolume/chunk_remote.go` `newChunkWiring`; `cmd/sw-block/chunk.go` `refuseUnlessSingleFiler` | `TestCheckSingleFilerRefusesAnotherOrSeveralFilers`, `TestCheckSingleFilerFailsClosed`, `TestCheckSingleFilerFavourableThenStalledRefuses`, `TestIsTargetComparesScopedAddresses`, `TestCheckSingleFilerPasses` (`core/frontend/chunkstore/single_filer_test.go`), `TestChunkWiringRefusesAMultiFilerGroup` (`cmd/blockvolume/single_filer_test.go`), `TestOpsChunk_WritingCommandsRunTheSingleFilerCheck` (`cmd/sw-block/chunk_start_check_test.go`), `TestOpsChunk_VerifyRunsTheSingleFilerCheck` (`cmd/sw-block/chunk_verify_test.go`) | — | ACTIVE | | `INV-WS-LEASE-REGRANT-001` | Re-grant after expiry keeps the same holder and epoch, with no pending move or revocation, a certain store, and one durable write after the horizon/deadline plus skew barrier. Restart begins a new session and voids the old; ordinary reopen keeps HEAD identity (epoch, holder, claim) unchanged. | M2 Expired → Granted; M9 Start | `core/authority/workspace_lease_view.go` `regrantWorkspaceLease`; `core/authority/workspace.go` `forcedMoveBarrierLocked`; `core/frontend/chunkstore/layout/start.go` `Start` | `TestWorkspaceLeaseExpiredSameHolderRegrantIsDurable`, `TestWorkspaceLeaseRegrantWaitsForFullSkew`, `TestWorkspaceLeaseRegrantDefeatsAlreadyPassedForcedPreflight`, `TestWorkspaceLeaseForcedIssueDefeatsOldHolderRegrant`, `TestWorkspaceLeaseRegrantWaitsForDurabilityAndLatchesFailure` (`core/authority/workspace_regrant_test.go`); `TestWorkspaceLeaseRegrantPreservesLocalLogThroughFirstCut` (`core/authority/workspace_regrant_storage_test.go`); `TestStart_OwnEpochFreshRootRefusedBeforeClaim`, `TestStart_OwnEpochSameRootContinues` (`core/frontend/chunkstore/layout/start_test.go`); `TestClaim_WritesItsClaimID`, `TestRunClaim_VoidsTheOldSession` (`core/frontend/chunkstore/layout/claim_test.go`); `TestLocalReopenClaimsBeforeServing` (`core/frontend/durable/provider_reopen_belt_test.go`) | `WorkspaceRegrant` `NoDualServingInc`, `RegrantNoLoss`, `DiskCoversMemory`; `INV-SNAPK-START-ROOT-001` | ACTIVE | | `INV-WS-LEASE-001` | A host admits frontend I/O and cuts only under an unexpired lease for its exact `{volume, replica, epoch}`; a fenced guard never reopens, even on a late renewal reply. | M4 lease guard: Valid → Fenced | `core/host/volume/workspace_lease.go` `permits`, `Refresh` | `TestWorkspaceLeaseExpiryFencesWithoutTimerAndCannotReopen`, `TestWorkspaceDelayedRenewalCannotUndoExpiry` (`core/host/volume/workspace_lease_test.go`); `TestWorkspaceHostRequiresLeaseBeforeFrontendAndCut` (`core/host/volume/workspace_runtime_test.go`); `TestWorkspacePausedGranteeRefusedAtAttach` (`core/host/master/workspace_paused_grantee_test.go`) | `WorkspaceTakeover` `NoDualServing` | ACTIVE | -| `INV-WS-REVOKE-ACK-001` | A host acknowledges a revocation only after its frontend and cuts have stopped; a cancelled or expired drain sends no acknowledgement. | M4 lease guard: Revoking → Acked | `core/host/volume/workspace_lease.go` `drain` | `TestWorkspaceRevocationAckOnlyAfterFrontendAndCutsStop` (`core/host/volume/workspace_lease_test.go`); `TestWorkspaceHostCancelOrExpiryDuringRevokeDrainNeverACKs` (`core/host/volume/workspace_runtime_test.go`); `TestWorkspaceRevocationAckOutlastsTheMastersBoundedSteps` (`core/host/volume/workspace_ack_budget_test.go`) | `WorkspaceTakeover` `CleanNoLoss` | ACTIVE | +| `INV-WS-REVOKE-ACK-001` | A host acknowledges a revocation only after its frontend and cuts have stopped; a cancelled or expired drain sends no acknowledgement. | M4 lease guard: Revoking → Acked | `core/host/volume/workspace_lease.go` `drain` | `TestWorkspaceRevocationAckOnlyAfterFrontendAndCutsStop` (`core/host/volume/workspace_lease_test.go`); `TestWorkspaceHostCancelOrExpiryDuringRevokeDrainNeverACKs` (`core/host/volume/workspace_runtime_test.go`); `TestWorkspaceRevocationAckOutlastsTheMastersBoundedSteps`, `TestWorkspaceRevocationAckIsCutAtTheLeaseDeadline` (`core/host/volume/workspace_ack_budget_test.go`) | `WorkspaceTakeover` `CleanNoLoss` | ACTIVE | | `INV-WS-STOP-PENDING-001` | From when the detach hook of a chunk detach runs until the lease guard fences, or until that detach's resume clears stop-pending, each sleep of the guard after a completed renewal is at most 250 ms on the local monotonic clock. | M4 lease guard: Valid → StopPending → Valid \| Fenced | `core/host/volume/workspace_lease.go` `StopPending`, `ClearStopPending`, `renewDelay`, `Run`; `core/host/volume/workspace_runtime.go` `WorkspaceStopPending`, `WorkspaceStopResumed`; `core/frontend/durable/provider_chunk.go` `DetachVolume`, `detachVolume`, `resumeAfterDetach`; `cmd/blockvolume/main.go` `run` (wiring) | `TestWorkspaceLeaseStopPendingSchedule`, `TestWorkspaceHostStopResumedClearsOnlyTheLatestAttempt`, `TestWorkspaceHostFailedDetachStopPendingByOutcome`, `TestWorkspaceHostDetachHookFencesWithinPoll`, `TestWorkspaceLeaseStopPendingNeverBlocks` (`core/host/volume/workspace_lease_stop_pending_test.go`); `TestWALStoreChunk_DetachHookPrecedesDrain`, `TestWALStoreChunk_DetachResumeHookOnlyOnProvenAbort`, `TestWALStoreChunk_DetachCallsStopHook` (`core/frontend/durable/provider_chunk_detach_hook_test.go`) | — | ACTIVE | | `INV-WS-SAME-HOST-CLEAN-MOVE-001` | A same-host move issues a higher epoch: a clean move needs the current holder's sealed HEAD and its recorded epoch/holder/position ACK, and the successor reads that sealed image; a forced move needs the normal lease barrier and a durable lost-range record. | M2 Acked or Expired → Moved; M9 detached → higher-epoch idle | `core/authority/workspace.go` `validateWorkspaceMoveRequest`, `prepareWorkspaceMoveLocked`; `core/host/master/workspace_service.go` `workspaceMoveCheckLocked`; `core/frontend/chunkstore/layout/start.go` `Start`, `core/frontend/chunkstore/layout/claim.go` `Claim` | `TestWorkspaceSameHostForcedMoveRecordsLostRange` (`core/authority/workspace_same_host_forced_test.go`); `TestWorkspaceRPCSameHostForcedRecoveryRecordsLoss` (`core/host/master/workspace_same_host_forced_test.go`); `TestWorkspaceSameHostCleanMoveUsesOvernightSeal` (`core/authority/workspace_same_host_clean_test.go`); `TestWorkspaceRPCSameHostCleanMoveKeepsRepreparedBinding` (`core/host/master/workspace_same_host_clean_test.go`); `TestLayoutSameHostCleanSuccessorReadsSealedImage` (`core/frontend/durable/provider_layout_same_host_clean_test.go`) | `WorkspaceRegrant` `SameHostLoadsSealed`; `INV-SNAPK-DETACHED-001`. The B provider test performs a real plain detach, same-host higher-epoch fresh-root Start, and reads the sealed bytes. | ACTIVE | | `INV-WS-DELETE-NO-LIVE-HOLDER-001` | A workspace volume is marked deleting only with no live holder (`TERM-LIVE-HOLDER-001`): no line, a clean revocation ACK for the line, or HEAD below the line's epoch. A sealed HEAD without an ACK, a live or unreadable one is refused; the HEAD compare-and-swap to deleting fences a later claim. | M2 none/Granted/Revoking/Expired → Deleting | `core/authority/workspace_holder_state.go` `WorkspaceHolderState`; `core/authority/workspace.go` `RecordWorkspaceDeletion`; `core/host/master/services.go` `MarkVolumeDeleting`, `deleteHolderEvidence` | `TestWorkspaceHolderState` (`core/authority/workspace_holder_state_test.go`); `TestDeleteAdmitsANeverStartedLine` (`core/host/master/workspace_delete_never_started_test.go`); `TestDeleteAdmissionVerdicts` (`core/authority/workspace_delete_admission_test.go`); `TestMarkVolumeDeleting_RefusedWhileAssigned` (`core/host/master/volume_deleting_test.go`) | NeverStarted r2 `DeleteNeverStrandsALiveHolder`, `NoServedWriteLost`, re-run can finish, re-run can settle (exhaustive, 21 of 21 configurations as expected). Not modelled: two delete processes at the same instant; the gap between HEAD deleted and the volume marked deleted | ACTIVE | @@ -833,7 +833,7 @@ Notes: - Part T fence ownership: `Host.FenceWorkspaceLease` uses `WorkspaceLeaseGuard.fenceLocked`, including before runtime publication; the zero-validity terminal guard preserves the first cause through installation and can grant no I/O. No second host fence latch exists. `TestWorkspaceHostFencePublishesOneTerminalCause`, `TestWorkspaceInstalledHostFenceRecordsCause`, `TestWorkspaceFenceBeforeHeldInstallIsTerminal` (`core/host/volume/workspace_terminal_test.go`). - Startup arbitration: sealed-replay/stale-local-root dispositions suppress the same wait's deadline defer (`TestChunkStartupRetainedDispositionWinsExpiredAttachContext`, `core/frontend/durable/provider_startup_outcome_test.go`). A stop request retires startup monitoring and its atomic-choice callback before resource cleanup; success is chosen only after the guard's ACK (`TestWorkspacePlannedDrainOwnsStartupExpiryUntilAck`, `cmd/blockvolume/process_exit_authority_test.go`). Provider-validated startup selection briefly takes the process startup mutex; cancellation takes only that mutex. No reverse provider-lock acquisition or remote call occurs. -- ACK closeout: the guard sets `revoked` under its mutex before calling `drain` and invoking the stop callback. After a drain reply, its ACK call is bounded by the original lease deadline and the 5 s `WorkspaceAckTimeout` (above the master's 2 s HEAD read plus its ACK write and reconcile). The existing 3 s closeout wait therefore expires before a newly selected retry's 5 s supervisor bound starts; a prior nonzero decision remains immutable. A restart can ACK the sealed HEAD only while the original revoking lease is still valid. Once it expires, re-grant refuses revoking/ACKed leases: repeated 75 is not recovery of an unconfirmed ACK, and operator recovery is required; no lease or ACK gate is bypassed. +- ACK closeout: the guard sets `revoked` under its mutex before calling `drain` and invoking the stop callback. After a drain reply, its ACK call is bounded by the original lease deadline and the 5 s `WorkspaceAckTimeout` (above the master's 2 s HEAD read plus its ACK write and reconcile). The 6 s closeout wait (`WorkspaceAckTimeout` + 1 s) therefore expires before a newly selected retry's 5 s supervisor bound starts; a prior nonzero decision remains immutable. A restart can ACK the sealed HEAD only while the original revoking lease is still valid. Once it expires, re-grant refuses revoking/ACKed leases: repeated 75 is not recovery of an unconfirmed ACK, and operator recovery is required; no lease or ACK gate is bypassed. Notes: From 80d9839b8c67d2ca891100806215b8538d0009bc Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 26 Nov 2026 05:53:32 -0800 Subject: [PATCH 13/14] test(chunkstore): a root read failure on a deleting or deleted volume writes nothing The read-failure case now runs on a deleting and on a deleted HEAD, and also checks the fake filer's update and delete counters: the failed re-run releases no source and deletes no object. Co-Authored-By: Claude Opus 5.5 --- .../chunkstore/catalog_delete_rerun_test.go | 104 ++++++++++-------- 1 file changed, 60 insertions(+), 44 deletions(-) diff --git a/seaweed-block/core/frontend/chunkstore/catalog_delete_rerun_test.go b/seaweed-block/core/frontend/chunkstore/catalog_delete_rerun_test.go index e862b5384f..8e8af5a638 100644 --- a/seaweed-block/core/frontend/chunkstore/catalog_delete_rerun_test.go +++ b/seaweed-block/core/frontend/chunkstore/catalog_delete_rerun_test.go @@ -160,52 +160,68 @@ func TestBCatalog_DeleteRerunSkipsOnlyMissingRootsOfADeletingVolume(t *testing.T } }) - t.Run("read failure of a root of a deleting HEAD", func(t *testing.T) { - c, f, _, _, tgt := rerunFixture(t) - // Interrupt at the source's release: HEAD is deleting, roots intact. - n := 0 - f.mu.Lock() - f.failUpdate = func(string) error { - n++ - if n == 2 { - return errors.New("injected: interrupted") + for _, deleted := range []bool{false, true} { + name := map[bool]string{false: "read failure of a root of a deleting HEAD", true: "read failure of a root of a deleted HEAD"}[deleted] + t.Run(name, func(t *testing.T) { + c, f, _, _, tgt := rerunFixture(t) + root := rootOf(t, f, tgt) + if deleted { + // A completed delete: HEAD deleted, its roots' objects gone. + if _, err := c.DeleteVolume(ctx, tgt, okDeleteAuthority{}); err != nil { + t.Fatal(err) + } + } else { + // Interrupted at the source's release: HEAD deleting, roots intact. + n := 0 + f.mu.Lock() + f.failUpdate = func(string) error { + n++ + if n == 2 { + return errors.New("injected: interrupted") + } + return nil + } + f.mu.Unlock() + if _, err := c.DeleteVolume(ctx, tgt, okDeleteAuthority{}); err == nil { + t.Fatal("fixture: the delete was not interrupted") + } } - return nil - } - f.mu.Unlock() - if _, err := c.DeleteVolume(ctx, tgt, okDeleteAuthority{}); err == nil { - t.Fatal("fixture: the delete was not interrupted") - } - ts, _, err := c.open(tgt) - if err != nil { - t.Fatal(err) - } - before, _, err := ts.ReadHead(ctx) - if err != nil || before.State != layout.StateDeleting { - t.Fatalf("fixture: HEAD %+v %v; want deleting", before, err) - } - root := rootOf(t, f, tgt) - sentinel := errors.New("injected: filer read failed") - f.mu.Lock() - f.failUpdate = nil - f.failLookup = func(p string) error { - if p == root { - return sentinel + ts, _, err := c.open(tgt) + if err != nil { + t.Fatal(err) } - return nil - } - f.mu.Unlock() - skipped, err := c.DeleteVolume(ctx, tgt, okDeleteAuthority{}) - f.mu.Lock() - f.failLookup = nil - f.mu.Unlock() - if !errors.Is(err, sentinel) || len(skipped) != 0 { - t.Fatalf("re-run with a root read failure: skipped=%v err=%v; want the read error and nothing skipped", skipped, err) - } - if after, _, err := ts.ReadHead(ctx); err != nil || after.Gen != before.Gen || after.State != layout.StateDeleting { - t.Fatalf("HEAD after the failed re-run %+v %v; want it unchanged (gen %d, deleting)", after, err, before.Gen) - } - }) + want := map[bool]string{false: layout.StateDeleting, true: layout.StateDeleted}[deleted] + before, _, err := ts.ReadHead(ctx) + if err != nil || before.State != want { + t.Fatalf("fixture: HEAD %+v %v; want %s", before, err, want) + } + sentinel := errors.New("injected: filer read failed") + f.mu.Lock() + f.failUpdate = nil + f.failLookup = func(p string) error { + if p == root { + return sentinel + } + return nil + } + updates, deletes := f.updates, f.deletes + f.mu.Unlock() + skipped, err := c.DeleteVolume(ctx, tgt, okDeleteAuthority{}) + f.mu.Lock() + f.failLookup = nil + updatesAfter, deletesAfter := f.updates, f.deletes + f.mu.Unlock() + if !errors.Is(err, sentinel) || len(skipped) != 0 { + t.Fatalf("re-run with a root read failure: skipped=%v err=%v; want the read error and nothing skipped", skipped, err) + } + if updatesAfter != updates || deletesAfter != deletes { + t.Fatalf("the failed re-run wrote: updates %d -> %d, deletes %d -> %d; want no source release and no object delete", updates, updatesAfter, deletes, deletesAfter) + } + if after, _, err := ts.ReadHead(ctx); err != nil || after.Gen != before.Gen || after.State != want { + t.Fatalf("HEAD after the failed re-run %+v %v; want it unchanged (gen %d, %s)", after, err, before.Gen, want) + } + }) + } t.Run("missing root of a live HEAD", func(t *testing.T) { c, f, _, _, tgt := rerunFixture(t) From eec08968bab3d742245a0a73ac435592f72b8d43 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 26 Nov 2026 05:55:50 -0800 Subject: [PATCH 14/14] test(volume): the lease-deadline control sees the ACK dispatched and its deadline The fake ACK records that it was entered with a live context and the deadline it carried; the test requires DeadlineExceeded, that deadline at the 1 s lease deadline (before the 5 s ACK bound and the caller's), no held lease afterwards and no completed ACK. A pre-dispatch error and an ACK bounded by the parent context alone each fail it. Co-Authored-By: Claude Opus 5.5 --- .../host/volume/workspace_ack_budget_test.go | 53 +++++++++++++++---- 1 file changed, 44 insertions(+), 9 deletions(-) diff --git a/seaweed-block/core/host/volume/workspace_ack_budget_test.go b/seaweed-block/core/host/volume/workspace_ack_budget_test.go index f2fa19b775..39b26590ed 100644 --- a/seaweed-block/core/host/volume/workspace_ack_budget_test.go +++ b/seaweed-block/core/host/volume/workspace_ack_budget_test.go @@ -2,6 +2,8 @@ package volume import ( "context" + "errors" + "sync" "testing" "time" @@ -15,6 +17,17 @@ type slowAckClient struct { delay time.Duration acked chan struct{} valid time.Duration // the revoking lease's validity (default 30 s) + seen *ackCall // what the ACK call was entered with (optional) +} + +// ackCall records the ACK call as dispatched: entered with a live context, +// and the deadline that context carried. +type ackCall struct { + mu sync.Mutex + entered bool + live bool + deadline time.Time + hasDeadline bool } func (c slowAckClient) RenewWorkspaceLease(context.Context, *control.WorkspaceIdentity, ...grpc.CallOption) (*control.WorkspaceLeaseFact, error) { @@ -26,6 +39,12 @@ func (c slowAckClient) RenewWorkspaceLease(context.Context, *control.WorkspaceId } func (c slowAckClient) AckWorkspaceRevoked(ctx context.Context, _ *control.WorkspaceRevocationAck, _ ...grpc.CallOption) (*control.WorkspaceEmpty, error) { + if c.seen != nil { + c.seen.mu.Lock() + c.seen.entered, c.seen.live = true, ctx.Err() == nil + c.seen.deadline, c.seen.hasDeadline = ctx.Deadline() + c.seen.mu.Unlock() + } select { case <-time.After(c.delay): close(c.acked) @@ -60,29 +79,45 @@ func TestWorkspaceRevocationAckOutlastsTheMastersBoundedSteps(t *testing.T) { } // The lease deadline still bounds the ACK: with the revoking lease valid for -// 1 s and a master that answers after 3 s, the ACK call is cancelled at the -// lease deadline (about 1 s), not at WorkspaceAckTimeout (5 s), and the -// revocation is not reported as acknowledged. +// 1 s and a master that answers after 3 s, the ACK call is dispatched with a +// live context whose deadline is the lease deadline (earlier than the 5 s +// ACK bound and the caller's), it ends with DeadlineExceeded at about 1 s, +// and afterwards the guard holds no lease and no ACK completed. func TestWorkspaceRevocationAckIsCutAtTheLeaseDeadline(t *testing.T) { - client := slowAckClient{delay: 3 * time.Second, acked: make(chan struct{}), valid: time.Second} + seen := &ackCall{} + client := slowAckClient{delay: 3 * time.Second, acked: make(chan struct{}), valid: time.Second, seen: seen} g, err := NewWorkspaceLeaseGuard(workspaceTestView{}, client, &control.WorkspaceIdentity{VolumeId: "v", ReplicaId: "r", Epoch: 1}, func(context.Context) (uint64, error) { return 7, nil }, nil) if err != nil { t.Fatal(err) } - ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) + parent := 20 * time.Second + ctx, cancel := context.WithTimeout(context.Background(), parent) defer cancel() start := time.Now() err = g.Run(ctx) elapsed := time.Since(start) - if err == nil { - t.Fatal("an ACK the master answered after the lease ended was reported as acknowledged") + + seen.mu.Lock() + entered, live, deadline, hasDeadline := seen.entered, seen.live, seen.deadline, seen.hasDeadline + seen.mu.Unlock() + if !entered || !live { + t.Fatalf("the ACK was not dispatched with a live context (entered %v, live %v); err %v", entered, live, err) + } + if !errors.Is(err, context.DeadlineExceeded) { + t.Fatalf("err %v; want DeadlineExceeded at the lease deadline", err) + } + if !hasDeadline || !deadline.Before(start.Add(WorkspaceAckTimeout)) || !deadline.Before(start.Add(parent)) || deadline.After(start.Add(1500*time.Millisecond)) { + t.Fatalf("the ACK's deadline %v (set %v) is not the 1 s lease deadline: start %v, ACK bound %v, parent %v", deadline, hasDeadline, start, WorkspaceAckTimeout, parent) } if elapsed >= 2500*time.Millisecond { - t.Fatalf("the ACK ran %v: it was not cut at the 1 s lease deadline (err %v)", elapsed, err) + t.Fatalf("the ACK ran %v: it was not cut at the 1 s lease deadline", elapsed) + } + if g.Held() { + t.Fatal("the guard still holds the lease after its deadline") } select { case <-client.acked: - t.Fatal("the master's late answer was awaited past the lease deadline") + t.Fatal("an ACK completed after the lease deadline") default: } }