diff --git a/seaweed-block/core/authority/authority.go b/seaweed-block/core/authority/authority.go index cdf988bbbe..f14d05376b 100644 --- a/seaweed-block/core/authority/authority.go +++ b/seaweed-block/core/authority/authority.go @@ -152,7 +152,8 @@ type Publisher struct { // behaves as "never bound" until a new mint. loadErrs []error - observer PublishObserver + observer PublishObserver + publicationAdmission PublicationAdmission // Workspace state is serialized with assignment minting under mu. Remote // HEAD reads and subscriber delivery never run under this lock. @@ -163,6 +164,15 @@ type Publisher struct { workspaceLeaseDeadline map[string]time.Time } +// PublicationAdmission surrounds an ordinary mint with local ownership/lifetime +// admission. It must call publish synchronously, at most once, and must not do +// remote I/O. Configure only before Run. Guarded moves already own host admission. +type PublicationAdmission func(AssignmentAsk, func() error) error + +func WithPublicationAdmission(admit PublicationAdmission) PublisherOption { + return func(p *Publisher) { p.publicationAdmission = admit } +} + // PublisherOption configures a Publisher at construction. // Currently the only option is WithStore, but the variadic // shape is chosen so later slices can add options without @@ -416,6 +426,9 @@ func (p *Publisher) closeAllSubscriptions() { // non-zero Epoch. The structural non-forgeability test in // authority_test.go enforces this boundary at repo scope. func (p *Publisher) apply(ask AssignmentAsk) error { + if p.publicationAdmission != nil { + return p.publicationAdmission(ask, func() error { return p.applyWithWorkspaceMove(ask, nil) }) + } return p.applyWithWorkspaceMove(ask, nil) } diff --git a/seaweed-block/core/host/bootstrap/bootstrap.go b/seaweed-block/core/host/bootstrap/bootstrap.go index 2b6bf2c4a8..19e6a32dcb 100644 --- a/seaweed-block/core/host/bootstrap/bootstrap.go +++ b/seaweed-block/core/host/bootstrap/bootstrap.go @@ -43,7 +43,8 @@ type DurableAuthorityBootstrap struct { // Options customizes durable-authority bootstrap wiring. type Options struct { - PublishObserver authority.PublishObserver + PublishObserver authority.PublishObserver + PublicationAdmission authority.PublicationAdmission } // Bootstrap performs the durable-authority startup sequence and @@ -116,6 +117,7 @@ func bootstrapFromStoreLocked(storeDir string, lock *authority.StoreLock, store if opts.PublishObserver != nil { pubOpts = append(pubOpts, authority.WithPublishObserver(opts.PublishObserver)) } + pubOpts = append(pubOpts, authority.WithPublicationAdmission(opts.PublicationAdmission)) pub := authority.NewPublisher(directive, pubOpts...) // Publisher's LoadErrors is the canonical source; prefer it diff --git a/seaweed-block/core/host/master/host.go b/seaweed-block/core/host/master/host.go index 91c4da613a..a829f0a713 100644 --- a/seaweed-block/core/host/master/host.go +++ b/seaweed-block/core/host/master/host.go @@ -206,7 +206,8 @@ func New(cfg Config) (*Host, error) { } boot, err := bootstrap.BootstrapWithOptions(cfg.AuthorityStoreDir, ctrl, bootstrap.Options{ - PublishObserver: h.recordAuthorityPublishedEvent, + PublishObserver: h.recordAuthorityPublishedEvent, + PublicationAdmission: h.admitWorkspacePublication, }) if err != nil { return nil, fmt.Errorf("master.New: Bootstrap: %w", err) diff --git a/seaweed-block/core/host/master/product_loop_test.go b/seaweed-block/core/host/master/product_loop_test.go index 0b76bf1973..b8d9cbeed9 100644 --- a/seaweed-block/core/host/master/product_loop_test.go +++ b/seaweed-block/core/host/master/product_loop_test.go @@ -730,6 +730,7 @@ func TestG15c_ProductLoopReconcilesCreatedVolumeBeforePublishing(t *testing.T) { } func seedVerifiedExistingReplicaPlacement(t *testing.T, h *Host) { + ensureProductVolume(t, h, "vol-a", 1) t.Helper() stores := h.Lifecycle() if _, err := stores.Placements.ApplyPlan(lifecycle.PlacementPlan{ @@ -774,6 +775,7 @@ func seedRF2PlacementFor(t *testing.T, h *Host, volumeID string) { } func seedRF2PlacementForServers(t *testing.T, h *Host, volumeID, r1ServerID, r2ServerID string) { + ensureProductVolume(t, h, volumeID, 2) t.Helper() stores := h.Lifecycle() if _, err := stores.Placements.ApplyPlan(lifecycle.PlacementPlan{ @@ -855,6 +857,7 @@ func ingestRF2ObservationForServers(t *testing.T, h *Host, volumeID, r1ServerID, } func seedRF3PlacementForServers(t *testing.T, h *Host, volumeID, r1ServerID, r2ServerID, r3ServerID string) { + ensureProductVolume(t, h, volumeID, 3) t.Helper() stores := h.Lifecycle() if _, err := stores.Placements.ApplyPlan(lifecycle.PlacementPlan{ @@ -871,6 +874,7 @@ func seedRF3PlacementForServers(t *testing.T, h *Host, volumeID, r1ServerID, r2S } func seedRF3PlacementForServersWithAddrs(t *testing.T, h *Host, volumeID, r1ServerID, r2ServerID, r3ServerID string) { + ensureProductVolume(t, h, volumeID, 3) t.Helper() stores := h.Lifecycle() if _, err := stores.Placements.ApplyPlan(lifecycle.PlacementPlan{ @@ -994,3 +998,15 @@ func recvAssignmentInfo(t *testing.T, ch <-chan adapter.AssignmentInfo) adapter. return adapter.AssignmentInfo{} } } + +// Placement fixtures represent live lifecycle volumes, just as production +// CreateVolume/ReconcilePlacement do before asking Publisher to mint authority. +func ensureProductVolume(t *testing.T, h *Host, volume string, rf int) { + t.Helper() + if _, ok := h.Lifecycle().Volumes.GetVolume(volume); ok { + return + } + if _, err := h.Lifecycle().Volumes.CreateVolume(lifecycle.VolumeSpec{VolumeID: volume, SizeBytes: 1 << 20, ReplicationFactor: rf}); err != nil { + t.Fatal(err) + } +} diff --git a/seaweed-block/core/host/master/workspace_binding.go b/seaweed-block/core/host/master/workspace_binding.go index e8a8462834..10bc3e57a8 100644 --- a/seaweed-block/core/host/master/workspace_binding.go +++ b/seaweed-block/core/host/master/workspace_binding.go @@ -4,6 +4,7 @@ import ( "context" "fmt" + "github.com/seaweedfs/seaweed-block/core/authority" "github.com/seaweedfs/seaweed-block/core/lifecycle" control "github.com/seaweedfs/seaweed-block/core/rpc/control" ) @@ -150,3 +151,50 @@ func (s *services) PlaceWorkspace(ctx context.Context, q *control.WorkspacePlace } return &control.WorkspaceEmpty{}, nil } + +// admitWorkspacePublication owns the last local boundary before an ordinary +// Publisher mint. Guarded Move already owns workspaceMu in its RPC path. +func (h *Host) admitWorkspacePublication(ask authority.AssignmentAsk, publish func() error) error { + if h.lifecycle == nil { + return publish() + } + h.workspaceMu.Lock() + defer h.workspaceMu.Unlock() + if _, alive := h.lifecycle.Volumes.GetVolume(ask.VolumeID); !alive { + return fmt.Errorf("workspace publication: volume no longer exists") + } + bindings, bound, err := h.lifecycle.WorkspaceBindings.Get(ask.VolumeID) + if err != nil { + return err + } + var epoch uint64 + if line, ok := h.Publisher().VolumeAuthorityLine(ask.VolumeID); ok { + epoch = line.Epoch + } + server := h.workspaceSourceHost(ask.VolumeID, ask.ReplicaID, epoch) + b := lifecycle.WorkspaceBinding{VolumeID: ask.VolumeID, ServerID: server, DataAddr: ask.DataAddr, CtrlAddr: ask.CtrlAddr} + if bound { + matched := false + for _, r := range bindings { + if !r.Retired && r.ServerID == server && r.DataAddr == ask.DataAddr && r.CtrlAddr == ask.CtrlAddr { + matched = true + break + } + } + if !matched { + return fmt.Errorf("workspace publication: no matching active binding") + } + } + if err := h.lifecycle.WorkspaceBindings.CheckAvailable(b); err != nil { + return err + } + // A supported snapshot and its direct promotion fallback may both be + // dequeued before either commits. Apply the product loop's existing + // already-current check again here, rather than advancing the epoch twice. + if ask.Intent == authority.IntentReassign && h.assignmentAskAlreadyCurrent(ask.VolumeID, ask.ReplicaID, ask.DataAddr, ask.CtrlAddr) { + return nil + } + // The same mutex covers Register/Delete. It stays held through the actual + // Publisher persistence and in-memory commit, not just queue admission. + return publish() +} diff --git a/seaweed-block/core/host/master/workspace_binding_review_test.go b/seaweed-block/core/host/master/workspace_binding_review_test.go index 1d6dcaa226..7a1fabe73e 100644 --- a/seaweed-block/core/host/master/workspace_binding_review_test.go +++ b/seaweed-block/core/host/master/workspace_binding_review_test.go @@ -21,11 +21,19 @@ func reviewBindingHost(t *testing.T) (*Host, *grpc.ClientConn, context.Context) } func reviewBindingHostWithReader(t *testing.T, reader func(context.Context, string) (authority.WorkspaceHead, error)) (*Host, *grpc.ClientConn, context.Context) { + t.Helper() + return reviewBindingHostBeforeStart(t, reader, nil) +} + +func reviewBindingHostBeforeStart(t *testing.T, reader func(context.Context, string) (authority.WorkspaceHead, error), before func(*Host)) (*Host, *grpc.ClientConn, context.Context) { t.Helper() h, e := New(Config{Listen: "127.0.0.1:0", AuthorityStoreDir: t.TempDir(), LifecycleStoreDir: t.TempDir(), WorkspaceRPC: true, WorkspaceHeadReader: reader}) if e != nil { t.Fatal(e) } + if before != nil { + before(h) + } h.Start() t.Cleanup(func() { closeTestMaster(t, h) }) c, e := grpc.NewClient(h.Addr(), grpc.WithTransportCredentials(insecure.NewCredentials())) @@ -116,6 +124,23 @@ func TestWorkspaceBindingDeleteCannotReleaseLiveAuthority(t *testing.T) { if _, bound, e := h.Lifecycle().WorkspaceBindings.Get("live"); e != nil || !bound { t.Fatal("refused deletion removed binding", bound, e) } + id := &control.WorkspaceIdentity{VolumeId: "live", ReplicaId: "r1", Epoch: 1} + if _, e := client.RevokeWorkspace(ctx, id); e != nil { + t.Fatal(e) + } + if _, e := client.AckWorkspaceRevoked(ctx, &control.WorkspaceRevocationAck{Identity: id, HeadGen: 9}); e != nil { + t.Fatal(e) + } + if _, e := control.NewLifecycleServiceClient(c).DeleteVolume(ctx, &control.DeleteVolumeRequest{VolumeId: "live"}); e != nil { + t.Fatal("clean retired deletion positive", e) + } + reviewCreate(t, c, ctx, "reuse") + b.VolumeId = "reuse" + b.ServerId = "node-b" + if _, e := client.RegisterWorkspaceBinding(ctx, b); e != nil { + t.Fatal("retired pair not reusable after clean delete", e) + } + } func TestWorkspaceBindingCanceledQueuedDeleteDoesNotMutate(t *testing.T) { @@ -239,6 +264,9 @@ func TestWorkspaceBindingRemoteReadDoesNotBlockAck(t *testing.T) { done <- e }() } else { + if _, e := h.Lifecycle().Volumes.CreateVolume(lifecycle.VolumeSpec{VolumeID: "vol-rf3", SizeBytes: 1 << 20, ReplicationFactor: 3}); e != nil { + t.Fatal(e) + } seedRF3Placement(t, h) ingestRF3Observation(t, h, true, true, true) if _, e := h.RunLifecycleProductTick(); e != nil { @@ -277,3 +305,97 @@ func (p reviewHeldPromotion) ProbePromotionCandidates(string, authority.Authorit <-p.release return PromotionProbeResult{}, nil } + +// The real controller dequeues the admitted ask, then its Publisher is held +// before the production admission/mint boundary. Queue discard cannot pass this. +func TestWorkspaceBindingInFlightPublicationRechecksOwnershipAndLifetime(t *testing.T) { + for _, action := range []string{"register", "delete"} { + t.Run(action, func(t *testing.T) { + arrived, release := make(chan struct{}), make(chan struct{}) + finished := make(chan error, 1) + h, c, ctx := reviewBindingHostBeforeStart(t, func(context.Context, string) (authority.WorkspaceHead, error) { return authority.WorkspaceHead{}, nil }, func(h *Host) { + authority.WithPublicationAdmission(func(ask authority.AssignmentAsk, publish func() error) error { + if ask.VolumeID == "inflight" { + close(arrived) + select { + case <-release: + case <-time.After(5 * time.Second): + return context.DeadlineExceeded + } + } + err := h.admitWorkspacePublication(ask, publish) + if ask.VolumeID == "inflight" { + finished <- err + } + return err + })(h.Publisher()) + }) + reviewCreate(t, c, ctx, "inflight") + if _, e := h.Lifecycle().Placements.ApplyPlan(lifecycle.PlacementPlan{VolumeID: "inflight", DesiredRF: 1, Candidates: []lifecycle.PlacementCandidate{{VolumeID: "inflight", ServerID: "node-a", ReplicaID: "r1", Source: lifecycle.PlacementSourceExistingReplica}}}); e != nil { + t.Fatal(e) + } + reviewHeartbeat(t, c, ctx, "inflight", "node-a", "127.0.0.1:10000", "127.0.0.1:10001") + if _, e := h.RunLifecycleProductTick(); e != nil { + t.Fatal(e) + } + select { + case <-arrived: + case <-ctx.Done(): + t.Fatal("publisher did not dequeue ask", ctx.Err()) + } + defer func() { + select { + case <-release: + default: + close(release) + } + }() + if action == "delete" { + if _, e := control.NewLifecycleServiceClient(c).DeleteVolume(ctx, &control.DeleteVolumeRequest{VolumeId: "inflight"}); e != nil { + t.Fatal("unassigned legacy delete", e) + } + if _, ok := h.Lifecycle().Volumes.GetVolume("inflight"); ok { + t.Fatal("delete did not remove volume") + } + } + reviewCreate(t, c, ctx, "owner") + wc := control.NewWorkspaceServiceClient(c) + reserve := func() { + if _, e := wc.RegisterWorkspaceBinding(ctx, &control.WorkspaceBinding{VolumeId: "owner", ServerId: "node-b", DataAddr: "127.0.0.1:10000", CtrlAddr: "127.0.0.1:10001"}); e != nil { + t.Fatal("reservation", e) + } + } + if action == "register" { + reserve() + } + close(release) + select { + case e := <-finished: + if e == nil { + t.Error("held stale ask was published after competing " + action) + } + case <-ctx.Done(): + t.Fatal("publisher did not settle", ctx.Err()) + } + if line, ok := h.Publisher().VolumeAuthorityLine("inflight"); ok { + t.Fatal("stale or deleted ask minted authority", line) + } + if action == "delete" { + reserve() + } + st, e := wc.QueryWorkspace(ctx, &control.WorkspaceVolume{VolumeId: "owner"}) + if e != nil || len(st.GetBindings()) != 1 { + t.Fatal("owner reservation lost", st, e) + } + // An unrelated, matching explicit owner can still reach the actual publisher. + if _, e = wc.PlaceWorkspace(ctx, &control.WorkspacePlacement{VolumeId: "owner", ServerId: "node-b", ReplicaId: "r1"}); e != nil { + t.Fatal(e) + } + reviewHeartbeat(t, c, ctx, "owner", "node-b", "127.0.0.1:10000", "127.0.0.1:10001") + if _, e = h.RunLifecycleProductTick(); e != nil { + t.Fatal(e) + } + waitAuthorityLine(t, h.Publisher(), "owner") + }) + } +} diff --git a/seaweed-block/core/host/master/workspace_protocol.md b/seaweed-block/core/host/master/workspace_protocol.md index b503342617..46f8971705 100644 --- a/seaweed-block/core/host/master/workspace_protocol.md +++ b/seaweed-block/core/host/master/workspace_protocol.md @@ -47,7 +47,15 @@ a crash between authority persistence and binding retirement is recoverable. Host workspace mutations serialize with `workspaceMu`. Remote HEAD reads and promotion probes run outside it; local intent, binding and reservation checks are -repeated under the lock before queueing or committing their results. +repeated under the lock before queueing or committing their results. Ordinary +Publisher mints also acquire that same host lock before checking the live volume, +current binding owner/pair and reservations, and retain it through authority +persistence/commit. The existing already-current product check is repeated for +ordinary Reassign asks here, so a snapshot plus its direct promotion fallback +cannot mint duplicate epochs after both were dequeued. Dequeued legacy asks therefore cannot bypass a later binding +or publish after successful deletion. Hosts without lifecycle stores retain their +static authority path. Guarded Move already holds this boundary and does not +recursively acquire it. Lock order is host workspace mutex, then Publisher or lifecycle-store locks. Initial placement persists under a Publisher unassigned guard; its callback must never call Publisher. Store reads do not hold their mutex while calling