diff --git a/seaweed-block/core/frontend/chunkstore/layout_staging_retry_test.go b/seaweed-block/core/frontend/chunkstore/layout_staging_retry_test.go new file mode 100644 index 0000000000..d56813efd1 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/layout_staging_retry_test.go @@ -0,0 +1,171 @@ +package chunkstore + +import ( + "bytes" + "context" + "errors" + "fmt" + "io" + "log" + "path/filepath" + "strings" + "sync" + "sync/atomic" + "testing" + + "github.com/seaweedfs/seaweed-block/core/storage" +) + +type cutCompareLog struct { + mu sync.Mutex + bytes.Buffer +} + +func (w *cutCompareLog) Write(p []byte) (int, error) { + w.mu.Lock() + defer w.mu.Unlock() + return w.Buffer.Write(p) +} +func (w *cutCompareLog) counts() []int { + w.mu.Lock() + defer w.mu.Unlock() + var counts []int + for _, line := range strings.Split(w.Buffer.String(), "\n") { + if !strings.Contains(line, `volume="r5-combined"`) { + continue + } + _, tail, ok := strings.Cut(line, " candidates=") + if !ok { + continue + } + var count int + if _, err := fmt.Sscanf(tail, "%d", &count); err == nil { + counts = append(counts, count) + } + } + return counts +} + +type timedOutThenRefusedRemote struct { + *LayoutRemote + checks atomic.Int32 + refused atomic.Bool +} + +func (r *timedOutThenRefusedRemote) CheckCommit(ctx context.Context, expected storage.ChunkHeadVersion, next storage.ChunkHead) error { + if r.checks.Add(1) <= 2 { + return context.DeadlineExceeded + } + return r.LayoutRemote.CheckCommit(ctx, expected, next) +} +func (r *timedOutThenRefusedRemote) CASHead(ctx context.Context, expected storage.ChunkHeadVersion, next storage.ChunkHead) (uint64, error) { + if r.refused.CompareAndSwap(false, true) { + return 0, storage.ErrChunkHeadPrecondition + } + return r.LayoutRemote.CASHead(ctx, expected, next) +} + +// Real layout adoption and engine progress compose: two request timeouts, +// then a refused commit, do not repeat the seven equal comparisons. The +// final request stages exactly the one chunk that differs and publishes. +func TestTimedOutRequestsThenRefusedCommitKeepEqualWork(t *testing.T) { + ctx := context.Background() + lh := newLayoutHost(t) + source, sourceLayer, _ := lh.attach("source", true, true) + want := make(map[uint32][]byte) + for lba := uint32(0); lba < lrBlocks; lba++ { + want[lba] = block(byte(lba + 1)) + } + writeSync(t, source, want) + baseline, err := sourceLayer.Cut(ctx) + if err != nil { + t.Fatal(err) + } + if err := sourceLayer.Close(); err != nil { + t.Fatal(err) + } + if err := source.Close(); err != nil { + t.Fatal(err) + } + s, err := storage.CreateWALStoreWithOptions(filepath.Join(lh.dir, "retry"), lrBlocks, 4096, storage.WALStoreOptions{ChunkBlocks: lrChunkBlocks}) + if err != nil { + t.Fatal(err) + } + if _, err := s.Recover(); err != nil { + t.Fatal(err) + } + inner, err := NewLayoutRemote(lh.cat, lh.v, lh.me) + if err != nil { + t.Fatal(err) + } + remote := &timedOutThenRefusedRemote{LayoutRemote: inner} + smallSpill := false + cfg := storage.ChunkLayerConfig{VolumeID: "r5-combined", ChunkBlocks: lrChunkBlocks, Epoch: lh.me.Epoch, Holder: lh.me.Holder, FreshFromHead: true, COWSpillFree: func() (int64, error) { + if smallSpill { + return 2 * ((1 << 30) + lrChunkBlocks*4096), nil + } + return 8 << 30, nil + }} + layer, err := storage.AttachChunkLayer(s, remote, cfg) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = layer.Close(); _ = s.Close() }) + // BASE is installed only after attach; it makes the complete local map + // UNKNOWN so this is a real full comparison, not a clean-fill shortcut. + handle, err := storage.BeginInstall(s, baseline.H+1, [16]byte{0xA7}) + if err != nil { + t.Fatal(err) + } + want[lrChunkBlocks] = block(0xE7) + for lba := uint32(0); lba < lrBlocks; lba++ { + if err := handle.WriteBase(lba, want[lba]); err != nil { + t.Fatal(err) + } + } + if err := handle.MarkBaseComplete(); err != nil { + t.Fatal(err) + } + var comparisons cutCompareLog + previousLog := log.Writer() + log.SetOutput(io.MultiWriter(previousLog, &comparisons)) + defer log.SetOutput(previousLog) + for attempt := 0; attempt < 2; attempt++ { + if _, err := layer.Cut(ctx); !errors.Is(err, context.DeadlineExceeded) { + t.Fatalf("request %d: %v", attempt, err) + } + counts := comparisons.counts() + if len(counts) != attempt+1 { + t.Fatalf("request %d has %d phase records", attempt, len(counts)) + } + if got := counts[attempt]; got != []int{8, 1}[attempt] { + t.Fatalf("request %d compared %d chunks", attempt, got) + } + if outcome, err := inner.AbortOpenSession(ctx); err != nil || (outcome != SessionAborted && (attempt == 0 || outcome != SessionIdle)) { + t.Fatalf("settle request %d: %s %v", attempt, outcome, err) + } + inner.Abort() + } + if _, err := layer.Cut(ctx); !errors.Is(err, storage.ErrChunkHeadPrecondition) { + t.Fatalf("commit refusal: %v", err) + } + counts := comparisons.counts() + if len(counts) != 3 { + t.Fatalf("refusal has %d phase records", len(counts)) + } + if got := counts[2]; got != 1 { + t.Fatalf("refused commit compared %d chunks, want 1", got) + } + smallSpill = true + result, err := layer.Cut(ctx) + if err != nil { + t.Fatal(err) + } + if result.Stats.StagedChunks != 1 || result.Stats.CandidateChunks != 1 { + t.Fatalf("final retry staged %d, compared %d; want 1 and 1", result.Stats.StagedChunks, result.Stats.CandidateChunks) + } + if lh.head().Position != result.H { + t.Fatal("final request did not publish") + } + lh.readBack("reader", want) +} diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index d72117f6a5..4474ea69b9 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`) | 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-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 |