From ea1faf6a0a1e87c930cc8707b8c9eb36aec70859 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 29 May 2026 23:57:20 -0700 Subject: [PATCH] storage: fail closed on smartwal integrity mismatch --- .../ops/managed_volume_conditions_test.go | 66 ++++++++++++++++++- .../core/ops/managed_volume_model.go | 3 + seaweed-block/core/ops/observation.go | 1 + seaweed-block/core/ops/observation_bundle.go | 2 + .../core/ops/volume_status_summary.go | 6 +- .../core/storage/recovery_contract.go | 28 ++++++++ .../core/storage/smartwal/recovery.go | 38 +++++------ .../smartwal/smartwal_typed_failure_test.go | 60 +++++++++++++++++ 8 files changed, 182 insertions(+), 22 deletions(-) diff --git a/seaweed-block/core/ops/managed_volume_conditions_test.go b/seaweed-block/core/ops/managed_volume_conditions_test.go index 12fbd69c30..45d23c091d 100644 --- a/seaweed-block/core/ops/managed_volume_conditions_test.go +++ b/seaweed-block/core/ops/managed_volume_conditions_test.go @@ -1,6 +1,9 @@ package ops -import "testing" +import ( + "strings" + "testing" +) func TestManagedVolumeProjection_ReadyConditionForFirstVolume(t *testing.T) { projection := ProjectManagedVolume(ManagedVolumeFacts{ @@ -145,6 +148,67 @@ func TestManagedVolumeProjection_StatusEndpointUnreachableIsNotReady(t *testing. } } +func TestManagedVolumeProjection_WALIntegrityFaultIsBlockedNotReady(t *testing.T) { + projection := ProjectManagedVolume(ManagedVolumeFacts{ + VolumeID: "pvc-corrupt", + ProductStatus: ObservationStatusBlocked, + ProductReason: ReasonWALIntegrityFault, + EvidenceRefs: []string{"status/report/cluster-evidence.json"}, + }) + + ready := findObservationCondition(projection.Conditions, "Ready") + blocked := findObservationCondition(projection.Conditions, "Blocked") + if ready == nil || blocked == nil { + t.Fatalf("conditions=%+v", projection.Conditions) + } + if ready.Status != "False" || ready.Reason != ReasonWALIntegrityFault || ready.Severity != "warning" { + t.Fatalf("ready=%+v", ready) + } + if blocked.Status != "True" || blocked.Reason != ReasonWALIntegrityFault { + t.Fatalf("blocked=%+v", blocked) + } + if projection.Status != ManagedVolumeStatusBlocked || projection.ReasonCode != ReasonWALIntegrityFault { + t.Fatalf("projection=%+v", projection) + } +} + +func TestReasonFromIssueList_WALIntegrityFault(t *testing.T) { + got := reasonFromIssueList([]string{ + "ops_status=unhealthy reason=durable_pvc_r1_operational_false_evidence_recover_failed_storage_walintegrity_crc_mismatch", + }) + if got != ReasonWALIntegrityFault { + t.Fatalf("reason=%s want %s", got, ReasonWALIntegrityFault) + } +} + +func TestVolumeStatusReportIssues_CarriesDurableEvidence(t *testing.T) { + issues := VolumeStatusReportIssues(VolumeStatusReport{ + SchemaVersion: VolumeStatusReportSchemaVersion, + ProductRevision: "test", + Volume: VolumeReport{ + VolumeID: "pvc-corrupt", + ReplicaID: "r1", + }, + Authority: AuthorityReport{ + AuthorityRole: "primary", + Healthy: true, + FrontendPrimaryReady: true, + }, + Replication: ReplicationReport{ReplicationRole: "none"}, + Durable: []DurableReport{{ + VolumeID: "pvc-corrupt", + ReplicaID: "r1", + Latched: true, + Operational: false, + Evidence: "recover failed: storage: WALIntegrity: CRC mismatch", + }}, + }) + joined := strings.Join(issues, "\n") + if !strings.Contains(joined, "WALIntegrity") { + t.Fatalf("issues missing WALIntegrity evidence: %v", issues) + } +} + func findObservationCondition(conditions []ObservationCondition, conditionType string) *ObservationCondition { for i := range conditions { if conditions[i].Type == conditionType { diff --git a/seaweed-block/core/ops/managed_volume_model.go b/seaweed-block/core/ops/managed_volume_model.go index 1377a0ccca..5904a4f682 100644 --- a/seaweed-block/core/ops/managed_volume_model.go +++ b/seaweed-block/core/ops/managed_volume_model.go @@ -523,6 +523,9 @@ func classifyManagedVolume(p ManagedVolumeProjection, facts ManagedVolumeFacts) if facts.ProductReason == ReasonCSINodeImagePullFailed { return ManagedVolumeStatusBlocked, ReasonCSINodeImagePullFailed } + if facts.ProductReason == ReasonWALIntegrityFault { + return ManagedVolumeStatusBlocked, ReasonWALIntegrityFault + } if hasBlockedCSINode(facts.KubernetesNodes) { return ManagedVolumeStatusBlocked, ReasonCSINodeImagePullFailed } diff --git a/seaweed-block/core/ops/observation.go b/seaweed-block/core/ops/observation.go index 1d948f2c0e..f3b8fa2f11 100644 --- a/seaweed-block/core/ops/observation.go +++ b/seaweed-block/core/ops/observation.go @@ -30,6 +30,7 @@ const ( ReasonObservedReplicasBelowDesired = "observed_replicas_below_desired" ReasonLoopbackFrontendRejected = "loopback_frontend_rejected" ReasonStalePrimaryFenced = "stale_primary_fenced" + ReasonWALIntegrityFault = "wal_integrity_fault" EventTypeCSIReattachObserved = "csi_reattach_observed" ) diff --git a/seaweed-block/core/ops/observation_bundle.go b/seaweed-block/core/ops/observation_bundle.go index 19c2c3c827..607534a32f 100644 --- a/seaweed-block/core/ops/observation_bundle.go +++ b/seaweed-block/core/ops/observation_bundle.go @@ -614,6 +614,8 @@ func observationStatusFromInventoryCode(code int) string { func reasonFromIssueList(issues []string) string { joined := strings.Join(issues, "\n") switch { + case strings.Contains(joined, "WALIntegrity") || strings.Contains(joined, "walintegrity") || strings.Contains(joined, "wal_integrity") || strings.Contains(joined, "WAL integrity"): + return ReasonWALIntegrityFault case strings.Contains(joined, "status_endpoint_unreachable"): return ReasonStatusEndpointUnreachable case strings.Contains(joined, "generated_deployment_missing"): diff --git a/seaweed-block/core/ops/volume_status_summary.go b/seaweed-block/core/ops/volume_status_summary.go index eb35d78068..8f565ce58e 100644 --- a/seaweed-block/core/ops/volume_status_summary.go +++ b/seaweed-block/core/ops/volume_status_summary.go @@ -156,7 +156,11 @@ func VolumeStatusReportIssues(r VolumeStatusReport) []string { issues = append(issues, fmt.Sprintf("durable %s/%s latched=false", d.VolumeID, d.ReplicaID)) } if !d.Operational { - issues = append(issues, fmt.Sprintf("durable %s/%s operational=false", d.VolumeID, d.ReplicaID)) + issue := fmt.Sprintf("durable %s/%s operational=false", d.VolumeID, d.ReplicaID) + if d.Evidence != "" { + issue += " evidence=" + d.Evidence + } + issues = append(issues, issue) } if d.Closed { issues = append(issues, fmt.Sprintf("durable %s/%s closed=true", d.VolumeID, d.ReplicaID)) diff --git a/seaweed-block/core/storage/recovery_contract.go b/seaweed-block/core/storage/recovery_contract.go index b6ea0fec0d..09909ce967 100644 --- a/seaweed-block/core/storage/recovery_contract.go +++ b/seaweed-block/core/storage/recovery_contract.go @@ -56,6 +56,12 @@ const ( // G-1 §3 row #8 placement decision §4.3). var ErrWALRecycled = errors.New("storage: WAL recycled past requested LSN") +// ErrWALIntegrityFault is returned when recovery detects that WAL metadata and +// durable extent contents disagree. Callers MUST NOT treat this as a clean +// torn-tail skip because doing so can claim readiness after a committed record +// was detected as corrupt. +var ErrWALIntegrityFault = errors.New("storage: WAL integrity fault") + // RecoveryEntry is one entry emitted by `LogicalStorage.ScanLBAs`. // Carries enough information for the catch-up sender to write a // wire frame to the replica. @@ -110,6 +116,12 @@ const ( // StorageRecoveryFailureSubstrateIO — substrate IO error // (read failure, decode failure mid-scan, etc.). Retryable. StorageRecoveryFailureSubstrateIO + + // StorageRecoveryFailureWALIntegrity — recovery detected that WAL + // metadata and durable extent contents disagree. Not a clean + // readiness path; surface as an integrity blocker until repaired or + // rebuilt. + StorageRecoveryFailureWALIntegrity ) // String returns the human-readable kind name for diagnostics. NOT @@ -120,6 +132,8 @@ func (k StorageRecoveryFailureKind) String() string { return "WALRecycled" case StorageRecoveryFailureSubstrateIO: return "SubstrateIO" + case StorageRecoveryFailureWALIntegrity: + return "WALIntegrity" default: return "Unknown" } @@ -178,6 +192,20 @@ func NewSubstrateIOFailure(cause error, detail string) *RecoveryFailure { } } +// NewWALIntegrityFailure wraps a recovery-time WAL/extent integrity mismatch in +// the typed envelope. Substrates call this when recovery detects corruption and +// must fail closed instead of claiming a clean frontier. +func NewWALIntegrityFailure(cause error, detail string) *RecoveryFailure { + if cause == nil { + cause = ErrWALIntegrityFault + } + return &RecoveryFailure{ + Kind: StorageRecoveryFailureWALIntegrity, + Cause: cause, + Detail: detail, + } +} + // --- T4d-1 Option C hybrid: per-LBA applied-LSN exposure --- // --- G7-redo priority 2.5: WAL recycle gate via pin floor --- diff --git a/seaweed-block/core/storage/smartwal/recovery.go b/seaweed-block/core/storage/smartwal/recovery.go index a8d11e3b47..8558abb010 100644 --- a/seaweed-block/core/storage/smartwal/recovery.go +++ b/seaweed-block/core/storage/smartwal/recovery.go @@ -5,6 +5,8 @@ import ( "hash/crc32" "log" "os" + + "github.com/seaweedfs/seaweed-block/core/storage" ) // runRecovery rebuilds the LSN frontier from a smartwal store's ring @@ -18,16 +20,13 @@ import ( // 2. Build a map LBA → highest-LSN record. Older records for the // same LBA are dominated and ignored. // 3. For each surviving record: -// - Trim record: counts as recovered (its CRC32 covers a zero -// block; if the extent matches that, the trim is durable). -// - Write record: read the extent block, compute its CRC32, -// compare to record.DataCRC32. If they match, the write is -// durable and counts toward the recovered frontier. If they -// do NOT match, this is a torn pre-Sync write — skip the -// record so the LBA reads as whatever the extent currently -// holds (which is either the pre-write bytes, if the rollback -// path ran, or torn bytes if it didn't; either way the -// metadata no longer claims authority over them). +// - Trim record: counts as recovered (its CRC32 covers a zero +// block; if the extent matches that, the trim is durable). +// - Write record: read the extent block, compute its CRC32, +// compare to record.DataCRC32. If they match, the write is +// durable and counts toward the recovered frontier. If they +// do NOT match, fail closed with a WAL integrity error so the +// volume cannot report Ready=True after detecting corruption. // 4. The recovered frontier is the highest LSN among VALIDATED // records, not just the highest LSN seen in the ring. A record // whose CRC didn't verify cannot advance the frontier. @@ -56,7 +55,7 @@ func runRecovery(r *ring, fd *os.File, extentBase int64, blockSize int) (uint64, } } - var recovered, torn int + var recovered int var highestVerifiedLSN uint64 for _, rec := range lastWrite { if rec.Flags&flagTrim != 0 { @@ -69,10 +68,9 @@ func runRecovery(r *ring, fd *os.File, extentBase int64, blockSize int) (uint64, return 0, fmt.Errorf("smartwal: recovery read trim LBA %d: %w", rec.LBA, err) } if crc32.ChecksumIEEE(data) != rec.DataCRC32 { - log.Printf("smartwal: recovery trim CRC mismatch LSN=%d LBA=%d — skipping", - rec.LSN, rec.LBA) - torn++ - continue + detail := fmt.Sprintf("trim CRC mismatch LSN=%d LBA=%d", rec.LSN, rec.LBA) + log.Printf("smartwal: recovery %s — failing closed", detail) + return 0, storage.NewWALIntegrityFailure(nil, detail) } recovered++ if rec.LSN > highestVerifiedLSN { @@ -88,10 +86,10 @@ func runRecovery(r *ring, fd *os.File, extentBase int64, blockSize int) (uint64, } actual := crc32.ChecksumIEEE(data) if actual != rec.DataCRC32 { - log.Printf("smartwal: recovery CRC mismatch LSN=%d LBA=%d expected=%08x actual=%08x — skipping", + detail := fmt.Sprintf("CRC mismatch LSN=%d LBA=%d expected=%08x actual=%08x", rec.LSN, rec.LBA, rec.DataCRC32, actual) - torn++ - continue + log.Printf("smartwal: recovery %s — failing closed", detail) + return 0, storage.NewWALIntegrityFailure(nil, detail) } recovered++ if rec.LSN > highestVerifiedLSN { @@ -99,7 +97,7 @@ func runRecovery(r *ring, fd *os.File, extentBase int64, blockSize int) (uint64, } } - log.Printf("smartwal: recovery: %d LBAs verified, %d torn, frontier=%d", - recovered, torn, highestVerifiedLSN) + log.Printf("smartwal: recovery: %d LBAs verified, frontier=%d", + recovered, highestVerifiedLSN) return highestVerifiedLSN, nil } diff --git a/seaweed-block/core/storage/smartwal/smartwal_typed_failure_test.go b/seaweed-block/core/storage/smartwal/smartwal_typed_failure_test.go index cf6acff481..5043a34fe5 100644 --- a/seaweed-block/core/storage/smartwal/smartwal_typed_failure_test.go +++ b/seaweed-block/core/storage/smartwal/smartwal_typed_failure_test.go @@ -2,6 +2,7 @@ package smartwal import ( "errors" + "os" "path/filepath" "testing" @@ -50,6 +51,65 @@ func TestStorageRecoveryFailureKind_Smartwal_RecycleWrappedAsKind(t *testing.T) } } +func TestStorageRecoveryFailureKind_Smartwal_CRCMismatchWrappedAsWALIntegrity(t *testing.T) { + dir := t.TempDir() + path := filepath.Join(dir, "smartwal-integrity.sw") + s, err := CreateStore(path, 16, 4096) + if err != nil { + t.Fatalf("CreateStore: %v", err) + } + for i := uint32(0); i < 3; i++ { + data := make([]byte, 4096) + data[0] = byte(0xA0 + i) + if _, werr := s.Write(i, data); werr != nil { + t.Fatal(werr) + } + } + if _, err := s.Sync(); err != nil { + t.Fatalf("Sync: %v", err) + } + if err := s.Close(); err != nil { + t.Fatalf("Close: %v", err) + } + + layout, rec, err := LatestRecord(path) + if err != nil { + t.Fatalf("LatestRecord: %v", err) + } + extentOffset := layout.ExtentStart + int64(rec.LBA)*int64(layout.BlockSize) + f, err := os.OpenFile(path, os.O_RDWR, 0) + if err != nil { + t.Fatalf("OpenFile: %v", err) + } + if _, err := f.WriteAt([]byte{0x5A}, extentOffset); err != nil { + _ = f.Close() + t.Fatalf("corrupt extent: %v", err) + } + if err := f.Close(); err != nil { + t.Fatalf("close corrupted file: %v", err) + } + + reopened, err := OpenStore(path) + if err != nil { + t.Fatalf("OpenStore: %v", err) + } + defer reopened.Close() + _, recoverErr := reopened.Recover() + if recoverErr == nil { + t.Fatal("expected WAL integrity failure after extent/WAL CRC mismatch") + } + if !errors.Is(recoverErr, storage.ErrWALIntegrityFault) { + t.Fatalf("Recover error must satisfy errors.Is(_, ErrWALIntegrityFault); got: %v", recoverErr) + } + var rf *storage.RecoveryFailure + if !errors.As(recoverErr, &rf) { + t.Fatalf("Recover error must be *storage.RecoveryFailure via errors.As; got: %v", recoverErr) + } + if rf.Kind != storage.StorageRecoveryFailureWALIntegrity { + t.Fatalf("Kind = %v, want StorageRecoveryFailureWALIntegrity", rf.Kind) + } +} + // TestSmartwal_AppliedLSNs_ReportsRingEntries pins smartwal's // AppliedLSNs (ring-based reduction). func TestSmartwal_AppliedLSNs_ReportsRingEntries(t *testing.T) {