diff --git a/seaweed-block/core/frontend/nvme/session.go b/seaweed-block/core/frontend/nvme/session.go index 823f126e62..05ffe6d9f0 100644 --- a/seaweed-block/core/frontend/nvme/session.go +++ b/seaweed-block/core/frontend/nvme/session.go @@ -620,6 +620,10 @@ func (s *Session) handleWrite(ctx context.Context, req *Request) { }) s.recordWriteHandler(time.Since(handlerStart)) if res.AsError() != nil { + if s.logger != nil && res.SCT == SCTGeneric && res.SC == SCNamespaceNotReady && + (s.target == nil || s.target.allowWriteFailureLog(time.Now())) { + s.logger.Printf("nvme: Write failed qid=%d nsid=%d lba=%d blocks=%d sct=%#x sc=%#x elapsed=%s reason=%q", s.qid, req.capsule.NSID, req.capsule.Lba(), req.capsule.LbaLength(), res.SCT, res.SC, time.Since(arrival), res.Reason) + } req.resp.Status = res.completionStatus() } s.enqueueResponse(&response{resp: req.resp, writeCompletion: true, queuedAt: time.Now()}) diff --git a/seaweed-block/core/frontend/nvme/target.go b/seaweed-block/core/frontend/nvme/target.go index 5415e3f572..1a9bcfe0e3 100644 --- a/seaweed-block/core/frontend/nvme/target.go +++ b/seaweed-block/core/frontend/nvme/target.go @@ -13,6 +13,7 @@ import ( "log" "net" "sync" + "time" "github.com/seaweedfs/seaweed-block/core/frontend" ) @@ -81,6 +82,8 @@ type Target struct { sessions sync.WaitGroup logger Logger closed chan struct{} + // Shared by all connections of this volume; guarded by mu. + nextWriteFailureLog time.Time // Admin controller registry — populated on admin-queue // Connect (§3.1 A10.5 + R3), looked up on IO-queue Connect @@ -92,6 +95,18 @@ type Target struct { stats targetStats } +// Retryable failures can arrive on many connections at once. Keep the first +// cause immediately, then emit at most one diagnostic per second per target. +func (t *Target) allowWriteFailureLog(now time.Time) bool { + t.mu.Lock() + defer t.mu.Unlock() + if now.Before(t.nextWriteFailureLog) { + return false + } + t.nextWriteFailureLog = now.Add(time.Second) + return true +} + // NewTarget builds a Target. Provider must be non-nil. func NewTarget(cfg TargetConfig) *Target { if cfg.Provider == nil { diff --git a/seaweed-block/core/frontend/nvme/write_failure_log_test.go b/seaweed-block/core/frontend/nvme/write_failure_log_test.go new file mode 100644 index 0000000000..30edcd6d59 --- /dev/null +++ b/seaweed-block/core/frontend/nvme/write_failure_log_test.go @@ -0,0 +1,88 @@ +package nvme + +import ( + "bytes" + "context" + "errors" + "log" + "strings" + "sync" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend" + "github.com/seaweedfs/seaweed-block/core/frontend/testback" +) + +func TestSessionRetryableWriteLogsReason(t *testing.T) { + for _, tc := range []struct { + name string + err error + expired bool + }{ + {"busy", frontend.ErrBackendBusy, false}, + {"not-ready", frontend.ErrNotReady, false}, + {"deadline", context.DeadlineExceeded, true}, + } { + t.Run(tc.name, func(t *testing.T) { + var logs bytes.Buffer + backend := &pressureWriteBackend{Backend: testback.NewRecordingBackend(frontend.Identity{VolumeID: "v1"}), err: tc.err} + s := &Session{handler: NewIOHandler(HandlerConfig{Backend: backend}), target: &Target{}, logger: log.New(&logs, "", 0), qid: 7, respCh: make(chan *response, 1), done: make(chan struct{})} + req := &Request{payload: make([]byte, 512), receivedAt: time.Now(), capsule: CapsuleCommand{OpCode: ioWrite, NSID: 1, D10: 23}} + if tc.expired { + req.receivedAt = time.Now().Add(-5 * time.Second) + } + s.handleWrite(context.Background(), req) + if got := (<-s.respCh).resp.Status; got != MakeStatusField(SCTGeneric, SCNamespaceNotReady, false) { + t.Fatalf("completion=%#x", got) + } + for _, want := range []string{"nvme: Write failed", "qid=7", "nsid=1", "lba=23", "sc=0x82", "backend temporarily unavailable on write", tc.err.Error()} { + if !strings.Contains(logs.String(), want) { + t.Fatalf("missing %q in log %q", want, logs.String()) + } + } + if strings.Count(logs.String(), "\n") != 1 { + t.Fatalf("want one failure line: %q", logs.String()) + } + }) + } +} + +func TestSessionRetryableWriteLogBoundAcrossConnections(t *testing.T) { + var logs bytes.Buffer + logger := log.New(&logs, "", 0) + target := &Target{} + write := func(target *Target, cause error) { + backend := &pressureWriteBackend{Backend: testback.NewRecordingBackend(frontend.Identity{VolumeID: "v1"}), err: cause} + s := &Session{handler: NewIOHandler(HandlerConfig{Backend: backend}), target: target, logger: logger, respCh: make(chan *response, 1), done: make(chan struct{})} + req := &Request{payload: make([]byte, 512), receivedAt: time.Now(), capsule: CapsuleCommand{OpCode: ioWrite, NSID: 1}} + s.handleWrite(context.Background(), req) + <-s.respCh + } + // Neither a successful write nor an unrelated error consumes the first + // transient diagnostic or creates a new log stream. + write(target, nil) + write(target, errors.New("permanent failure")) + if logs.Len() != 0 { + t.Fatalf("unrelated writes logged: %q", logs.String()) + } + var wg sync.WaitGroup + for range 16 { + wg.Add(1) + go func() { defer wg.Done(); write(target, frontend.ErrBackendBusy) }() + } + wg.Wait() + if got := strings.Count(logs.String(), "nvme: Write failed"); got != 1 { + t.Fatalf("burst across connections logged %d lines, want 1", got) + } + // A different volume must retain its first diagnostic. + write(&Target{}, frontend.ErrNotReady) + if got := strings.Count(logs.String(), "nvme: Write failed"); got != 2 { + t.Fatalf("second target did not log independently: %d lines", got) + } + time.Sleep(1100 * time.Millisecond) + write(target, frontend.ErrBackendBusy) + if got := strings.Count(logs.String(), "nvme: Write failed"); got != 3 { + t.Fatalf("diagnostics did not resume after the rate window: %d lines", got) + } +} diff --git a/seaweed-block/core/storage/chunk_record_shadow.go b/seaweed-block/core/storage/chunk_record_shadow.go index 467c8d7660..9a44661af3 100644 --- a/seaweed-block/core/storage/chunk_record_shadow.go +++ b/seaweed-block/core/storage/chunk_record_shadow.go @@ -257,13 +257,19 @@ func (s *chunkRecordShadow) hashed(c capturedChunk, current func() uint64, head } // commit is E5 and E6: a HEAD names the chunk's captured hash. Skipped when -// the chunk was written since its capture. +// the chunk was written since its capture, and when the record does not hold +// a hash for it (HU or HP): a cut that captured the chunk while its absence +// stood sent no Hash, and on v1.0 its local bits can complete since (landed, +// P to U, with no version change); the chunk stays a candidate. func (s *chunkRecordShadow) commit(c capturedChunk, current func() uint64) bool { if c.idx >= s.rec.chunks { return false } same := capturedAt(c.version, current) - _, ok, err := s.rec.ApplyIf(c.idx, chunkkernel.Commit, dash, &c.sum, same) + hashedAt := func(k chunkkernel.Kind) bool { + return (k == chunkkernel.HashUnpublished || k == chunkkernel.HashPublished) && same(k) + } + _, ok, err := s.rec.ApplyIf(c.idx, chunkkernel.Commit, dash, &c.sum, hashedAt) if err != nil { s.defect(c.idx, chunkkernel.Commit, err) } diff --git a/seaweed-block/core/storage/chunk_record_shadow_test.go b/seaweed-block/core/storage/chunk_record_shadow_test.go index 2f7d3dacc0..5a69721661 100644 --- a/seaweed-block/core/storage/chunk_record_shadow_test.go +++ b/seaweed-block/core/storage/chunk_record_shadow_test.go @@ -620,3 +620,75 @@ func TestShadowScratchExemptionIsBoundToItsCapturedVersion(t *testing.T) { }) } } + +// E6 on a v1.0 shadow: a cut captured a written absent chunk while its +// absence stood (P: Hash skipped), and the flusher then completed the +// chunk's local bits (landed, P to U, with no write and so no version +// change) before the cut published. The publish's Commit at the captured +// version meets U: it is skipped, not sent (the kernel refuses U/Commit), +// and the chunk stays U, a candidate for the next cut. +func TestShadowCommitAfterAChunkLandedSinceItsScratchCaptureIsSkipped(t *testing.T) { + s, l, _ := lazyFreshVolume(t) + const idx = 3 + if _, err := s.Write(idx*ctChunkBlocks+1, makeBlock(ctBlockSize, 0xD3)); err != nil { + t.Fatal(err) + } + if k := shadowKind(l, idx); k != chunkkernel.Partial { + t.Fatalf("setup: the written absent chunk is %s, want P", k) + } + current := func() uint64 { return l.chunkVersion(idx) } + c := capturedChunk{idx: idx, version: current(), sum: [32]byte{1}} + l.shadow.hashed(c, current, chunkHead{}) // the cut's compare: skipped on P (a scratch capture) + l.stMu.Lock() + l.shadow.landed(idx) // the flusher completes the chunk's local bits + l.stMu.Unlock() + if k := shadowKind(l, idx); k != chunkkernel.Unknown || current() != c.version { + t.Fatalf("setup: after landing %s at version %d, want U at the captured version %d", k, current(), c.version) + } + l.shadowCommit([]capturedChunk{c}, map[uint64]uint64{idx: c.version}) // the publish + if n := shadowDefects(l); n != 0 { + t.Fatalf("%d shell events refused: Commit was sent for a chunk the record holds U", n) + } + if k := shadowKind(l, idx); k != chunkkernel.Unknown { + t.Fatalf("after the publish: %s, want U (a candidate for the next cut)", k) + } +} + +// The model's premise "every record state change moves the chunk version" +// holds on v1.1 only: there an extent write never lands an absent chunk +// (the write's own event carries the store's bits), so completing a written +// chunk's local bits through the flusher leaves its kind and version as they +// were. On v1.0 the same extent writes land it (P to U) with no version +// change: the case the Commit guard covers. +func TestShadowExtentWritesLandAnAbsentChunkOnlyOnV10(t *testing.T) { + for _, v11 := range []bool{true, false} { + t.Run(map[bool]string{true: "v1.1", false: "v1.0"}[v11], func(t *testing.T) { + if v11 { + withV11Format(t) + } + s, l, _ := lazyFreshVolume(t) + const idx = 3 + lsn, err := s.Write(idx*ctChunkBlocks+1, makeBlock(ctBlockSize, 0xD4)) + if err != nil { + t.Fatal(err) + } + kind, version := shadowKind(l, idx), l.chunkVersion(idx) + if kind != chunkkernel.Partial { + t.Fatalf("setup: the written absent chunk is %s, want P", kind) + } + for b := uint64(0); b < ctChunkBlocks; b++ { + l.OnExtentWrite(idx*ctChunkBlocks+b, lsn) // the flusher's extent writes complete the local bits + } + after, v := shadowKind(l, idx), l.chunkVersion(idx) + switch { + case v11 && (after != kind || v != version): + t.Fatalf("v1.1: extent writes moved the record %s->%s (version %d->%d): an extent write must not land a chunk", kind, after, version, v) + case !v11 && (after != chunkkernel.Unknown || v != version): + t.Fatalf("v1.0 control: %s at version %d, want U at the same version %d (landed)", after, v, version) + } + if n := shadowDefects(l); n != 0 { + t.Fatalf("%d shell events refused", n) + } + }) + } +} diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index dc647bdaf4..9d61787496 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -647,7 +647,7 @@ The "Machine / transition" column refers to Part A. Notes under a table record w | `INV-CHUNK-RECORD-SEED-001` | The v1.0.x upgrade seeds a whole local chunk as published with HEAD's hash only on an unmarked store, with a clean stop read on the HEAD the claim was built on (an idle detach of the store's lineage) at the store's synced position; otherwise it is unknown. | M1 Recovering → Serving (v1.1 upgrade at attach, after a clean stop) | `core/frontend/chunkstore/layout/start.go` `Start` (`ReportCleanStop`); `core/storage/chunk_record_upgrade.go` `upgradeChunkRecordSeeded`, `seedsLineage`, `cleanStopHashes` | `TestStart_ReportsTheCleanStopItClaimedFrom`, `TestStart_TheCleanStopIsTheClaimsOwnRead`, `TestStart_NoCleanStopWithoutADetachOfThisLineage` (`core/frontend/chunkstore/layout/start_cleanstop_test.go`); `TestUpgradeSeedsAfterACleanStop`, `TestUpgradeSeedNeedsTheStoreAtTheProofPosition`, `TestUpgradeSeedNeedsTheStoresLineage`, `TestUpgradeSeedNeedsAProofHEADStillShows`, `TestUpgradeSeedCrashAtEachStep` (`core/storage/chunk_record_seed_test.go`); `TestV11AttachSeedsFromTheCleanStopInItsConfig` (`core/storage/chunk_record_v11_seed_test.go`); `TestStartLayoutRootReportsTheCleanStop` (`core/frontend/durable/provider_layout_cleanstop_test.go`) | UpgradeWide3 rows 122 and 123 (`Proof`, `SameEpoch` judged on the HEAD the claim is built on; the claim is a stutter on image and position), 126 to 128 (the per-chunk state models are not in this repository) | STUB | | `INV-CHUNK-UPGRADE-PASS-CURSOR-001` | Upgrade pass: rewinds only at open, before Run; a failed rewind latches it until reopen; the persisted cursor is only ever min(earliest unpublished rewind, last written-through position); a restart resumes there; while it runs, a request needing every hash answers in_progress. | M1 Opened (v1.1 upgrade compare pass) | `core/storage/chunk_upgrade_pass.go` `upgradePass.Run`, `advance`, `Rewind`, `Admit` | `TestUpgradePassCursorFollowsThePagesBehindIt`, `TestUpgradePassRestartContinuesAtTheCursor`, `TestUpgradePassRefusesWithProgress`, `TestUpgradePassRewindAtOpenAfterARebuiltPage`, `TestUpgradePassPauseAndHurry`, `TestUpgradePassFailedRewindLatchesUntilReopen`, `TestUpgradePassRewindOnlyBeforeRun`, `TestUpgradePassKeepsItsCountAcrossRuns`, `TestUpgradePassCursorRuleUnderInterleavings` (`core/storage/chunk_upgrade_pass_test.go`) | UpgradePass `BehindCursorKnown`, `NoWorkTwice`; UpgradeWide3 rows 119 to 124, rewinds at restart only (the per-chunk state models are not in this repository) | STUB | | `INV-CHUNK-RECORD-RUNTIME-001` | While serving: state only via the kernel, a hash only with its evidence; a page dirties only on a state or hash change and is written by its count or age (an evict's at once), in snapshot order, after the WAL is synced through the position it shows; G <= min(applied, dirty-from, WAL synced). | M3 Serving (chunk record runtime) | `core/storage/chunk_record_runtime.go` `chunkRecordRuntime.Apply`, `Due`, `WriteDue`, `WriteThrough`, `Flush`, `writeSegmentLocked` (`syncThrough`), `writeHeaderLocked` (`durable`) | `TestRecordRuntimeAppliesTheKernel`, `TestRecordRuntimeEvictWritesThePageFirst`, `TestRecordRuntimeSchedulePerPage`, `TestRecordRuntimeFlushIsLoadedBack`, `TestRecordRuntimeWriteThrough`, `TestRecordRuntimeAnUnchangedStateWritesNothing`, `TestRecordRuntimeHeaderMovesUnderWrites`, `TestRecordRuntimeEvictDuringAFlushLandsLast`, `TestRecordRuntimePageWritesFollowChangesNotSize`, `TestRecordRuntimePageWritersPublishInOrder`, `TestRecordRuntimeHashEvidence`, `TestRecordRuntimeCopiesItsInputs`, `TestRecordRuntimeAPageChangedAtOpenHoldsG` (`core/storage/chunk_record_runtime_test.go`); the WAL bound: `TestV11NoPageClaimsMoreThanTheDurableWAL`, `TestV11APageNeverShowsAWriteTheWALCanLose` (`core/storage/chunk_record_v11_review_test.go`, `chunk_record_v11_hold_test.go`) | chunk-kernel/2; ChunkPages rule 1 (pages before the header) and rule 3 (an evict writes its page first) (the per-chunk state models are not in this repository) | STUB | -| `INV-CHUNK-RECORD-SHADOW-001` | While serving, the chunk record follows the engine's events via the kernel; an event bound to a captured version is skipped, never refused, after a write; at each barrier every chunk the engine captures is a record candidate. It decides nothing; on v1.0 it writes no page. | M3 Serving (chunk record shadow) | `core/storage/chunk_record_shadow.go` `newChunkRecordShadow`, `chunkRecordShadow.check`; `core/storage/chunk_layer.go` `noteMutation`, `fillOnce`, `EvictChunk`, `recoveredLocked`, `BeforeCheckpointAdvance`, `shadowCommit`, `shadowCommitCaptured` (also from `resolvePending`, `SettleDetach`); `core/storage/chunk_cut_payload.go` `markEqualNow`; `core/storage/chunk_record_runtime.go` `ApplyIf` | `TestShadowWriteCoverageFollowsTheStoreBitmap`, `TestShadowFillRacedByAWriteEndsUnknown`, `TestShadowCutOfAPartialChunkKeepsItPartial`, `TestShadowAttachKeepsACheckpointedWriteACandidate`, `TestShadowWriteRacingHashAndCommitIsSkippedNotRefused`, `TestShadowEvictEdges`, `TestShadowRecordWritesNoPage`, `TestShadowCheckerIsExactAndCatchesAMissingWrite`, `TestShadowRecoverChangesOnlyTheRecoveredChunks`, `TestShadowBaseInstallCompletingChangesEveryChunk`, `TestShadowDelayedSettlementCommitsTheCapturedChunks`, `TestShadowProductionCheckDoesNotScanTheRecord`, `TestShadowScratchExemptionIsBoundToItsCapturedVersion` (`core/storage/chunk_record_shadow_test.go`); every test of the package runs with the shadow strict, misses and extra record candidates both (`TestMain`, `core/storage/chunk_record_shadow_main_test.go`) | chunk-kernel/2 (the per-chunk state models are not in this repository) | ACTIVE | +| `INV-CHUNK-RECORD-SHADOW-001` | While serving, the chunk record follows the engine's events via the kernel; an event bound to a captured version is skipped, never refused, after a write; at each barrier every chunk the engine captures is a record candidate. It decides nothing; on v1.0 it writes no page. | M3 Serving (chunk record shadow) | `core/storage/chunk_record_shadow.go` `newChunkRecordShadow`, `chunkRecordShadow.check`; `core/storage/chunk_layer.go` `noteMutation`, `fillOnce`, `EvictChunk`, `recoveredLocked`, `BeforeCheckpointAdvance`, `shadowCommit`, `shadowCommitCaptured` (also from `resolvePending`, `SettleDetach`); `core/storage/chunk_cut_payload.go` `markEqualNow`; `core/storage/chunk_record_runtime.go` `ApplyIf` | `TestShadowWriteCoverageFollowsTheStoreBitmap`, `TestShadowFillRacedByAWriteEndsUnknown`, `TestShadowCutOfAPartialChunkKeepsItPartial`, `TestShadowCommitAfterAChunkLandedSinceItsScratchCaptureIsSkipped`, `TestShadowExtentWritesLandAnAbsentChunkOnlyOnV10`, `TestShadowAttachKeepsACheckpointedWriteACandidate`, `TestShadowWriteRacingHashAndCommitIsSkippedNotRefused`, `TestShadowEvictEdges`, `TestShadowRecordWritesNoPage`, `TestShadowCheckerIsExactAndCatchesAMissingWrite`, `TestShadowRecoverChangesOnlyTheRecoveredChunks`, `TestShadowBaseInstallCompletingChangesEveryChunk`, `TestShadowDelayedSettlementCommitsTheCapturedChunks`, `TestShadowProductionCheckDoesNotScanTheRecord`, `TestShadowScratchExemptionIsBoundToItsCapturedVersion` (`core/storage/chunk_record_shadow_test.go`); every test of the package runs with the shadow strict, misses and extra record candidates both (`TestMain`, `core/storage/chunk_record_shadow_main_test.go`) | chunk-kernel/2 (the per-chunk state models are not in this repository) | ACTIVE | | `INV-CHUNK-RECORD-V11-001` | On the draft v1.1 format a layer upgrades its store once at attach and opens from its record; a fill's page claims no local block before one durable mark (partial fills and later writes too); an evict clears the store's bits only after its absent page is durable, retries too. | M1 Opened, M3 Serving (draft v1.1 format) | `core/storage/chunk_record_open.go` `openChunkRecordV11`, `loadChunkRecordV11`, `markFills`; `core/storage/chunk_record_upgrade.go` `upgradeChunkRecordWith`; `core/storage/chunk_record_runtime.go` `holdFills`, `PersistSegmentOf`; `core/storage/chunk_record_shadow.go` `evict`; `core/storage/chunk_layer.go` `EvictChunk`, `Close` | `TestV11AttachUpgradesTheStoreOnce`, `TestV11ReopenJudgesAWriteAfterThePageAsChanged`, `TestV11CleanStopWritesOnlyTheDirtyPages`, `TestV11UpgradeRecoversFromACrashAtEachStep`, `TestV11DamagedPageIsRebuiltFromTheStoreBits`, `TestV11FillsAreMarkedInOneBatchBeforeTheirPagesClaimThem`, `TestV11EvictSurvivesARestart` (`core/storage/chunk_record_v11_test.go`); `TestV11CloseDuringTheUpgradeRefusesTheAttach`, `TestV11EvictWithoutItsAbsentPageClearsNothing`, `TestV11ParkedFillBatchCannotOverwriteAnEvict`, `TestV11MalformedLeftoverPresenceDoesNotRefuseTheAttach`, `TestV11FinalPageFailureIsTheCloseResult` (`core/storage/chunk_record_v11_review_test.go`); `TestV11PartialFillWaitsForTheDurableMark`, `TestV11WriteAfterAHeldFillKeepsTheHold`, `TestV11EvictRetryStillWritesItsAbsentPage` (`core/storage/chunk_record_v11_hold_test.go`); `TestV11AbsentChunkSurvivesALostHeader`, `TestV11LogOnlyWriteSurvivesTheUpgrade` (`core/storage/chunk_record_v11_upgrade_test.go`) | chunk-kernel/2; CoverageDurable row 199 (the WAL is durable through a published position) (not in this repository) | DORMANT | | `INV-CHUNK-FOREIGN-ROOT-FENCE-001` | A HEAD that moved past the holder's base without superseding it and is not its own proposal must keep the chunk root; one that changed it fences the layer (`errChunkForeignRoot`), so no chunk is held clean against a root that no longer names it. | M5 Commit (head conflict, settlement) | `core/storage/chunk_layer.go` `adoptHeadLocked` (from `captureLocked`, `SettleDetach`, `resolvePending`) | `TestShadowForeignRootWithoutSupersedeFences` (`core/storage/chunk_record_shadow_test.go`) | HeadWriters (only metadata writers move HEAD without superseding; not in this repository) | ACTIVE | | `INV-CHUNK-RECORD-PAYLOAD-001` | Persisting and loading a chunk record preserves every entry's state and hash, including entries on either side of a segment boundary. | M1 chunk record codec (caller not wired) | `core/storage/chunk_record.go` `encodeChunkRecordPage`, `decodeChunkRecordPage` | `TestRecordEntryPayloadRoundTripsAcrossSegments` (`core/storage/chunk_record_test.go`; state-zero and one-entry hash-drop controls) | Encoding fidelity; no state transition change | STUB |