From 1da0c2905dbbb1e1033cbf64ed26b296c82ddfc6 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 03:22:28 -0800 Subject: [PATCH] fix: use guard fence ownership and one workspace exit decision --- seaweed-block/cmd/blockvolume/process_exit.go | 21 ++++++++--------- seaweed-block/core/host/volume/host.go | 3 +-- .../core/host/volume/workspace_runtime.go | 23 ++++++++++++++----- .../host/volume/workspace_terminal_test.go | 3 +++ .../docs/design/agent-workspace-design.md | 2 ++ seaweed-block/docs/design/invariants.md | 5 ++-- 6 files changed, 35 insertions(+), 22 deletions(-) diff --git a/seaweed-block/cmd/blockvolume/process_exit.go b/seaweed-block/cmd/blockvolume/process_exit.go index f19b2c6b71..f1f5925e3b 100644 --- a/seaweed-block/cmd/blockvolume/process_exit.go +++ b/seaweed-block/cmd/blockvolume/process_exit.go @@ -118,10 +118,10 @@ func reportWorkspaceExit(out workspaceExit) int { return out.code } -// INV-WS-STARTUP-RETRY-001: only a newer other-replica authority fact -// permits no-retry. Host owns the lineage observation and shared predicate. -func workspaceRetryOutcome(reason string, h *volume.Host) workspaceExit { - if h.IsCurrentReplicaSuperseded() { +// INV-WS-STARTUP-RETRY-001: one decision combines a newer other-replica +// authority fact and the provider's generation-bound foreign-HEAD proof. +func workspaceRetryOutcome(reason string, h *volume.Host, claimSuperseded bool) workspaceExit { + if claimSuperseded || h.IsCurrentReplicaSuperseded() { return workspaceExit{exitWorkspaceSuperseded, "superseded"} } return workspaceExit{exitWorkspaceRetry, reason} @@ -161,7 +161,7 @@ func waitWorkspaceStop(e *processExit, f flags, h *volume.Host, requests <-chan e.stopChunkStartup() out := workspaceExit{reason: "revoked"} if !h.WorkspaceLeaseRevoking() { - out = workspaceRetryOutcome("lease_expired", h) + out = workspaceRetryOutcome("lease_expired", h, false) } if out.code != 0 { e.choose(out) @@ -170,7 +170,7 @@ func waitWorkspaceStop(e *processExit, f flags, h *volume.Host, requests <-chan case err := <-done: e.stopChunkStartup() fmt.Fprintln(os.Stderr, "blockvolume: workspace lease stopped:", err) - e.choose(workspaceRetryOutcome("lease_expired", h)) + e.choose(workspaceRetryOutcome("lease_expired", h, false)) return nil, nil } } @@ -210,11 +210,8 @@ func chooseChunkStartupExit(e *processExit, f flags, h *volume.Host, p chunkStar if !failed { return false } - out := workspaceRetryOutcome("assignment_timeout", h) - // INV-WS-STARTUP-RETRY-001: a claim's foreign-holder proof is - // independent of the master stream; generation is rechecked below. - if p.ChunkStartupSuperseded(f.volumeID, gen) { - out = workspaceExit{exitWorkspaceSuperseded, "superseded"} - } + // INV-WS-STARTUP-RETRY-001: one exit decision consumes both proof + // sources; the provider rechecks the claim generation below. + out := workspaceRetryOutcome("assignment_timeout", h, p.ChunkStartupSuperseded(f.volumeID, gen)) return p.ChooseChunkStartupExit(f.volumeID, gen, func() { e.chooseChunkStartup(out) }) } diff --git a/seaweed-block/core/host/volume/host.go b/seaweed-block/core/host/volume/host.go index b7591515d8..9466b02ded 100644 --- a/seaweed-block/core/host/volume/host.go +++ b/seaweed-block/core/host/volume/host.go @@ -176,8 +176,7 @@ type Host struct { workspaceLeaseStarted atomic.Bool // Guard installation and terminal host fencing share this lock. Order: // workspaceLeaseMu -> guard.mu; never hold either across RPC or drain. - workspaceLeaseMu sync.Mutex - workspaceLeaseFenced bool + workspaceLeaseMu sync.Mutex // workspaceStopPending is the guard's stop-pending mode, kept here for a // guard installed later; workspaceStopAttempt numbers detach attempts so // only the latest one's resume clears it. diff --git a/seaweed-block/core/host/volume/workspace_runtime.go b/seaweed-block/core/host/volume/workspace_runtime.go index d6fad91ccf..775810b746 100644 --- a/seaweed-block/core/host/volume/workspace_runtime.go +++ b/seaweed-block/core/host/volume/workspace_runtime.go @@ -43,7 +43,14 @@ func (h *Host) runWorkspaceLease(ctx context.Context, stop func(context.Context, h.workspaceLeaseMu.Lock() // The guard is not yet shared: publish it already fenced if a // synchronous shutdown won the race with this installer. - guard.fenced = h.workspaceLeaseFenced || ctx.Err() != nil + if prior := h.view.workspaceGuard.Load(); prior != nil { + // Before this one-shot install, only FenceWorkspaceLease can + // publish a guard: its terminal cause must survive installation. + guard.fenceLocked(prior.FenceCause()) + } + if ctx.Err() != nil { + guard.fenceLocked("shutdown requested (context cancelled)") + } guard.stopPending = h.workspaceStopPending h.view.workspaceGuard.Store(guard) h.workspaceLeaseMu.Unlock() @@ -103,12 +110,16 @@ func (h *Host) WorkspaceStopResumed(volumeID string, attempt uint64) { func (h *Host) FenceWorkspaceLease() { h.workspaceLeaseMu.Lock() defer h.workspaceLeaseMu.Unlock() - h.workspaceLeaseFenced = true - if g := h.view.workspaceGuard.Load(); g != nil { - g.mu.Lock() - g.fenced = true - g.mu.Unlock() + // INV-WS-STARTUP-RETRY-001: the guard owns the only terminal latch, + // including shutdown before its runtime installation. + g := h.view.workspaceGuard.Load() + if g == nil { + g = &WorkspaceLeaseGuard{} } + g.mu.Lock() + g.fenceLocked("host shutdown requested") + g.mu.Unlock() + h.view.workspaceGuard.Store(g) } // WorkspaceLeaseRevoking distinguishes the ACK-owning planned drain from a diff --git a/seaweed-block/core/host/volume/workspace_terminal_test.go b/seaweed-block/core/host/volume/workspace_terminal_test.go index dcfc11e467..6bc031f272 100644 --- a/seaweed-block/core/host/volume/workspace_terminal_test.go +++ b/seaweed-block/core/host/volume/workspace_terminal_test.go @@ -42,6 +42,9 @@ func TestWorkspaceFenceBeforeHeldInstallIsTerminal(t *testing.T) { _ = runtimeDone(t, done) t.Fatal("fenced installer did not settle") } + if g := h.view.workspaceGuard.Load(); g == nil || g.FenceCause() != "host shutdown requested" { + t.Fatal("installation lost the synchronous fence cause") + } if stops.Load() != 1 || h.ProjectionView().Projection().Healthy { t.Fatal("fence failed to stop installed guard", stops.Load()) } diff --git a/seaweed-block/docs/design/agent-workspace-design.md b/seaweed-block/docs/design/agent-workspace-design.md index 833168a6a4..9601926f6b 100644 --- a/seaweed-block/docs/design/agent-workspace-design.md +++ b/seaweed-block/docs/design/agent-workspace-design.md @@ -531,3 +531,5 @@ The existing-local-root precheck uses the same distinction: another holder at or above the assigned epoch is positive supersede evidence; an older foreign publication remains the existing move-back diagnostic. Neither path serves or publishes the local WAL, which remains on disk for diagnosis. + +Part T ownership: the lease guard alone holds the terminal fence and its first cause. A host shutdown before runtime installation publishes only a fenced, zero-validity guard; installation carries that cause into the valid-identity guard and never renews it. Startup and runtime exit callers both use workspaceRetryOutcome; only startup can supply a generation-bound refused-claim HEAD proof. diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 8cdc67b999..927a61773d 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -189,7 +189,7 @@ stateDiagram-v2 | From | To | Guard | Enforced in | Protects | |---|---|---|---|---| | NoLease, Valid | Valid | the reply names this `{volume, replica, epoch}`, its validity is positive and at most 30 s, and it arrives before the old deadline; the new deadline is anchored to the request start | `core/host/volume/workspace_lease.go` `Refresh` | `INV-WS-LEASE-001`, `INV-WS-FORCED-MOVE-001`, `INV-WS-FORCED-MOVE-HALF-SKEW-001` | -| Valid, StopPending | Fenced | the local deadline passes (checked on every projection read), the reply is invalid, or the lease is revoking; a fenced guard never reopens | `core/host/volume/workspace_lease.go` `permits`, `Refresh` | `INV-WS-LEASE-001` | +| NoLease, Valid, StopPending | Fenced | the local deadline passes (checked on every projection read), the reply is invalid, the lease is revoking, or synchronous host shutdown fences through the guard; first cause is kept and a fenced guard never reopens | `core/host/volume/workspace_lease.go` `permits`, `Refresh`, `fenceLocked`; `core/host/volume/workspace_runtime.go` `FenceWorkspaceLease` | `INV-WS-LEASE-001` | | Valid | StopPending | a chunk detach of this volume starts (before its drain); the guard renews at once. Scheduling only: StopPending admits, fences and ACKs exactly as Valid | `core/frontend/durable/provider_chunk.go` `DetachVolume`; `core/host/volume/workspace_runtime.go` `WorkspaceStopPending`; `core/host/volume/workspace_lease.go` `StopPending` | `INV-WS-STOP-PENDING-001` | | StopPending | StopPending | each sleep after a completed renewal is at most `stopPendingPoll` (250 ms); a renewal already in flight is not interrupted | `core/host/volume/workspace_lease.go` `renewDelay`, `Run` | `INV-WS-STOP-PENDING-001` | | StopPending | Valid | only the latest detach attempt, provably not applied, with serving resumed; an applied, fenced or unknown outcome, or an older attempt's resume, leaves StopPending | `core/frontend/durable/provider_chunk.go` `resumeAfterDetach`; `core/host/volume/workspace_runtime.go` `WorkspaceStopResumed`; `core/host/volume/workspace_lease.go` `ClearStopPending` | `INV-WS-STOP-PENDING-001` | @@ -674,7 +674,8 @@ Notes: | `INV-WS-STARTUP-RETRY-001` | A workspace primary exits 75 on assignment timeout or lease expiry, with bounded cleanup; a newer other-replica master fact or an exact foreign HEAD at or above the assigned epoch permits 78. ACKed revocation and signal retain normal exit. Lease and claim gates never relax. | M2 restart | `cmd/blockvolume/process_exit.go` `superviseProcess`, `workspaceRetryOutcome`; `core/frontend/durable/provider_chunk.go` `claimHeadSupersedes`; `core/frontend/durable/provider_startup.go` `endChunkStartup` | `TestChunkAssignmentTimeoutExposesCurrentRecoveryOutcome` (`core/frontend/durable/provider_startup_outcome_test.go`); `TestChunkStartupOutcomeRejectsOldGenerationAndCoalescesWake` (`core/frontend/durable/provider_startup_internal_test.go`); `TestWorkspaceDisplacedClaimUsesAssignedEpoch`, `TestWorkspaceRetryUsesNewestOwnAssignment`, `TestWorkspaceForeignHeadClaimChoosesNoRetry`, `TestWorkspaceOldLocalHolderForeignHeadChoosesNoRetry` (`cmd/blockvolume/process_exit_authority_test.go`); `TestWorkspaceExitFirstOutcomeIsLatched`, `TestWorkspaceExitDoesNotWaitForBlockedFrontendClose`, `TestWorkspacePlannedStopKeepsSuccess` (`cmd/blockvolume/process_exit_test.go`) | Existing WorkspaceRegrant restart transition; no new grant rule | ACTIVE | - `INV-WS-STARTUP-RETRY-001`: exit 78 is permitted by a NEWER observed master fact for this volume naming another replica (compared with the latest own assignment, zero before any), or by the exact refused HEAD claim image proving another holder at or above the assigned epoch. The provider binds the latter proof to its recovery generation. Both existing-root checks and claim CAS readback use the same epoch-qualified supersede classifier. A lower-epoch foreign HEAD on an existing root retains the move-back diagnostic; a displaced lower-epoch claim on a fresh root retries 75 without serving. A same-holder higher-epoch HEAD fence retries 75. Unknown/no line, same replica at a higher epoch, and status codes alone mean retry 75. A wrong retry costs a bounded restart loop; a wrong 78 causes an outage until an explicit operator start. Sealed same-epoch recovery remains up for read-only replay after assignment; stale local roots, corrupt WAL and I/O faults retain diagnostic wait. The first chosen outcome wins. Process cleanup reuses `WorkspaceDrainTimeout` (5 s), including a blocked Close; only main exits the process. -- Part T evidence scope: startup `chooseChunkStartupExit` ORs the newer other-replica master line with the recovery-generation-bound refused-claim HEAD proof. Runtime lease-end `workspaceRetryOutcome` has no new claim attempt supplying such a proof, so it uses only the master line and otherwise retries 75; absence of a HEAD proof never implies 78. +- Part T evidence scope: `workspaceRetryOutcome` is the one retry/no-retry decision. Startup `chooseChunkStartupExit` supplies the recovery-generation-bound refused-claim HEAD proof; runtime lease-end supplies none. Both combine that input with the newer other-replica master line; absent proof means retry 75. +- 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.