fix: preserve durability exit contract and strengthen finalize controls

This commit is contained in:
pingqiu committed 2026-12-05 05:46:00 -08:00
1 parent c34bc1bdeb
commit 4e40e691ab
6 files changed
+127 -35

No files matched your search

@@ -3,53 +3,138 @@ package master
import (
"context"
"errors"
"fmt"
"log"
"os"
"os/exec"
"strings"
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/authority"
control "github.com/seaweedfs/seaweed-block/core/rpc/control"
)
type blockedFinalizeLog struct{}
const finalizeSetupCheckpoint = "FINALIZE_SETUP_COMPLETE"
const finalizeFaultCheckpoint = "FINALIZE_POST_RENAME_FAULT"
const finalizeLogCheckpoint = "FINALIZE_LOG_ENTERED"
const finalizeWindowCheckpoint = "FINALIZE_INTENT_AND_GRANTS_CHECKED"
func (blockedFinalizeLog) Write([]byte) (int, error) { select {} }
type blockedFinalizeLog struct{ check func() }
func (w blockedFinalizeLog) Write([]byte) (int, error) {
fmt.Fprintln(os.Stderr, finalizeLogCheckpoint)
w.check()
fmt.Fprintln(os.Stderr, finalizeWindowCheckpoint)
select {}
}
func qualifiedFinalizeFailure(out []byte, err, contextErr error, sink string) bool {
var exit *exec.ExitError
if contextErr != nil || !errors.As(err, &exit) || exit.ExitCode() != authority.ExitDurabilityUnknown {
return false
}
for _, marker := range []string{finalizeSetupCheckpoint, finalizeFaultCheckpoint} {
if strings.Count(string(out), marker) != 1 {
return false
}
}
if sink == "blocked" {
return strings.Count(string(out), finalizeLogCheckpoint) == 1 && strings.Count(string(out), finalizeWindowCheckpoint) == 1
}
return strings.Contains(string(out), "ERROR") && strings.Contains(string(out), "supervisor restarts")
}
func TestFormatFinalizeUncertainWriteFailStops(t *testing.T) {
for _, sink := range []string{"normal", "blocked"} {
for _, sink := range []string{"normal", "blocked", "setup-failure", "setup-durability-failure"} {
t.Run(sink, func(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestFormatFinalizeUncertainWriteChild$", "-test.count=1")
cmd.Env = append(os.Environ(), "FINALIZE_FAILURE_CHILD="+sink)
out, err := cmd.CombinedOutput()
var exit *exec.ExitError
if ctx.Err() != nil || !errors.As(err, &exit) || exit.ExitCode() != 1 {
t.Fatalf("uncertain finalize did not exit 1 itself: %v ctx=%v\n%s", err, ctx.Err(), out)
qualified := qualifiedFinalizeFailure(out, err, ctx.Err(), sink)
if sink == "setup-failure" || sink == "setup-durability-failure" {
expected := 1
if sink == "setup-durability-failure" {
expected = authority.ExitDurabilityUnknown
}
var exit *exec.ExitError
if qualified || ctx.Err() != nil || !errors.As(err, &exit) || exit.ExitCode() != expected || !strings.Contains(string(out), "injected setup") {
t.Fatalf("setup failure was not distinguished: %v ctx=%v\n%s", err, ctx.Err(), out)
}
return
}
if sink == "normal" && (!strings.Contains(string(out), "ERROR") || !strings.Contains(string(out), "supervisor restarts")) {
t.Fatalf("missing persistence diagnostic: %s", out)
if !qualified {
t.Fatalf("fault/checkpoints did not qualify exit %d: %v ctx=%v\n%s", authority.ExitDurabilityUnknown, err, ctx.Err(), out)
}
})
}
}
func finalizeFailureRig(t *testing.T) *isolationRig {
t.Helper()
dir := upgradedStoreDir(t)
disk, err := authority.NewFileAuthorityStore(dir)
if err != nil {
t.Fatal(err)
}
if err := disk.Put(authority.DurableRecord{VolumeID: "v", ReplicaID: "r1", Epoch: 1, EndpointVersion: 1, WriteSeq: 1, DataAddr: hbPorts["node-b"][0], CtrlAddr: hbPorts["node-b"][1]}); err != nil {
t.Fatal(err)
}
if err := disk.Close(); err != nil {
t.Fatal(err)
}
r := newIsolationRig(t, false, dir, t.TempDir())
r.createVolume(t, "v")
r.place(t, "v", "node-b")
if err := r.fgProcessHeartbeat("node-b", "capable-v", "v", 1); err != nil {
t.Fatal(err)
}
if _, err := r.ws.RenewWorkspaceLease(r.ctx, &control.WorkspaceIdentity{VolumeId: "v", ReplicaId: "r1", Epoch: 1, ServerId: "node-b"}); err != nil {
t.Fatal(err)
}
return r
}
func TestFormatFinalizeUncertainWriteChild(t *testing.T) {
sink := os.Getenv("FINALIZE_FAILURE_CHILD")
if sink == "" {
t.Skip("bounded fault child")
}
r := newIsolationRig(t, false, upgradedStoreDir(t), t.TempDir())
for _, server := range []string{"node-a", "node-b"} {
if err := r.fgHeartbeat(server, 1); err != nil {
t.Fatal(err)
}
if sink == "setup-durability-failure" {
fmt.Fprintln(os.Stderr, "ERROR injected setup durability failure; supervisor restarts")
os.Exit(authority.ExitDurabilityUnknown)
}
if sink == "setup-failure" {
t.Fatal("injected setup failure before checkpoints")
}
r := finalizeFailureRig(t)
fmt.Fprintln(os.Stderr, finalizeSetupCheckpoint)
r.m.log = log.New(os.Stderr, "", 0)
if sink == "blocked" {
r.m.log = log.New(blockedFinalizeLog{}, "", 0)
r.m.log = log.New(blockedFinalizeLog{check: func() {
if !r.m.formatFinalizing.Load() || r.m.Publisher().FormatLevel() != 0 {
t.Fatal("host intent lost or level raised before recovery")
}
// At level 0, refusal without a report observes the publisher's intent.
if _, err := r.m.Publisher().RenewWorkspaceLease(r.ctx, "v", "r1", 1); err == nil {
t.Fatal("publisher intent reopened an unreported serving deadline")
}
proof := r.m.formatReadProof("v", "r1", "node-b", 1)
if _, err := r.m.Publisher().RenewWorkspaceLease(r.ctx, "v", "r1", 1, proof); err != nil {
t.Fatalf("capable live renewal blanket-refused while logging blocked: %v", err)
}
}}, "", 0)
}
syncAttestationDir = func(string) error {
onDisk, err := loadStoreAttestations(r.m.cfg.AuthorityStoreDir)
if err != nil || onDisk.level() != 1 {
t.Fatalf("fault did not follow the level-1 rename: %v", err)
}
fmt.Fprintln(os.Stderr, finalizeFaultCheckpoint)
return errors.New("injected post-rename directory barrier failure")
}
syncAttestationDir = func(string) error { return errors.New("injected post-rename directory barrier failure") }
_, _, _ = r.m.FinalizeFormat(1)
os.Exit(42) // returning reopens grants after a possibly durable level raise
os.Exit(42)
}
@@ -552,9 +552,9 @@ func (h *Host) FinalizeFormat(level uint32) (already bool, unconfirmed []hostBel
// rename may already have raised the durable level. Arm exit before logging:
// diagnostic delivery is best effort if the sink or its output lock is blocked.
func (h *Host) failUncertainFormatFinalize(err error) {
time.AfterFunc(time.Second, func() { os.Exit(1) })
time.AfterFunc(time.Second, func() { os.Exit(authority.ExitDurabilityUnknown) })
h.log.Printf("ERROR format finalize persistence failure store=%q error=%q; exiting so the supervisor restarts from durable state", h.attest.path, err)
os.Exit(1)
os.Exit(authority.ExitDurabilityUnknown)
}
// RetireHost removes server from the node inventory, so it no longer counts
@@ -382,25 +382,32 @@ func TestRetireHostRefusesAHostThatHoldsWork(t *testing.T) {
}
}
// A finalize whose durable write fails changes no level: the publisher and
// the master stay at 0 (the switch follows the write; FormatGateMaster
// finalize_not_atomic).
// A failure before the rename leaves both levels at 0, reopens admission,
// and permits a later finalize retry once the obstruction is removed.
func TestAFailedFinalizeWriteLeavesLevel0(t *testing.T) {
r := newIsolationRig(t, false, upgradedStoreDir(t), t.TempDir())
for _, s := range []string{"node-a", "node-b"} {
if err := r.fgHeartbeat(s, 1); err != nil {
t.Fatal(err)
}
if !finalizeServingChild(t) {
return
}
// A temp-path directory prevents the file write before any rename.
if err := os.Mkdir(r.m.attest.path+".tmp", 0o700); err != nil {
r := finalizeFailureRig(t)
obstruction := r.m.attest.path + ".tmp"
if err := os.Mkdir(obstruction, 0o700); err != nil {
t.Fatal(err)
}
if _, err := r.lc.FinalizeFormat(r.ctx, &control.FinalizeFormatRequest{Level: 1}); status.Code(err) != codes.Internal {
t.Fatalf("a finalize whose envelope write failed: %v, want Internal (a failure, not a transient answer)", err)
t.Fatalf("pre-rename failure: %v, want Internal", err)
}
if r.m.formatLevel() != 0 || r.m.Publisher().FormatLevel() != 0 {
t.Fatalf("a failed finalize switched the level: master %d, publisher %d", r.m.formatLevel(), r.m.Publisher().FormatLevel())
if r.m.formatLevel() != 0 || r.m.Publisher().FormatLevel() != 0 || r.m.formatFinalizing.Load() {
t.Fatal("pre-rename failure changed level or left host intent set")
}
// A no-report level-0 deadline proves the publisher intent is clear too.
if _, err := r.m.Publisher().RenewWorkspaceLease(r.ctx, "v", "r1", 1); err != nil {
t.Fatalf("publisher intent was not cleared after pre-rename failure: %v", err)
}
if err := os.Remove(obstruction); err != nil {
t.Fatal(err)
}
if _, _, err := r.m.FinalizeFormat(1); err != nil || r.m.formatLevel() != 1 || r.m.Publisher().FormatLevel() != 1 || r.m.formatFinalizing.Load() {
t.Fatalf("finalize could not retry after removing obstruction: %v", err)
}
}
+2 -2
View File
@@ -735,8 +735,8 @@ stateDiagram-v2
| Finalizing | Finalizing | Move and publication are placement: refuse only known-old targets. First serving deadlines, live renewals and regrants require the current process's level-1 report during intent and at level 1. A stored move lease alone permits no serving. Capable renewals stay memory-only; no grant lock spans the durable write. | `core/host/master/workspace_binding.go` `admitWorkspacePublication`; `core/authority/workspace_lease_view.go` `firstWorkspaceGrant`, `regrantWorkspaceLease` | `INV-FMT-FINALIZE-001`, `INV-WS-RENEW-NONBLOCKING-001` |
| Finalizing | Level 1 / Level 0 | On durable success publish level 1 under the grant locks; on a proven pre-rename failure clear the intent; an uncertain post-rename persistence failure retains the intent and fail-stops for recovery. The in-memory intent is not a persisted format or a new authority fact. | `core/authority/workspace_lease_v100.go` `FinalizeFormatLevel`; `core/authority/format_finalize.go` `CancelFormatFinalize` | `INV-FMT-LEVEL-001`, `INV-FMT-FINALIZE-001` |
This implementation interval refines FormatGate r12's atomic `Finalize`; the intent closes level-0 admission
while the store write runs outside the grant locks. It neither grants authority nor raises a holder's effective level.
FormatGate r12 models this interval as Begin, durable raise and Abort, refining r11's atomic `Finalize`.
The intent closes level-0 serving admission while the store write runs outside the grant locks. It neither grants authority nor raises a holder's effective level.
## Part B. Invariant ledger
+1 -1
View File
@@ -600,7 +600,7 @@ writing the v1.0 format until you finalize. Until then you can go back.
- **`listed`** names other hosts the master cannot confirm but that do not block the finalize: an unserved
placement with no report, a host with no work or report, or a stale capable report.
- **Persistence fault.** If the attestation replacement may have landed, blockmaster retains the admission
intent and exits nonzero so its supervisor restarts from disk. Run it under a restarting supervisor.
intent and exits 74 so its supervisor restarts from disk. Run it under a restarting supervisor.
ERROR delivery is best effort if logging is blocked; termination remains bounded. Inspect `format-level`
after recovery before retrying. A failure before replacement leaves level 0 and can be retried.
- **Exit codes:** **0** finalized or already finalized; **2** refused; **75** blockmaster unreachable, retry; **1**
+1 -1
View File
@@ -12,7 +12,7 @@ Current capable processes renew without waiting for the store write. This change
Moves and authority publication remain placement: an unknown target may be placed; only a known-old report refuses it.
An issued move record alone permits no serving. The target must report and get an accepted renewal reply first.
If finalize fails after replacing its attestation file, blockmaster exits nonzero so its supervisor restarts
If finalize fails after replacing its attestation file, blockmaster exits 74 so its supervisor restarts
from disk. ERROR delivery is best effort if logging is blocked; termination remains bounded. Run blockmaster
under a restarting supervisor and inspect `format-level` after recovery. Failures before replacement leave
level 0 and may be retried.