From 613c5d478909c21c179d3c752a1eff51fb047156 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 26 Nov 2026 04:13:25 -0800 Subject: [PATCH 1/3] 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 48e77c05b8ea2f6ad7a96f31752939c8bc7f9ee9 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 26 Nov 2026 04:19:30 -0800 Subject: [PATCH 2/3] 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 49389c8bd5118f2f4f687a8cae9e797fe9703258 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 26 Nov 2026 04:41:21 -0800 Subject: [PATCH 3/3] 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{