fix(authority): report uncertain move outcomes before refusals

This commit is contained in:
pingqiu committed 2026-11-21 06:43:27 -08:00
1 parent f30d91fec5
commit 677e0a50d4
8 files changed
+139 -26

No files matched your search

+18 -1
View File
@@ -199,7 +199,24 @@ func (p *Publisher) IssuedWorkspaceMove(req WorkspaceMoveRequest) bool {
return replay && err == nil
}
func (p *Publisher) MoveWorkspace(ctx context.Context, req WorkspaceMoveRequest, head WorkspaceHead) (WorkspaceMoveRecord, error) {
// WorkspaceMoveOutcomeError classifies a failed move at the reply boundary.
// M2 Uncertain / INV-AUTH-UNCERTAIN-001: admission cannot promise no effect
// while an earlier workspace write may have landed. Cancellation stays typed.
func (p *Publisher) WorkspaceMoveOutcomeError(volume string, err error) error {
if err == nil || errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {
return err
}
p.mu.Lock()
uncertain := p.workspaceUncertain[volume]
p.mu.Unlock()
if uncertain {
return errors.Join(ErrWorkspaceOutcomeUncertain, err)
}
return err
}
func (p *Publisher) MoveWorkspace(ctx context.Context, req WorkspaceMoveRequest, head WorkspaceHead) (_ WorkspaceMoveRecord, resultErr error) {
defer func() { resultErr = p.WorkspaceMoveOutcomeError(req.VolumeID, resultErr) }()
if err := ctx.Err(); err != nil {
return WorkspaceMoveRecord{}, err
}
@@ -73,6 +73,7 @@ func TestWorkspaceUncertaintyPrecedesRequestRefusal(t *testing.T) {
ctx := context.Background()
disk, _ := newTempStore(t)
p, _, _ := forcedLostRangeFixture(t, disk, false)
t.Cleanup(p.CloseWorkspaceExtenders)
bad := forcedLostRangeReq
bad.TargetReplicaID = "other-slot"
if _, err := p.MoveWorkspace(ctx, bad, forcedLostRangeHead); err == nil || errors.Is(err, ErrWorkspaceOutcomeUncertain) {
@@ -113,6 +114,16 @@ func TestWorkspaceUncertaintyPrecedesRequestRefusal(t *testing.T) {
t.Errorf("uncertain volume answered a definite admission refusal: %v", err)
}
}
canceled, cancel := context.WithCancel(ctx)
cancel()
if _, err := p.MoveWorkspace(canceled, bad, forcedLostRangeHead); err != context.Canceled {
t.Errorf("caller cancellation changed: %v", err)
}
other := bad
other.VolumeID = "other"
if _, err := p.MoveWorkspace(ctx, other, forcedLostRangeHead); err == nil || errors.Is(err, ErrWorkspaceOutcomeUncertain) {
t.Errorf("uncertainty leaked across volumes: %v", err)
}
if !reflect.DeepEqual(before, p.WorkspaceState("v")) {
t.Fatal("refused requests changed authority memory")
}
@@ -180,7 +180,35 @@ func (s *services) logForcedGrant(g *control.WorkspaceGrant, replay bool, postIs
g.GetVolumeId(), g.GetRequestId(), g.GetOldHost(), g.GetOldReplicaId(), g.GetOldEpoch(), g.GetNewHost(), g.GetNewReplicaId(), g.GetNewEpoch(), replay, lost)
}
func (s *services) MoveWorkspace(ctx context.Context, q *control.WorkspaceMove) (*control.WorkspaceGrant, error) {
func (s *services) MoveWorkspace(ctx context.Context, q *control.WorkspaceMove) (_ *control.WorkspaceGrant, resultErr error) {
// Remote reads never hold the workspace mutation lock. Re-read every
// local precondition below; Publisher checks the expected epoch atomically.
// A refusal is logged after the lock is released (deferred first, so it
// runs last): a slow log writer never holds workspaceMu.
// An issued forced grant is logged the same way, also after the unlock.
var refusal string
var issued *control.WorkspaceGrant
var replay bool
var postIssue, unknown error
defer func() {
// M2 Uncertain reply precedence applies even to preflight/HEAD errors.
outcome := resultErr
if code := status.Code(resultErr); code != codes.Canceled && code != codes.DeadlineExceeded {
outcome = s.host.Publisher().WorkspaceMoveOutcomeError(q.GetVolumeId(), resultErr)
}
if errors.Is(outcome, authority.ErrWorkspaceOutcomeUncertain) {
unknown, refusal = outcome, ""
resultErr = status.Errorf(codes.Internal, "workspace move %q of volume %q has an UNKNOWN outcome: %v; the volume's workspace authority stays uncertain until the master restarts; after the restart, rerun with the same request id", q.GetRequestId(), q.GetVolumeId(), outcome)
}
if refusal != "" {
s.host.log.Printf("blockmaster: MoveWorkspace refused volume=%q request=%q: %s", q.GetVolumeId(), q.GetRequestId(), refusal)
}
s.logForcedGrant(issued, replay, postIssue)
if unknown != nil {
s.host.log.Printf("blockmaster: MoveWorkspace outcome unknown volume=%q request=%q kind=%q: %v", q.GetVolumeId(), q.GetRequestId(), q.GetKind(), unknown)
}
}()
if err := s.workspaceVolume(q.GetVolumeId()); err != nil {
return nil, err
}
@@ -201,24 +229,6 @@ func (s *services) MoveWorkspace(ctx context.Context, q *control.WorkspaceMove)
if err != nil {
return nil, workspaceError(err)
}
// Remote reads never hold the workspace mutation lock. Re-read every
// local precondition below; Publisher checks the expected epoch atomically.
// A refusal is logged after the lock is released (deferred first, so it
// runs last): a slow log writer never holds workspaceMu.
// An issued forced grant is logged the same way, also after the unlock.
var refusal string
var issued *control.WorkspaceGrant
var replay bool
var postIssue, unknown error
defer func() {
if refusal != "" {
s.host.log.Printf("blockmaster: MoveWorkspace refused volume=%q request=%q: %s", q.GetVolumeId(), q.GetRequestId(), refusal)
}
s.logForcedGrant(issued, replay, postIssue)
if unknown != nil {
s.host.log.Printf("blockmaster: MoveWorkspace outcome unknown volume=%q request=%q kind=%q: %v", q.GetVolumeId(), q.GetRequestId(), q.GetKind(), unknown)
}
}()
s.host.workspaceMu.Lock()
defer s.host.workspaceMu.Unlock()
if err := ctx.Err(); err != nil {
@@ -246,11 +256,6 @@ func (s *services) MoveWorkspace(ctx context.Context, q *control.WorkspaceMove)
issued, postIssue = s.issuedRecord(req), err
return nil, postIssueError(q, err)
}
if errors.Is(err, authority.ErrWorkspaceOutcomeUncertain) {
unknown = err
return nil, status.Errorf(codes.Internal, "workspace move %q of volume %q has an UNKNOWN outcome: %v; the volume's workspace authority stays uncertain until the master restarts; after the restart, rerun with the same request id",
q.GetRequestId(), q.GetVolumeId(), err)
}
return nil, workspaceError(err)
}
// The move is issued from here on: record it for the audit log before
@@ -10,6 +10,7 @@ import (
"strings"
"sync/atomic"
"testing"
"time"
)
func TestWorkspaceMoveUnknownPrecedesAdmissionRefusals(t *testing.T) {
@@ -73,6 +74,25 @@ func TestWorkspaceMoveUnknownPrecedesAdmissionRefusals(t *testing.T) {
if _, err := client.MoveWorkspace(ctx, request("clean")); status.Code(err) != codes.Internal || !strings.Contains(status.Convert(err).Message(), "UNKNOWN") {
t.Errorf("early HEAD error hid uncertainty: %v", err)
}
// These direct calls inspect the server result, not the client's own
// deadline override, so reply classification must preserve both.
for _, deadline := range []bool{false, true} {
var ended context.Context
var end context.CancelFunc
want := codes.Canceled
if deadline {
ended, end = context.WithDeadline(ctx, time.Unix(0, 1))
want = codes.DeadlineExceeded
} else {
ended, end = context.WithCancel(ctx)
end()
}
_, err := (&services{host: h}).MoveWorkspace(ended, request("forced"))
end()
if status.Code(err) != want {
t.Errorf("server caller-end classification changed: %v want %v", err, want)
}
}
authority.SetPutAfterRenameFaultForTest(nil)
state := h.Publisher().WorkspaceState("v")
line, ok := h.Publisher().VolumeAuthorityLine("v")
+4 -1
View File
@@ -82,6 +82,7 @@ blockmaster's publisher is the only component that mints epochs. Diagrams: the a
| Bound | Reassigned (per-volume maximum epoch + 1) | `IntentReassign`; some earlier publication exists; an enrolled workspace volume changes only through a guarded move | `core/authority/authority.go` `applyWithWorkspaceMove`, `maxPublishedEpochForVolume` | `INV-AUTH-EPOCH-MINT-001`, `INV-AUTH-ONE-PRIMARY-001` |
| any | (store write first) | with an authority store configured, every transition is written to the store before memory changes or subscribers are notified; a failed write publishes nothing, but its durable outcome may be unknown | `core/authority/authority.go` `applyWithWorkspaceMove` | `INV-AUTH-PERSIST-BEFORE-PUBLISH-001` |
| any (workspace) | Uncertain | a failed workspace authority write, including a lease extension; later changes for that volume, and renewals that would issue a new or extended grant, are refused until restart (a Revoking lease still gets its bounded drain reply) | `core/authority/authority.go` `applyWithWorkspaceMove`; `core/authority/workspace.go` `persistWorkspaceLocked`; `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `extendWorkspaceLease` | `INV-AUTH-UNCERTAIN-001` |
| Uncertain | Uncertain (move answer) | failed move replies classify uncertainty after local locks release, before any admission refusal; cancellation/deadline remain typed; known successful replay is unchanged | `core/authority/workspace.go` `WorkspaceMoveOutcomeError`; `core/host/master/workspace_service.go` `MoveWorkspace` | `INV-AUTH-UNCERTAIN-001` |
| Bound | Deleting | a deletion reservation; the id is never created again | `core/host/master/services.go` `MarkVolumeDeleting` | `INV-VOL-ID-NO-REUSE-001` |
**Workspace lease and move, in blockmaster.**
@@ -432,6 +433,8 @@ The "Machine / transition" column refers to Part A. Notes under a table record w
Notes:
- `INV-AUTH-UNCERTAIN-001` detail: After a failed authority write for a workspace volume, the publisher refuses further authority changes for that volume until it restarts and reloads. A failed lease extension is such a write. Renewals that would issue a new or extended (non-revoking) grant for the volume are refused too: the renewal path reads uncertainty from the lease view (`INV-LEASE-VIEW-001`) instead of meeting it in `persistWorkspaceLocked`. A Revoking lease still gets its bounded drain reply, min(horizon, deadline), never extended, as before. Move error classification reads the per-volume uncertainty latch under the publisher lock at reply time, covering RPC preflight, HEAD reads and local admission as well as the publisher. The unknown outcome overrides the refusal audit entry. It adds no authority write and does not clear uncertainty.
- `INV-WAL-V3-LSN-ORDER-001`: the writer gate prevents an out-of-order physical chain whose dropped unacked middle record could later resurrect. Raw scanner/recovery integrity verdicts and the v3 ApplyEntry superseded-no-op/refusal policy are separate caller obligations. Legacy ApplyEntry and production v2 behavior are unchanged.
- `INV-WAL-V3-FLUSH-LIFETIME-001`: Capture recoverGen under store.mu with the dirty snapshot, before WAL materialization/extent I/O. Recheck the original generation under syncMu before either mapped or historical dark checkpoint publication. Under store.mu, recheck again before local tail progress and LSN-only compare/delete; Recover uses the same store lock at both boundaries. This adds no new lock or I/O under a publication lock. The pre-proof held control materializes unacknowledged A2, damages only that WAL suffix, Recover keeps W1, then reuses the same LBA/offset/LSN for acknowledged B2. Old publication must refuse, retain B, and a fresh retry must put B in the physical extent before crash-style reopen verifies exact bytes.
@@ -455,7 +458,7 @@ Notes:
| `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` | `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-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 the proposed assignment, but its durable outcome may be unknown (the write may have landed); for a workspace volume the failure latches uncertainty (`INV-AUTH-UNCERTAIN-001`). The cited test covers the non-workspace in-memory rollback. | M2 every transition | `core/authority/authority.go` `applyWithWorkspaceMove` | `TestDurableAuthority_PutFailureRollsBackInMemoryState` (`core/authority/authority_restart_test.go`) | `ControlPlane` `UniqueEpoch` | ACTIVE |
| `INV-AUTH-MOVE-JOURNAL-001` | A workspace move's epoch is issued only after its journal record is durable, and one move request id gets exactly one epoch, also across restarts. | M2 MoveReserved → MoveIssued | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `MoveWorkspace`, `sameWorkspaceRequest` | `TestWorkspaceMoveCannotIssueEpochWithoutJournal`, `TestWorkspaceCrashAfterJournalBeforeEpochResumesSameGrant` (`core/authority/workspace_test.go`); `TestWorkspaceReplayedIssueStartsGranteeLease` (`core/authority/workspace_unclaimed_grant_test.go`) | `ControlPlane` `Idempotent`, `JournalComplete` | ACTIVE |
| `INV-AUTH-UNCERTAIN-001` | After a failed authority write for a workspace volume, the publisher refuses further authority changes for that volume until it restarts and reloads. A failed lease extension is such a write. Renewals that would issue a new or extended (non-revoking) grant for the volume are refused too: the renewal path reads uncertainty from the lease view (`INV-LEASE-VIEW-001`) instead of meeting it in `persistWorkspaceLocked`. A Revoking lease still gets its bounded drain reply, min(horizon, deadline), never extended, as before. | M2 any → Uncertain | `core/authority/authority.go` `applyWithWorkspaceMove`; `core/authority/workspace.go` `persistWorkspaceLocked`; `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `extendWorkspaceLease` | `TestWorkspaceAmbiguousExtensionLatchesUncertainty` (`core/authority/workspace_lease_horizon_test.go`) | `ControlPlane` `UniqueEpoch` | ACTIVE |
| `INV-AUTH-UNCERTAIN-001` | Failed workspace writes latch uncertainty until reload. Authority and lease extensions refuse; revoking leases keep bounded drain replies. A failed move is UNKNOWN before admission refusal; caller cancellation/deadline stays typed. Known issued replays remain valid. | M2 any → Uncertain | `core/authority/authority.go` `applyWithWorkspaceMove`; `core/authority/workspace.go` `persistWorkspaceLocked`; `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `extendWorkspaceLease`; `core/authority/workspace.go` `WorkspaceMoveOutcomeError`, `MoveWorkspace`; `core/host/master/workspace_service.go` `MoveWorkspace` | `TestWorkspaceAmbiguousExtensionLatchesUncertainty` (`core/authority/workspace_lease_horizon_test.go`); `TestWorkspaceUncertaintyPrecedesRequestRefusal`, `TestWorkspaceMoveUnknownPrecedesAdmissionRefusals`, `TestWorkspaceUncertainIssueWriteIsTyped` | `ControlPlane` `UniqueEpoch`; `WorkspaceMoveOutcome` `NoFalseRefusal`, `CallerEndTyped` | ACTIVE |
| `INV-LEASE-VIEW-001` | Whenever the publisher lock is released, each volume's lease view (the renewal path's only input) equals derive(the published authority line, workspace state, uncertainty, store presence). Writers refresh it under the publisher lock then the lease lock at every change of those inputs; the deadline and the extender flag are owned by the view. A move issue publishes the derived view and the new holder's initial deadline in one lease-lock section, never lowering a deadline a renewal raised. | M2 every workspace transition | `core/authority/workspace_lease_view.go` `refreshLeaseViewLocked`, `publishIssuedLeaseLocked`; `core/authority/authority.go` `applyWithWorkspaceMove`, `reloadFromStore`; `core/authority/workspace.go` `persistWorkspaceLocked` | `TestWorkspaceLeaseViewMatchesDeriveAfterEveryWriter`, `TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose` (`core/authority/workspace_lease_horizon_test.go`); `TestWorkspaceIssuePublishNeverLowersARenewedDeadline` (`core/authority/workspace_issue_publish_test.go`) | — | ACTIVE |
| `INV-WS-LEASE-HORIZON-001` | For the active lease of the current authority epoch: the persisted `Lease.ExpiresAtNS` ≥ the published horizon ≥ every grant issued since the last reload, and the published horizon only grows. A move issue that replaces the lease with the new holder's is the ordered successor (a clean handoff, or a forced move past the barrier) and leaves this scope; if that issued successor is persisted ambiguously (it may have landed while memory has not published it), the volume is uncertain and no further old-epoch grant is issued, so no disk expiry is claimed for it. | M2 Granted → Granted | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `extendWorkspaceLease`; `core/authority/workspace.go` `persistWorkspaceLocked` | `TestWorkspaceLeaseClampsToHorizonUnderStalledStore`, `TestWorkspaceRestartForcedBarrierHonoursHorizon`, `TestWorkspaceAmbiguousExtensionLatchesUncertainty`, `TestWorkspaceExtenderHeldOrdersSameVolumeWriters`, `TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose` (`core/authority/workspace_lease_horizon_test.go`); `TestWorkspaceLeaseGuardFencesByHorizonUnderStalledStore` (`core/host/master/workspace_lease_horizon_test.go`) | — | ACTIVE |
| `INV-WS-RENEW-NONBLOCKING-001` | A renewal of an established lease takes only the leaf lease lock and lock-free lifecycle snapshots: it never waits on the publisher lock, an authority store write or a lifecycle store mutex. Only the first grant of a lease writes synchronously. | M2 Granted → Granted | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`; `core/host/master/workspace_service.go` `workspaceVolumeForRenewal` | `TestWorkspaceRenewalDoesNotWaitForSlowStore`, `TestWorkspaceConcurrentRenewalsDoNotSerializeOnStore`, `TestWorkspaceRenewalDoesNotWaitForUnrelatedHeldWrite` (`core/authority/workspace_renewal_slowstore_test.go`); `TestWorkspaceExtenderAdmittedBeforeCloseDoesNotWrite` (`core/authority/workspace_lease_horizon_test.go`); `TestWorkspaceLeaseGuardSurvivesSlowAuthorityStore`, `TestWorkspaceRenewalRPCDoesNotWaitForHeldReservationWrite` (`core/host/master/workspace_renewal_slowstore_test.go`) | — | ACTIVE |
+29
View File
@@ -517,3 +517,32 @@ checked by native Go tests; this derived arithmetic model does not model the HTT
encoder, sampler atomicity, orchestrator timing or an unbounded estimator overrun.
#344 review qualification: `TestChunkFrozenDrainRefusalCarriesObservedBudget` drives a real admitted Sync through frontend drain expiry, durable provider and HTTP, with no report injection; `TestFrozenDrainObservationPreservesKnownBeforeReasonMutation` covers the known observation. `TestFrozenSaturatedTailRemainsKnownButNonActionable` and the literal 60 s/61 s candidate cases preserve the existing saturation sentinel (zero slack, not a complete duration). These native controls add no model claim or admission guard.
### Workspace move reply precedence
`WorkspaceMoveOutcome.tla` covers M2's `Uncertain -> Uncertain (move answer)`
transition and `INV-AUTH-UNCERTAIN-001`. One volume can receive one failed
workspace write (landed or not), one error from request validation, forced
preflight, HEAD read, target or endpoint admission, or a caller cancellation /
deadline. The write may fail before or after the error is selected. Reply-time
classification must never report a definite refusal while uncertainty is
observed; caller cancellation/deadline stays typed. No authority changes are
modeled here: journal durability, lease safety, RPC delivery and reload remain
with their existing specs and native controls.
TLC 2.19 (tools SHA256
`936a262061c914694dfd669a543be24573c45d5aa0ff20a8b96b23d01e050e88`),
2026-11-21: `cfg/WorkspaceMoveOutcome.cfg` exhausted 59 generated / 45 distinct
states, depth 4, queue empty. Bounds: one volume, seven error causes, one failed
write with Boolean durable outcome, one reply. `NoFalseRefusal` and
`CallerEndTyped` hold. The `BypassUncertainty=TRUE` negative must violate
`NoFalseRefusal`; native controls map to
`TestWorkspaceUncertaintyPrecedesRequestRefusal` (publisher validation),
`TestWorkspaceMoveUnknownPrecedesAdmissionRefusals` (real gRPC preflight/HEAD/
target paths, uncertainty before the call or during HEAD read, plus direct
server caller-end classification), and the retained
`TestWorkspaceUncertainIssueWriteIsTyped` (issue failure and replay after reload).
The new tests use a real file-store rename followed by an injected error;
a readout verifies that the failed write actually landed while memory rolled
back. They also check no new authority epoch/move and per-volume scope.
@@ -0,0 +1,25 @@
------------------------- MODULE WorkspaceMoveOutcome -------------------------
EXTENDS Naturals, FiniteSets
CONSTANT BypassUncertainty
VARIABLES uncertain, landed, cause, reply, uncertainAtReply
vars == <<uncertain, landed, cause, reply, uncertainAtReply>>
Causes == {"request", "forced_preflight", "head", "target", "endpoint", "canceled", "deadline"}
Init == /\ uncertain = FALSE /\ landed = FALSE /\ cause = "none"
/\ reply = "none" /\ uncertainAtReply = FALSE
FailedWrite == /\ ~uncertain /\ reply = "none"
/\ uncertain' = TRUE /\ landed' \in BOOLEAN
/\ UNCHANGED <<cause, reply, uncertainAtReply>>
AdmissionError == /\ cause = "none" /\ reply = "none"
/\ cause' \in Causes
/\ UNCHANGED <<uncertain, landed, reply, uncertainAtReply>>
Reply == /\ cause # "none" /\ reply = "none"
/\ reply' = IF cause \in {"canceled", "deadline"} THEN cause
ELSE IF uncertain /\ ~BypassUncertainty THEN "unknown"
ELSE "refused"
/\ uncertainAtReply' = uncertain
/\ UNCHANGED <<uncertain, landed, cause>>
Next == FailedWrite \/ AdmissionError \/ Reply
Spec == Init /\ [][Next]_vars
NoFalseRefusal == ~(reply = "refused" /\ uncertainAtReply)
CallerEndTyped == cause \in {"canceled", "deadline"} /\ reply # "none" => reply = cause
=============================================================================
@@ -0,0 +1,3 @@
SPECIFICATION Spec
CONSTANT BypassUncertainty = FALSE
INVARIANTS NoFalseRefusal CallerEndTyped