From 4c4506c7c74c6446614f64614cfaa2258c9b7d40 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 29 Nov 2026 16:17:38 -0800 Subject: [PATCH 1/6] test: retain captured equality across copy aborts --- .../storage/chunk_copy_error_equal_test.go | 94 +++++++++++++++++++ 1 file changed, 94 insertions(+) create mode 100644 seaweed-block/core/storage/chunk_copy_error_equal_test.go diff --git a/seaweed-block/core/storage/chunk_copy_error_equal_test.go b/seaweed-block/core/storage/chunk_copy_error_equal_test.go new file mode 100644 index 0000000000..1dd48f5bc1 --- /dev/null +++ b/seaweed-block/core/storage/chunk_copy_error_equal_test.go @@ -0,0 +1,94 @@ +package storage + +import ( + "bytes" + "context" + "errors" + "sync/atomic" + "testing" +) + +func TestCopyErrorKeepsCapturedEqualMarks(t *testing.T) { + for _, mode := range []string{"spill_cap", "context_end", "write_after_capture"} { + 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) + // 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() { + for _, idx := range []uint64{0, 1} { + lba := uint32(idx * ctChunkBlocks) + if _, err := s.Write(lba, blockOf(image, lba)); err != nil { + t.Error(err) + } + } + } + ctx, cancel := context.WithCancel(ctTimeout(t)) + defer cancel() + var triggered atomic.Bool + l.testCOWRead = func(idx uint64, _ bool) { + if triggered.Swap(true) { + return + } + w := l.cowActive.Load() + if mode == "write_after_capture" { + if _, err := s.Write(2*ctChunkBlocks, makeBlock(ctBlockSize, 0xE9)); err != nil { + t.Error(err) + } + } + if mode == "spill_cap" { + w.mu.Lock() + w.memory, w.spillLimit = w.memoryLimit, 0 + w.mu.Unlock() + other := uint32((1 - idx) * ctChunkBlocks) + if _, err := s.Write(other, blockOf(image, other)); err != nil { + t.Error(err) + } + } else { + cancel() + w.abort(context.Canceled) + } + } + _, err := l.Cut(ctx) + wantErr := error(context.Canceled) + if mode == "spill_cap" { + wantErr = errCutCOWCapacity + } + if !triggered.Load() || !errors.Is(err, wantErr) { + t.Fatalf("copy did not abort as intended: %v", err) + } + l.stMu.Lock() + marked := make(map[uint64]bool) + for idx := range l.filledClean { + marked[idx] = true + } + l.stMu.Unlock() + want := 6 + if mode == "write_after_capture" { + want-- + } + if len(marked) != want || (mode == "write_after_capture" && marked[2]) { + t.Fatalf("kept equal marks %v, want %d captured versions (no later write)", marked, want) + } + l.testBeforeBarrierLockHook, l.testCOWRead = nil, nil + var repeated atomic.Int64 + l.testAfterCompareHook = func(idx uint64) { + if marked[idx] { + repeated.Add(1) + } + } + result, err := l.Cut(ctTimeout(t)) + if err != nil { + t.Fatal(err) + } + 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)) { + t.Fatal("retry lost the write made after capture") + } + }) + } +} From 1a04289ebafe42da4d4a65d4d87323563fff46c4 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 29 Nov 2026 16:17:54 -0800 Subject: [PATCH 2/6] fix: keep captured equal marks when copy fails --- seaweed-block/core/storage/chunk_layer.go | 13 +++++++++++++ seaweed-block/docs/design/invariants.md | 2 +- 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/seaweed-block/core/storage/chunk_layer.go b/seaweed-block/core/storage/chunk_layer.go index 4a89376315..9d06f4d787 100644 --- a/seaweed-block/core/storage/chunk_layer.go +++ b/seaweed-block/core/storage/chunk_layer.go @@ -1097,6 +1097,19 @@ 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.requeueCut(all) return chunkCutResult{}, fmt.Errorf("storage: capture copy: %w", copyErr) } diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 4474ea69b9..2142245412 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 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`); `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`, `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-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 | From 48578ac8e36aa263bdf459ef14d75bd559a32d5d Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 29 Nov 2026 16:21:44 -0800 Subject: [PATCH 3/6] 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 | From 7d3b3ec1269fbc55dd3fa95ea7cbc949fbc80064 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 29 Nov 2026 16:25:52 -0800 Subject: [PATCH 4/6] test: keep partial staging comparisons across cancellation --- .../storage/chunk_copy_error_equal_test.go | 94 ++++++++++++++++++- 1 file changed, 90 insertions(+), 4 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 b4ed424d1e..6e16b230e6 100644 --- a/seaweed-block/core/storage/chunk_copy_error_equal_test.go +++ b/seaweed-block/core/storage/chunk_copy_error_equal_test.go @@ -67,7 +67,9 @@ func TestCopyErrorKeepsCapturedEqualMarks(t *testing.T) { l.stMu.Lock() marked := make(map[uint64]bool) for idx := range l.filledClean { - marked[idx] = true + if l.knownEqualToHeadLocked(idx) { + marked[idx] = true + } } l.stMu.Unlock() want := 6 @@ -78,8 +80,9 @@ func TestCopyErrorKeepsCapturedEqualMarks(t *testing.T) { t.Fatalf("kept equal marks %v, want %d captured versions (no later write)", marked, want) } l.testBeforeBarrierLockHook, l.testCOWRead = nil, nil - var repeated atomic.Int64 + var compared, repeated atomic.Int64 l.testAfterCompareHook = func(idx uint64) { + compared.Add(1) if marked[idx] { repeated.Add(1) } @@ -88,8 +91,15 @@ func TestCopyErrorKeepsCapturedEqualMarks(t *testing.T) { if err != nil { t.Fatal(err) } - 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) + wantCompared, wantCandidates := int64(2), 0 + if mode == "write_after_capture" { + wantCompared++ + } + if want == 5 { + wantCandidates = 1 + } + if result.Stats.CandidateChunks != wantCandidates || compared.Load() != wantCompared || repeated.Load() != 0 { + t.Fatalf("retry candidates=%d compared=%d repeated=%d; want %d,%d,0", result.Stats.CandidateChunks, compared.Load(), repeated.Load(), wantCandidates, wantCompared) } 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") @@ -97,3 +107,79 @@ func TestCopyErrorKeepsCapturedEqualMarks(t *testing.T) { }) } } + +// A deadline inside pre-copy must keep the completed comparisons, not only +// the results of an entire staging round that reached the capture barrier. +func TestInterruptedStagingKeepsEqualWork(t *testing.T) { + for _, mutate := range []bool{false, true} { + name := "context_end" + if mutate { + name = "write_after_read" + } + t.Run(name, func(t *testing.T) { + s, l, f := unknownFilledVolume(t) + l.cfg.UploadConcurrency = 1 + l.cfg.COWSpillFree = func() (int64, error) { return 2 * (cowSpillFreeReserve + ctChunkBytes), nil } + ctx, cancel := context.WithCancel(ctTimeout(t)) + defer cancel() + var reads atomic.Int64 + var written uint64 + l.testAfterStageReadHook = func(idx uint64) { + n := reads.Add(1) + if n == 1 && mutate { + written = idx + if _, err := s.Write(uint32(idx*ctChunkBlocks), makeBlock(ctBlockSize, 0xEC)); err != nil { + t.Error(err) + } + } + if n == 3 { + cancel() + } + } + if _, err := l.Cut(ctx); !errors.Is(err, context.Canceled) { + t.Fatalf("staging cancellation: %v", err) + } + l.stMu.Lock() + kept := make(map[uint64]bool) + for idx := range l.filledClean { + if l.knownEqualToHeadLocked(idx) { + kept[idx] = true + } + } + l.stMu.Unlock() + want := 3 + if mutate { + want-- + } + if len(kept) != want || (mutate && kept[written]) { + t.Fatalf("staging kept %v, want %d valid captured proofs", kept, want) + } + if !mutate { + written = 7 // not among the first three completed comparisons + if kept[written] { + t.Fatal("fixture wrote a retained chunk") + } + if _, err := s.Write(uint32(written*ctChunkBlocks), makeBlock(ctBlockSize, 0xEC)); err != nil { + t.Fatal(err) + } + } + var retryReads, repeated atomic.Int64 + l.testAfterStageReadHook = func(idx uint64) { + retryReads.Add(1) + if kept[idx] { + repeated.Add(1) + } + } + result, err := l.Cut(ctTimeout(t)) + if err != nil { + t.Fatal(err) + } + if result.Stats.CandidateChunks != 1 || retryReads.Load() != int64(8-want) || repeated.Load() != 0 { + t.Fatalf("retry candidates=%d reads=%d repeated=%d, want 1,%d,0", result.Stats.CandidateChunks, retryReads.Load(), repeated.Load(), 8-want) + } + if !bytes.Equal(blockOf(f.imageOf(t, result.Head), uint32(written*ctChunkBlocks)), makeBlock(ctBlockSize, 0xEC)) { + t.Fatal("retry lost the write after the staging read") + } + }) + } +} From 6c0661dc3e0ec704db1f804538fbaabad09d6d75 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 29 Nov 2026 16:28:43 -0800 Subject: [PATCH 5/6] fix: preserve completed equality proofs during staging --- seaweed-block/core/storage/chunk_cut_payload.go | 10 ++++------ seaweed-block/core/storage/chunk_layer.go | 10 +++------- seaweed-block/docs/design/invariants.md | 2 +- 3 files changed, 8 insertions(+), 14 deletions(-) diff --git a/seaweed-block/core/storage/chunk_cut_payload.go b/seaweed-block/core/storage/chunk_cut_payload.go index ae80610f51..3dde4c29cd 100644 --- a/seaweed-block/core/storage/chunk_cut_payload.go +++ b/seaweed-block/core/storage/chunk_cut_payload.go @@ -70,8 +70,9 @@ func (l *chunkLayerImpl) streamCutPayloads(ctx context.Context, batch []uint64, } } l.rememberPayload(c, head.Gen, staging) - if !staging { - l.markEqualNow(c, head) + l.markEqualNow(c, head) + if hook := l.testAfterCompareHook; hook != nil { + hook(c.idx) } c.data = nil out[i] = c @@ -84,7 +85,7 @@ func (l *chunkLayerImpl) streamCutPayloads(ctx context.Context, batch []uint64, } // markEqualNow records a captured chunk that compared equal to HEAD as a -// clean mark as soon as it is compared, at the version the barrier captured +// clean mark as soon as it is compared, at the version its read captured // and only while the chunk still has it, so a cut that runs out of time // keeps every chunk it finished comparing and the next request continues // from there (the same mark the cut records for all of them after the @@ -98,9 +99,6 @@ func (l *chunkLayerImpl) markEqualNow(c capturedChunk, head chunkHead) { } l.stMu.Unlock() } - if hook := l.testAfterCompareHook; hook != nil { - hook(c.idx) - } } func (l *chunkLayerImpl) stagePayloadRound(ctx context.Context, batch []uint64, versions map[uint64]uint64, head chunkHead, st *chunkCutStats) (map[uint64]stagedChunk, error) { diff --git a/seaweed-block/core/storage/chunk_layer.go b/seaweed-block/core/storage/chunk_layer.go index bb45602b51..6775adfb43 100644 --- a/seaweed-block/core/storage/chunk_layer.go +++ b/seaweed-block/core/storage/chunk_layer.go @@ -788,14 +788,10 @@ func (l *chunkLayerImpl) ObserveRemoteError(err error) error { return l.latchIde // 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} - } + if v, ok := versions[c.idx]; ok { + c.version = v + l.markEqualNow(c, head) } } } diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 4b69401770..dead06708a 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`, `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-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. An interrupted or refused 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`, `TestInterruptedStagingKeepsEqualWork` (`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 | From 7003168a8057d6c8b987ea5491417331e5e48678 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 29 Nov 2026 17:46:04 -0800 Subject: [PATCH 6/6] fix: preserve staged candidate counts at the capture barrier --- .../storage/chunk_copy_error_equal_test.go | 29 +++++++++++++++---- seaweed-block/core/storage/chunk_layer.go | 3 +- 2 files changed, 25 insertions(+), 7 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 6e16b230e6..8c3668c888 100644 --- a/seaweed-block/core/storage/chunk_copy_error_equal_test.go +++ b/seaweed-block/core/storage/chunk_copy_error_equal_test.go @@ -91,13 +91,11 @@ func TestCopyErrorKeepsCapturedEqualMarks(t *testing.T) { if err != nil { t.Fatal(err) } - wantCompared, wantCandidates := int64(2), 0 + wantCompared := int64(2) if mode == "write_after_capture" { wantCompared++ } - if want == 5 { - wantCandidates = 1 - } + wantCandidates := int(wantCompared) if result.Stats.CandidateChunks != wantCandidates || compared.Load() != wantCompared || repeated.Load() != 0 { t.Fatalf("retry candidates=%d compared=%d repeated=%d; want %d,%d,0", result.Stats.CandidateChunks, compared.Load(), repeated.Load(), wantCandidates, wantCompared) } @@ -174,8 +172,8 @@ func TestInterruptedStagingKeepsEqualWork(t *testing.T) { if err != nil { t.Fatal(err) } - if result.Stats.CandidateChunks != 1 || retryReads.Load() != int64(8-want) || repeated.Load() != 0 { - t.Fatalf("retry candidates=%d reads=%d repeated=%d, want 1,%d,0", result.Stats.CandidateChunks, retryReads.Load(), repeated.Load(), 8-want) + if result.Stats.CandidateChunks != 8-want || retryReads.Load() != int64(8-want) || repeated.Load() != 0 { + t.Fatalf("retry candidates=%d reads=%d repeated=%d, want %d,%d,0", result.Stats.CandidateChunks, retryReads.Load(), repeated.Load(), 8-want, 8-want) } if !bytes.Equal(blockOf(f.imageOf(t, result.Head), uint32(written*ctChunkBlocks)), makeBlock(ctBlockSize, 0xEC)) { t.Fatal("retry lost the write after the staging read") @@ -183,3 +181,22 @@ func TestInterruptedStagingKeepsEqualWork(t *testing.T) { }) } } + +func TestStagingEqualChunksStillCountAsCandidates(t *testing.T) { + _, l, _ := unknownFilledVolume(t) + l.cfg.UploadConcurrency = 1 + l.cfg.COWSpillFree = func() (int64, error) { return 2 * (cowSpillFreeReserve + ctChunkBytes), nil } + var reads atomic.Int64 + l.testAfterStageReadHook = func(uint64) { reads.Add(1) } + result, err := l.Cut(ctTimeout(t)) + if err != nil { + t.Fatal(err) + } + const total = ctNumBlocks / ctChunkBlocks + if reads.Load() != total || result.Stats.StagedChunks != total { + t.Fatalf("fixture reads=%d staged=%d, want %d", reads.Load(), result.Stats.StagedChunks, total) + } + if result.Stats.CandidateChunks != total { + t.Fatalf("staging compared %d equal chunks, CandidateChunks=%d, want %d", total, result.Stats.CandidateChunks, total) + } +} diff --git a/seaweed-block/core/storage/chunk_layer.go b/seaweed-block/core/storage/chunk_layer.go index 6775adfb43..63a9cdacea 100644 --- a/seaweed-block/core/storage/chunk_layer.go +++ b/seaweed-block/core/storage/chunk_layer.go @@ -1070,7 +1070,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch return chunkCutResult{}, fmt.Errorf("%w: %w: cut LSN %d, HEAD remote_lsn %d", errChunkCaptureRefused, errChunkLSNBehind, h, baseHead.RemoteLSN) } - st.CandidateChunks = len(candidates) + st.CandidateChunks = max(st.CandidateChunks, len(candidates)) var copyErr error copyStart := time.Now() bytesBeforeCopy := st.UploadedBytes @@ -1790,6 +1790,7 @@ func (l *chunkLayerImpl) stage(ctx context.Context, st *chunkCutStats, spillCap head := copyHead(l.head) l.stMu.Unlock() st.StageRounds++ + st.CandidateChunks = max(st.CandidateChunks, len(batch)) roundChunks, err := l.stagePayloadRound(ctx, batch, vers, head, st) if err != nil { return nil, err