From 48578ac8e36aa263bdf459ef14d75bd559a32d5d Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 29 Nov 2026 16:21:44 -0800 Subject: [PATCH] fix: share captured equality recording across cut outcomes --- .../storage/chunk_copy_error_equal_test.go | 13 ++++-- seaweed-block/core/storage/chunk_layer.go | 45 ++++++++----------- seaweed-block/docs/design/invariants.md | 2 +- 3 files changed, 28 insertions(+), 32 deletions(-) diff --git a/seaweed-block/core/storage/chunk_copy_error_equal_test.go b/seaweed-block/core/storage/chunk_copy_error_equal_test.go index 1dd48f5bc1..b4ed424d1e 100644 --- a/seaweed-block/core/storage/chunk_copy_error_equal_test.go +++ b/seaweed-block/core/storage/chunk_copy_error_equal_test.go @@ -9,12 +9,17 @@ import ( ) func TestCopyErrorKeepsCapturedEqualMarks(t *testing.T) { - for _, mode := range []string{"spill_cap", "context_end", "write_after_capture"} { + for _, mode := range []string{"spill_cap", "context_end", "write_after_capture", "different_staged"} { t.Run(mode, func(t *testing.T) { s, l, f := unknownFilledVolume(t) l.cfg.UploadConcurrency = 1 l.cfg.COWSpillFree = func() (int64, error) { return 2 * (cowSpillFreeReserve + 2*ctChunkBytes), nil } image := f.imageOf(t, f.stats().head) + if mode == "different_staged" { + if _, err := s.Write(2*ctChunkBlocks, makeBlock(ctBlockSize, 0xE9)); err != nil { + t.Fatal(err) + } + } // Stage the image, then invalidate two staged copies before the barrier. // The other six equal results are captured without another COW read. l.testBeforeBarrierLockHook = func() { @@ -66,10 +71,10 @@ func TestCopyErrorKeepsCapturedEqualMarks(t *testing.T) { } l.stMu.Unlock() want := 6 - if mode == "write_after_capture" { + if mode == "write_after_capture" || mode == "different_staged" { want-- } - if len(marked) != want || (mode == "write_after_capture" && marked[2]) { + if len(marked) != want || ((mode == "write_after_capture" || mode == "different_staged") && marked[2]) { t.Fatalf("kept equal marks %v, want %d captured versions (no later write)", marked, want) } l.testBeforeBarrierLockHook, l.testCOWRead = nil, nil @@ -86,7 +91,7 @@ func TestCopyErrorKeepsCapturedEqualMarks(t *testing.T) { if result.Stats.CandidateChunks != 8-want || repeated.Load() != 0 { t.Fatalf("retry candidates=%d repeated=%d; want %d and 0", result.Stats.CandidateChunks, repeated.Load(), 8-want) } - if mode == "write_after_capture" && !bytes.Equal(blockOf(f.imageOf(t, result.Head), 2*ctChunkBlocks), makeBlock(ctBlockSize, 0xE9)) { + if (mode == "write_after_capture" || mode == "different_staged") && !bytes.Equal(blockOf(f.imageOf(t, result.Head), 2*ctChunkBlocks), makeBlock(ctBlockSize, 0xE9)) { t.Fatal("retry lost the write made after capture") } }) diff --git a/seaweed-block/core/storage/chunk_layer.go b/seaweed-block/core/storage/chunk_layer.go index 9d06f4d787..bb45602b51 100644 --- a/seaweed-block/core/storage/chunk_layer.go +++ b/seaweed-block/core/storage/chunk_layer.go @@ -784,6 +784,22 @@ func (l *chunkLayerImpl) latchIdentityMoved(err error) error { // an identity-moved signal; it returns err unchanged. func (l *chunkLayerImpl) ObserveRemoteError(err error) error { return l.latchIdentityMoved(err) } +// recordCapturedEqualMarks shares the success and copy-abort proof rule. +// A mark names the barrier-captured version and base HEAD ref, never bytes +// uploaded but not committed or a version written after that barrier. +func (l *chunkLayerImpl) recordCapturedEqualMarks(captured []capturedChunk, versions map[uint64]uint64, head chunkHead) { + l.stMu.Lock() + defer l.stMu.Unlock() + for _, c := range captured { + ref, had := head.Chunks[c.idx] + if c.zero && !had || unchangedFromHead(c, ref, had) { + if v, ok := versions[c.idx]; ok && l.chunkVersion(c.idx) == v { + l.filledClean[c.idx] = filledMark{version: v, ref: ref} + } + } + } +} + func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res chunkCutResult, err error) { defer func() { err = l.latchIdentityMoved(err) }() done, err := l.register() @@ -1097,19 +1113,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch } st.UploadNs = st.CopyNs if copyErr != nil { - // Staged captures already compared equal before the window failed. - // Keep that work only at the version captured by this barrier: - // a guest write after capture must remain a retry candidate. - l.stMu.Lock() - for _, c := range captured { - ref, had := baseHead.Chunks[c.idx] - if c.zero && !had || unchangedFromHead(c, ref, had) { - if v, ok := capturedVersions[c.idx]; ok && l.chunkVersion(c.idx) == v { - l.filledClean[c.idx] = filledMark{version: v, ref: ref} - } - } - } - l.stMu.Unlock() + l.recordCapturedEqualMarks(captured, capturedVersions, baseHead) l.requeueCut(all) return chunkCutResult{}, fmt.Errorf("storage: capture copy: %w", copyErr) } @@ -1133,16 +1137,11 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch key string } var uploads []upload - // equal: the chunks this cut compared equal to HEAD, at the version it - // captured; recorded as clean marks below, so a rerun after this cut - // fails does not compare them again. - var equal []uint64 for _, c := range captured { ref, had := baseHead.Chunks[c.idx] switch { case c.zero && !had, unchangedFromHead(c, ref, had): st.UnchangedChunks++ - equal = append(equal, c.idx) continue case c.zero: delete(next.Chunks, c.idx) @@ -1164,15 +1163,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch if hook := l.testBeforeRecordMarksHook; hook != nil { hook() } - if len(equal) > 0 { - l.stMu.Lock() - for _, idx := range equal { - if v, ok := capturedVersions[idx]; ok && l.chunkVersion(idx) == v { - l.filledClean[idx] = filledMark{version: v, ref: baseHead.Chunks[idx]} - } - } - l.stMu.Unlock() - } + l.recordCapturedEqualMarks(captured, capturedVersions, baseHead) // The holder's session is begun before the first upload: every object // the cut writes belongs to it until the commit (CASHead) or Abort. l.cutPhase("upload") diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 2142245412..4b69401770 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -602,7 +602,7 @@ The "Machine / transition" column refers to Part A. Notes under a table record w | `INV-WAL-V3-FLUSH-PROFILE-001` | Native flusher header/full-record/decode counters describe actual reads and validation; I/O failure is distinct from validation failure and only successfully materialized blocks count validated. | M1 checkpoint instrumentation | `walstore_v3.go` `readWholeRecordProfiledV3`, `readDirtyRecordV3` | `TestFlusherV3ProfileCountsRealRecordStages` | Observability; no durability transition change | ACTIVE | | `INV-WAL-V3-WRITE-AHEAD-001` | No extent byte reaches the disk before its WAL record is durable: the flusher writes an extent only from dirty entries at or below the synced (acknowledged) WAL frontier; Recover and the install log fsync their records before raising it. | M1 Serving (flusher extent write) | `core/storage/flusher.go` `flushOnceInternal`; `walstore_v3.go` `recoverV3` (descriptor publish fsync before `wack`); `install_log_v3.go` | `TestRedCrashKeepingAnUnsyncedExtentWriteLeavesLocalAndHEADApart` (`core/storage/chunk_u1_reorder_test.go`); `TestFlusherWriteAheadNeverFlushingGuestReachesExtentAtPressure` (`core/storage/flusher_write_ahead_test.go`) | A checkpoint may pass a synced record superseded by an unsynced newer one only because the cycle's sync covers the whole file, WAL included (one file, one descriptor: `INV-WAL-FLUSH-SYNC-COVERS-WAL-001`); separating WAL and extent, or a range sync, must first change the checkpoint bound | ACTIVE | | `INV-WAL-V3-CAPTURE-CANDIDATES-001` | A retained WAL entry already covered by HEAD is not dirt since HEAD. New post-HEAD WAL entries, UNKNOWN map chunks and map max-LSN above HEAD remain capture candidates, except as `INV-WAL-V3-CAPTURE-COMPARED-001`. | M5 candidate selection | `chunk_layer.go` `captureCandidates` | `TestChunkLayerV3CapturedUncheckpointedWALIsCleanUntilRewritten`, `TestChunkLayerV3_CaptureUsesOwnedMapAfterCheckpoint`, `TestBaseInstallV3CompletePersistsTheMapUnknownOfBaseWrites` | Conservative reachability unchanged; narrower redundant work | ACTIVE | -| `INV-WAL-V3-CAPTURE-COMPARED-001` | A chunk known equal to HEAD is neither staged nor compared again while its mutation version and HEAD ref match; own-batch chunks remain candidates. A refused or copy-aborted cut retains these proofs and requeues only unproven chunks. All candidate paths use one predicate. | M5 candidate selection | `core/storage/chunk_layer.go` `knownEqualToHeadLocked`, `captureCandidates`, `captureLocked`, `stage`, `requeueCut`; `chunk_cut_payload.go` `markEqualNow` | `TestFreshFromHeadReadBackLeavesNoCutCandidates`, `TestFreshFromHeadFilledThenWrittenIsACandidate`, `TestEveryLocalWriteAfterACleanFillMakesTheChunkACandidate`, `TestABaseInstallAfterCleanFillsEndsTheirRecords`, `TestACleanFillRecordEndsWithItsHeadRef`, `TestARestoreTargetThatOnlyReadCutsNothing`, `TestARerunAfterAFailedCutComparesOnlyWhatDiffers`, `TestWithoutAFailedCutEveryUnknownChunkIsCompared`, `TestACutOffCompareKeepsItsWorkAndTheRerunComparesOnlyTheRest`, `TestFilledChunksAreFirstCutCandidatesAfterARestart`, `TestEveryDirtyMapInsertNotesTheChunkMutation`, `TestOwnBatch_BoundedBatchesReplaceEveryForeignKey`; `TestRefusedFullCutStagesOnlyTheUnmarkedChunk` (`core/storage/chunk_staging_equal_test.go`); `TestCopyErrorKeepsCapturedEqualMarks` (`core/storage/chunk_copy_error_equal_test.go`); `TestTimedOutRequestsThenRefusedCommitKeepEqualWork` (`core/frontend/chunkstore/layout_staging_retry_test.go`) | Conservative reachability unchanged; narrower redundant work | ACTIVE | +| `INV-WAL-V3-CAPTURE-COMPARED-001` | A chunk known equal to HEAD is neither staged nor compared again while its mutation version and HEAD ref match; own-batch chunks remain candidates. A refused or copy-aborted cut retains these proofs and requeues only unproven chunks. All candidate paths use one predicate. | M5 candidate selection | `core/storage/chunk_layer.go` `knownEqualToHeadLocked`, `captureCandidates`, `captureLocked`, `recordCapturedEqualMarks`, `stage`, `requeueCut`; `chunk_cut_payload.go` `markEqualNow` | `TestFreshFromHeadReadBackLeavesNoCutCandidates`, `TestFreshFromHeadFilledThenWrittenIsACandidate`, `TestEveryLocalWriteAfterACleanFillMakesTheChunkACandidate`, `TestABaseInstallAfterCleanFillsEndsTheirRecords`, `TestACleanFillRecordEndsWithItsHeadRef`, `TestARestoreTargetThatOnlyReadCutsNothing`, `TestARerunAfterAFailedCutComparesOnlyWhatDiffers`, `TestWithoutAFailedCutEveryUnknownChunkIsCompared`, `TestACutOffCompareKeepsItsWorkAndTheRerunComparesOnlyTheRest`, `TestFilledChunksAreFirstCutCandidatesAfterARestart`, `TestEveryDirtyMapInsertNotesTheChunkMutation`, `TestOwnBatch_BoundedBatchesReplaceEveryForeignKey`; `TestRefusedFullCutStagesOnlyTheUnmarkedChunk` (`core/storage/chunk_staging_equal_test.go`); `TestCopyErrorKeepsCapturedEqualMarks` (`core/storage/chunk_copy_error_equal_test.go`); `TestTimedOutRequestsThenRefusedCommitKeepEqualWork` (`core/frontend/chunkstore/layout_staging_retry_test.go`) | EqualMarks.MarkSound, EqualMarks.NoRecompare (must-violate rows 102-104); conservative reachability unchanged | ACTIVE | | `INV-WAL-V3-DESCRIPTOR-001` | A v3 descriptor slot is used only if it is valid: a matching CRC32C (Castagnoli), every reserved byte zero, an accepted impl, a nonzero slotGen at most 2^64-2, a nonzero nonce, and geometry consistent under checked arithmetic. | M1 Opened (v3 descriptor selection) | `core/storage/superblock_v3.go` `decodeSlotV3`, `descriptorV3.validate`, `checkedAddV3` | `TestSlotV3VectorsDecodeAsExpected`, `TestSlotV3CounterExhaustion` (`core/storage/superblock_v3_test.go`) | — | STUB | | `INV-WAL-V3-DESCRIPTOR-BASE-001` | A valid v3 descriptor slot has CheckpointLSN ≤ mapCoveredCheckpoint ≤ W, and BASE fields that follow the rules of its BASE state. | M1 Opened (v3 descriptor selection) | `core/storage/superblock_v3.go` `descriptorV3.validate` | `TestSlotV3VectorsDecodeAsExpected`, `TestSlotV3InstalledMayHaveCursorBelowTail` (`core/storage/superblock_v3_test.go`) | — | STUB | | `INV-WAL-V3-DESCRIPTOR-SELECT-001` | Of the two v3 descriptor slots, open selects the valid selectable slot with the higher slotGen, and never a prepared migration slot. | M1 Opened (v3 descriptor selection) | `core/storage/superblock_v3.go` `selectSlotV3` | `TestSlotV3Selection` (`core/storage/superblock_v3_test.go`); `TestWALStoreV3CloseKeepsTheNewestSlotAAndItsW` (`core/storage/walstore_close_v3_test.go`) | — | ACTIVE |