From 5fa69f529c6d8d73807287f1af9fdb970288e224 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 29 Nov 2026 15:39:53 -0800 Subject: [PATCH] fix: replay recorded revocation ACK before lease admission --- seaweed-block/core/authority/workspace.go | 23 +++-- .../authority/workspace_ack_recorded_test.go | 93 +++++++++++++++++++ .../core/host/master/workspace_protocol.md | 2 + seaweed-block/docs/design/invariants.md | 3 +- 4 files changed, 110 insertions(+), 11 deletions(-) diff --git a/seaweed-block/core/authority/workspace.go b/seaweed-block/core/authority/workspace.go index ae8d074e53..3bd2de600c 100644 --- a/seaweed-block/core/authority/workspace.go +++ b/seaweed-block/core/authority/workspace.go @@ -318,26 +318,29 @@ func (p *Publisher) AckWorkspaceRevocation(ctx context.Context, volume string, a } p.mu.Lock() defer p.mu.Unlock() - _, line, ok := p.workspaceLineLocked(volume) s := cloneWorkspace(p.workspace[volume]) - if !ok || line.info.ReplicaID != ack.ReplicaID || line.info.Epoch != ack.Epoch || ack.Holder == "" || s == nil || s.Lease == nil || !s.Lease.Revoking { - return fmt.Errorf("workspace revoke ACK: stale or unsolicited") - } if !h.Detached || h.Deleting || h.Epoch != ack.Epoch || h.Holder != ack.Holder { return fmt.Errorf("workspace revoke ACK: no detached HEAD for this holder") } ack.RemoteLSN = h.RemoteLSN + // A matching recorded stop is an answered operation, not a fresh lease + // admission. In particular, losing its answer does not make its retry + // expire. Generation remains readout only; retain the original ACK. + if s != nil && s.Ack != nil { + if s.Ack.ReplicaID != ack.ReplicaID || s.Ack.Epoch != ack.Epoch || s.Ack.Holder != ack.Holder || s.Ack.RemoteLSN != ack.RemoteLSN { + return fmt.Errorf("workspace revoke ACK changed") + } + return nil + } + _, line, ok := p.workspaceLineLocked(volume) + if !ok || line.info.ReplicaID != ack.ReplicaID || line.info.Epoch != ack.Epoch || ack.Holder == "" || s == nil || s.Lease == nil || !s.Lease.Revoking { + return fmt.Errorf("workspace revoke ACK: stale or unsolicited") + } lease := *s.Lease lease.ExpiresAtNS = min(lease.ExpiresAtNS, p.leaseDeadlineLocked(volume).UnixNano()) if p.WorkspaceLeaseValidity(lease) == 0 { return fmt.Errorf("workspace revoke ACK: lease expired; forced move required") } - if s.Ack != nil { - if s.Ack.ReplicaID != ack.ReplicaID || s.Ack.Epoch != ack.Epoch || s.Ack.Holder != ack.Holder || s.Ack.RemoteLSN != ack.RemoteLSN { - return fmt.Errorf("workspace revoke ACK changed") - } - return nil // generation is readout only; retain the original ACK - } s.Ack = &ack return p.persistWorkspaceLocked(volume, s) } diff --git a/seaweed-block/core/authority/workspace_ack_recorded_test.go b/seaweed-block/core/authority/workspace_ack_recorded_test.go index f6771869d6..d442e537f6 100644 --- a/seaweed-block/core/authority/workspace_ack_recorded_test.go +++ b/seaweed-block/core/authority/workspace_ack_recorded_test.go @@ -2,6 +2,12 @@ package authority import ( "context" + "github.com/seaweedfs/seaweed-block/core/frontend" + hostvolume "github.com/seaweedfs/seaweed-block/core/host/volume" + "github.com/seaweedfs/seaweed-block/core/rpc/control" + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" "reflect" "testing" "time" @@ -24,6 +30,7 @@ func TestRecordedRevocationAckRetryAfterDeadline(t *testing.T) { t.Fatal(err) } recorded := p.WorkspaceState("v") + writes := len(store.records) clock.at(100) // the caller lost the answer and repeats after both deadlines if p.WorkspaceLeaseValidity(*recorded.Lease) != 0 { t.Fatal("fixture lease still valid") @@ -32,6 +39,9 @@ func TestRecordedRevocationAckRetryAfterDeadline(t *testing.T) { t.Fatalf("recorded ACK retry after deadline: %v", err) } // Replaying the witness must not persist or renew anything. + if len(store.records) != writes { + t.Fatal("retry wrote the authority store") + } if !reflect.DeepEqual(recorded, p.WorkspaceState("v")) { t.Fatal("retry changed the recorded state") } @@ -51,3 +61,86 @@ func TestRecordedRevocationAckRetryAfterDeadline(t *testing.T) { t.Fatal("changed retry modified the recorded state") } } + +// This adapter uses the production publisher for both operations; only the +// first committed ACK's answer is lost and the master clock is advanced. +type expiredRecordedAckClient struct { + p *Publisher + clock *testClock + calls int +} + +func (c *expiredRecordedAckClient) RenewWorkspaceLease(ctx context.Context, id *control.WorkspaceIdentity, _ ...grpc.CallOption) (*control.WorkspaceLeaseFact, error) { + l, e := c.p.RenewWorkspaceLease(ctx, id.VolumeId, id.ReplicaId, id.Epoch) + if e != nil { + return nil, e + } + return &control.WorkspaceLeaseFact{VolumeId: id.VolumeId, ReplicaId: l.ReplicaID, Epoch: l.Epoch, ValidForNs: int64(c.p.WorkspaceLeaseValidity(l)), Revoking: l.Revoking}, nil +} +func (c *expiredRecordedAckClient) AckWorkspaceRevoked(ctx context.Context, q *control.WorkspaceRevocationAck, _ ...grpc.CallOption) (*control.WorkspaceEmpty, error) { + c.calls++ + id := q.Identity + e := c.p.AckWorkspaceRevocation(ctx, id.VolumeId, WorkspaceRevokeAck{ReplicaID: id.ReplicaId, Epoch: id.Epoch, Holder: "host/r", HeadGen: q.HeadGen}, WorkspaceHead{Detached: true, Epoch: id.Epoch, Holder: "host/r", RemoteLSN: 42}) + if e != nil { + return nil, status.Error(codes.FailedPrecondition, e.Error()) + } + if c.calls == 1 { + c.clock.at(100) + return nil, status.Error(codes.DeadlineExceeded, "injected lost reply after ACK commit") + } + return &control.WorkspaceEmpty{}, nil +} + +type recordedAckProjection struct{} + +func (recordedAckProjection) Projection() frontend.Projection { + return frontend.Projection{VolumeID: "v", ReplicaID: "r", Epoch: 1, Healthy: true} +} + +func TestRecordedAckLostReplyAfterMasterDeadlineDrainsWithoutRetryExit(t *testing.T) { + clock := newTestClock() + p := newLeasePublisher(t, &failingStore{}, 30*time.Second, clock) + bindAndGrant(t, p, "v", "r") + c := &expiredRecordedAckClient{p: p, clock: clock} + stops := 0 + g, e := hostvolume.NewWorkspaceLeaseGuard(recordedAckProjection{}, c, &control.WorkspaceIdentity{VolumeId: "v", ReplicaId: "r", Epoch: 1, ServerId: "host"}, func(context.Context) (uint64, error) { stops++; return 7, nil }, nil) + if e != nil { + t.Fatal(e) + } + ctx := context.Background() + if e = g.Refresh(ctx); e != nil { + t.Fatal(e) + } + if e = p.BeginWorkspaceRevocation(ctx, "v", "r", 1); e != nil { + t.Fatal(e) + } + if e = g.Refresh(ctx); e != nil { + t.Fatalf("drain returned an error that would trigger exit 75: %v", e) + } + if c.calls != 2 || stops != 1 { + t.Fatalf("ACK calls=%d stops=%d; want two calls and one drain", c.calls, stops) + } + st := p.WorkspaceState("v") + if st.Ack == nil || p.WorkspaceLeaseValidity(*st.Lease) != 0 || g.Projection().Healthy { + t.Fatal("fixture did not end ACKed, expired and stopped") + } +} + +func TestUnrecordedRevocationAckStillRefusesAfterDeadline(t *testing.T) { + clock := newTestClock() + store := &failingStore{} + p := newLeasePublisher(t, store, time.Second, clock) + bindAndGrant(t, p, "v", "r") + ctx := context.Background() + if e := p.BeginWorkspaceRevocation(ctx, "v", "r", 1); e != nil { + t.Fatal(e) + } + writes := len(store.records) + clock.at(100) + if e := p.AckWorkspaceRevocation(ctx, "v", WorkspaceRevokeAck{ReplicaID: "r", Epoch: 1, Holder: "host/r", HeadGen: 7}, WorkspaceHead{Detached: true, Epoch: 1, Holder: "host/r", RemoteLSN: 42}); e == nil { + t.Fatal("expired first ACK admitted") + } + if p.WorkspaceState("v").Ack != nil || len(store.records) != writes { + t.Fatal("expired first ACK wrote state") + } +} diff --git a/seaweed-block/core/host/master/workspace_protocol.md b/seaweed-block/core/host/master/workspace_protocol.md index c6dd07eadb..5af07ac3c9 100644 --- a/seaweed-block/core/host/master/workspace_protocol.md +++ b/seaweed-block/core/host/master/workspace_protocol.md @@ -153,3 +153,5 @@ target_replica_id must be equal. ID-changing requests are refused before any move journal or authority epoch is persisted. Dynamic subscription/peer changes for a different logical slot are outside v1. Use the existing logical replica ID for CLEAN and FORCED moves. + +An ACK retry matching a recorded stop (replica, epoch, holder and stopped position) returns the recorded success before lease admission checks, even after the deadline; it writes nothing and extends no lease. A first ACK after expiry remains refused. RPC caller identity and detached-HEAD stop checks still apply; HEAD generation is readout only. diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index a0d5e012a4..478101e2a6 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -220,7 +220,7 @@ a pre-issued publication. | none | Granted | `RenewWorkspaceLease` from the current primary (server id, replica id) at the current epoch; a missing/foreign server is refused by RPC holderMatches (registered server id, gRPC peer on its registered host: `refuseWorkspaceHolderHost`); no move pending; the first grant is written synchronously and persists the durable horizon now + 1.5·TTL (an epoch issued by a move already has its lease) | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `firstWorkspaceGrant`; `core/host/master/workspace_service.go` `holderMatches` | `INV-WS-LEASE-001`, `INV-WS-LEASE-HORIZON-001`, `INV-AUTH-HOLDER-IDENTITY-001` | | Granted | Granted | current primary server/replica/epoch required by RPC holderMatches (registered server id, gRPC peer on its registered host: `refuseWorkspaceHolderHost`) (missing server refused); renew from memory (the lease view, leaf lock only) before the durable horizon and the granted deadline; the grant is min(now + TTL, horizon), refused with an error when it would leave no host validity (grant − skew/2 ≤ now); an extender, an ordinary writer under the publisher lock, raises the horizon to trigger + 1.5·TTL | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `extendWorkspaceLease`; `core/host/master/workspace_service.go` `holderMatches` | `INV-WS-LEASE-001`, `INV-WS-LEASE-HORIZON-001`, `INV-WS-LEASE-HORIZON-MONO-001`, `INV-WS-RENEW-NONBLOCKING-001`, `INV-LEASE-VIEW-001`, `INV-WS-FORCED-MOVE-REPLY-001`, `INV-WS-FORCED-MOVE-HALF-SKEW-001`, `INV-AUTH-HOLDER-IDENTITY-001` | | Granted | Revoking | `BeginWorkspaceRevocation` for the matching lease; a renew now returns the revoking lease with the granted expiry, min(horizon, deadline), without extending it | `core/authority/workspace.go` `BeginWorkspaceRevocation`; `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `WorkspaceLeaseReply` | `INV-WS-CLEAN-MOVE-001`, `INV-WS-FORCED-MOVE-REPLY-001` | -| Revoking | Acked | `AckWorkspaceRevocation` from the primary server/replica at the current epoch, validated by the same RPC holderMatches (registered server id, gRPC peer on its registered host: `refuseWorkspaceHolderHost`) (missing/foreign server refused), an authoritative detached HEAD matching the ACK epoch/holder/position, positive granted validity after half the configured/persisted skew on the publisher clock; a different second acknowledgement is refused | `core/authority/workspace.go` `AckWorkspaceRevocation`; `core/host/master/workspace_service.go` `holderMatches` | `INV-WS-CLEAN-MOVE-001`, `INV-WS-REVOKE-ACK-001`, `INV-AUTH-HOLDER-IDENTITY-001` | +| Revoking | Acked | `AckWorkspaceRevocation` from the primary server/replica at the current epoch, validated by the same RPC holderMatches (registered server id, gRPC peer on its registered host: `refuseWorkspaceHolderHost`) (missing/foreign server refused), an authoritative detached HEAD matching the ACK epoch/holder/position, for a first ACK, positive granted validity after half the configured/persisted skew on the publisher clock; a matching recorded stop answers before any lease check without writing, while a different second acknowledgement is refused | `core/authority/workspace.go` `AckWorkspaceRevocation`; `core/host/master/workspace_service.go` `holderMatches` | `INV-WS-CLEAN-MOVE-001`, `INV-WS-REVOKE-ACK-001`, `INV-AUTH-HOLDER-IDENTITY-001` | | Acked | Moved (clean) | HEAD detached by the expected holder at the expected epoch, and the acknowledgement names that HEAD generation; the target may be the same host, with a newly issued epoch and every binding/collision/isolation check retained | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `validateWorkspaceMoveRequest`; `core/host/master/workspace_service.go` `workspaceMoveCheckLocked` | `INV-WS-CLEAN-MOVE-001`, `INV-WS-SAME-HOST-CLEAN-MOVE-001` | | Acked or Expired | (move refused, nothing written) | blockmaster admits a move only with valid target endpoints (host:port, port 1..65535, data and ctrl distinct), a known source host, a registered target node (including the source host; clean proof or forced-move lease barrier still required), and target endpoints that either match a live per-volume binding or, for a volume without bindings, lie on the target node's registered hosts (any port) and are not owned by another assignment or binding, and, under strict journal isolation, a target node whose durable root does not share the authority store's file system (the retry of an issued move excepted); each refusal names its condition and is logged | `core/host/master/workspace_service.go` `MoveWorkspace`, `workspaceMoveCheckLocked`; `core/host/master/journal_isolation.go` `colocatedTargetRefused` | `INV-WS-CLEAN-MOVE-001`, `INV-WS-FORCED-MOVE-001`, `INV-MASTER-JOURNAL-ISOLATION-001` | | Granted or Revoking | Expired | the durable horizon or the granted deadline passes | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`; `core/authority/workspace.go` `AckWorkspaceRevocation` | `INV-WS-FORCED-MOVE-001` | @@ -833,6 +833,7 @@ Notes: | `INV-WS-SINGLE-FILER-001` | A chunk volume starts only when `--chunk-filer` is its group's only filer, confirmed in a round where every master answered: a master listing another filer or several refuses at once; an unanswered master leaves the round unconfirmed; 60 s unconfirmed is refused. A startup census, not a fence. | M4 (startup) → Refused | `core/frontend/chunkstore/single_filer.go` `CheckSingleFiler`; `cmd/blockvolume/chunk_remote.go` `newChunkWiring`; `cmd/sw-block/chunk.go` `refuseUnlessSingleFiler` | `TestCheckSingleFilerRefusesAnotherOrSeveralFilers`, `TestCheckSingleFilerFailsClosed`, `TestCheckSingleFilerNeedsEveryMasterToAnswer`, `TestIsTargetComparesScopedAddresses`, `TestCheckSingleFilerPasses` (`core/frontend/chunkstore/single_filer_test.go`), `TestChunkWiringRefusesAMultiFilerGroup` (`cmd/blockvolume/single_filer_test.go`), `TestOpsChunk_WritingCommandsRunTheSingleFilerCheck` (`cmd/sw-block/chunk_start_check_test.go`), `TestOpsChunk_StartCheckRefusesAnUnparsableMaster` (`cmd/sw-block/chunk_single_filer_unanswered_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-RECORDED-001` | A matching recorded revocation stop is answered before lease checks without writing or extending the lease. An expired lease still refuses a first ACK, and a changed replica, epoch, holder or stopped position never replays another ACK. | M2 revocation ACK replay, no state change | `core/authority/workspace.go` `AckWorkspaceRevocation` | `TestRecordedRevocationAckRetryAfterDeadline`, `TestRecordedAckLostReplyAfterMasterDeadlineDrainsWithoutRetryExit`, `TestUnrecordedRevocationAckStillRefusesAfterDeadline` | WorkspaceTakeover CleanNoLoss; replay stutters | 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`); `TestWorkspaceRevocationAckIsAskedAgainAfterALostAnswer`, `TestWorkspaceCloseoutFitsTheUnitsStopBudget` (`cmd/blockvolume/process_exit_ack_retry_test.go`) | `WorkspaceTakeover` `CleanNoLoss` | ACTIVE | | `INV-WS-REVOKE-ACK-RETRY-001` | A holder's revocation ACK is asked again only after a call that got no answer (`DeadlineExceeded`, `Unavailable`), within its lease deadline and the units' stop budget (19 s closeout); the master answers a repeat of a recorded ACK as recorded while the line is revoking. | M4 lease guard: Revoking → Acked; M2 Revoking → Revoked | `core/host/volume/workspace_lease.go` `drain`, `retryableAckError`; `cmd/blockvolume/process_exit.go` `workspaceLeaseCloseoutTimeout`; `core/authority/workspace.go` `AckWorkspaceRevocation` (a repeat returns nil) | `TestWorkspaceRevocationAckIsAskedAgainAfterALostAnswer`, `TestWorkspaceCloseoutFitsTheUnitsStopBudget` (`cmd/blockvolume/process_exit_ack_retry_test.go`); `TestWorkspaceRevocationAckIsCutAtTheLeaseDeadline` (`core/host/volume/workspace_ack_budget_test.go`); `TestWorkspaceRevocationAckRetryAgainstTheRealMaster` (`core/host/master/workspace_ack_retry_test.go`) | — | 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 |