diff --git a/seaweed-block/core/storage/wal_io_v3.go b/seaweed-block/core/storage/wal_io_v3.go index 59a05ffd2c..f89e568695 100644 --- a/seaweed-block/core/storage/wal_io_v3.go +++ b/seaweed-block/core/storage/wal_io_v3.go @@ -62,7 +62,11 @@ func newWALWriterV3(fd *os.File, pub *descriptorPublisherV3) (*walWriterV3, erro return &walWriterV3{pub: pub, nonce: d.Nonce, head: d.RetainedHead, highestLSN: max(d.CheckpointLSN, d.BaseLSN), writeAt: fd.WriteAt}, nil } -func (w *walWriterV3) append(e walEntryV3, durableLSN uint64) (uint64, error) { +// budget (nil = none) is the guest command's budget: checked after the +// descriptor snapshot, the writer lock wait and the encoding, before the first +// physical write, so an expired command starts no new payload I/O (#252). It +// never cancels a write already started. +func (w *walWriterV3) append(e walEntryV3, durableLSN uint64, budget func() error) (uint64, error) { // Descriptor snapshot precedes the writer lock. A concurrent floor advance // makes this snapshot conservative; reset must quiesce/recreate the writer. d, floor, ok := w.pub.walSnapshotV3() @@ -148,6 +152,11 @@ func (w *walWriterV3) append(e walEntryV3, durableLSN uint64) (uint64, error) { } return nil } + if budget != nil { + if err := budget(); err != nil { + return 0, err + } + } if len(pad) > 0 { if err := write(pad, w.head); err != nil { return 0, err diff --git a/seaweed-block/core/storage/wal_io_v3_test.go b/seaweed-block/core/storage/wal_io_v3_test.go index b113a13bf5..1190ff70a1 100644 --- a/seaweed-block/core/storage/wal_io_v3_test.go +++ b/seaweed-block/core/storage/wal_io_v3_test.go @@ -77,7 +77,7 @@ func TestWALIOV3_RealWriterReopenScan(t *testing.T) { // Caller binding fields are overwritten, not trusted. e.Nonce = [16]byte{0xFF} e.LogicalStart = 999 - if _, err := w.append(e, i-1); err != nil { + if _, err := w.append(e, i-1, nil); err != nil { t.Fatal(err) } } @@ -116,7 +116,7 @@ func TestWALIOV3_WrapPaddingAndSlack(t *testing.T) { start := uint64(size) - remaining f, p, w := newWALIOTestV3(t, start, start) d := p.current() - if _, err := w.append(walEntryV3{LSN: 1, Type: walEntryWrite, LBA: 1, Length: d.BlockSize, Data: make([]byte, d.BlockSize)}, 0); err != nil { + if _, err := w.append(walEntryV3{LSN: 1, Type: walEntryWrite, LBA: 1, Length: d.BlockSize, Data: make([]byte, d.BlockSize)}, 0, nil); err != nil { t.Fatal(err) } if err := f.Sync(); err != nil { @@ -187,7 +187,7 @@ func TestWALIOV3_InstalledScanBeginsAtMaxTail(t *testing.T) { d.CheckpointLSN = 5 d.W = 5 d.MapCoveredCheckpoint = 5 - if _, err := w.append(walEntryV3{LSN: 6, Type: walEntryBarrier}, 5); err != nil { + if _, err := w.append(walEntryV3{LSN: 6, Type: walEntryBarrier}, 5, nil); err != nil { t.Fatal(err) } r, err := scanWALV3(f, d) @@ -207,20 +207,20 @@ func TestWALIOV3_ValidatedFrontierIntervals(t *testing.T) { d.BaseState = BaseInstalling d.BaseInstallID = [16]byte{1} d.BaseLSN = 100 - if _, err := w.append(walEntryV3{LSN: 102, Type: walEntryBarrier}, 100); err != nil { + if _, err := w.append(walEntryV3{LSN: 102, Type: walEntryBarrier}, 100, nil); err != nil { t.Fatal(err) } before := w.logicalHeadV3() - if _, err := w.append(walEntryV3{LSN: 101, Type: walEntryBarrier}, 100); !errors.Is(err, ErrWALLSNOrder) { + if _, err := w.append(walEntryV3{LSN: 101, Type: walEntryBarrier}, 100, nil); !errors.Is(err, ErrWALLSNOrder) { t.Fatalf("non-monotone101=%v", err) } if w.logicalHeadV3() != before { t.Fatal("refused101 advanced cursor") } - if _, err := w.append(walEntryV3{LSN: 104, Type: walEntryBarrier}, 100); err != nil { + if _, err := w.append(walEntryV3{LSN: 104, Type: walEntryBarrier}, 100, nil); err != nil { t.Fatal(err) } - if _, err := w.append(walEntryV3{LSN: 103, Type: walEntryBarrier}, 100); !errors.Is(err, ErrWALLSNOrder) { + if _, err := w.append(walEntryV3{LSN: 103, Type: walEntryBarrier}, 100, nil); !errors.Is(err, ErrWALLSNOrder) { t.Fatalf("late gap fill103=%v", err) } r, err := scanWALV3(f, d) @@ -236,7 +236,7 @@ func TestWALIOV3_FloorAndPwriteFailureRefuse(t *testing.T) { f, p, w := newWALIOTestV3(t, 16*1024, 0) _ = f before := w.logicalHeadV3() - if _, err := w.append(walEntryV3{LSN: 1, Type: walEntryBarrier}, 0); !errors.Is(err, errWALFull) { + if _, err := w.append(walEntryV3{LSN: 1, Type: walEntryBarrier}, 0, nil); !errors.Is(err, errWALFull) { t.Fatalf("full ring error=%v", err) } if w.logicalHeadV3() != before { @@ -245,7 +245,7 @@ func TestWALIOV3_FloorAndPwriteFailureRefuse(t *testing.T) { if _, err := p.publish(nil, nil, func(d *descriptorV3) error { d.RetainedTail = 16 * 1024; return nil }); err != nil { t.Fatal(err) } - if _, err := w.append(walEntryV3{LSN: 1, Type: walEntryBarrier}, 0); !errors.Is(err, errWALFull) { + if _, err := w.append(walEntryV3{LSN: 1, Type: walEntryBarrier}, 0, nil); !errors.Is(err, errWALFull) { t.Fatalf("fallback tail must still pin: %v", err) } if ok, err := p.rolloverIfPinned(); err != nil || !ok { @@ -253,10 +253,10 @@ func TestWALIOV3_FloorAndPwriteFailureRefuse(t *testing.T) { } calls := 0 w.writeAt = func(b []byte, off int64) (int, error) { calls++; return 1, io.ErrShortWrite } - if _, err := w.append(walEntryV3{LSN: 1, Type: walEntryBarrier}, 0); !errors.Is(err, errWALPwrite) { + if _, err := w.append(walEntryV3{LSN: 1, Type: walEntryBarrier}, 0, nil); !errors.Is(err, errWALPwrite) { t.Fatalf("append failure=%v", err) } - if _, err := w.append(walEntryV3{LSN: 1, Type: walEntryBarrier}, 0); !errors.Is(err, errWALPwrite) || calls != 1 { + if _, err := w.append(walEntryV3{LSN: 1, Type: walEntryBarrier}, 0, nil); !errors.Is(err, errWALPwrite) || calls != 1 { t.Fatal("failed append retried physical I/O") } } @@ -270,7 +270,7 @@ func TestWALIOV3_EmbeddedRecordInPayloadIsNotScanned(t *testing.T) { } data := make([]byte, d.BlockSize) copy(data[100:], inner) - if _, err := w.append(walEntryV3{LSN: 1, Type: walEntryWrite, LBA: 4, Length: d.BlockSize, Data: data}, 0); err != nil { + if _, err := w.append(walEntryV3{LSN: 1, Type: walEntryWrite, LBA: 4, Length: d.BlockSize, Data: data}, 0, nil); err != nil { t.Fatal(err) } r, err := scanWALV3(f, d) @@ -288,7 +288,7 @@ func TestWALIOV3_ConcurrentAppendsHaveUniqueCursors(t *testing.T) { done := make(chan error, 40) // Forty callers race the same first LSN: exactly one may consume it. for n := 0; n < 40; n++ { - go func() { _, err := w.append(walEntryV3{LSN: 1, Type: walEntryBarrier}, 0); done <- err }() + go func() { _, err := w.append(walEntryV3{LSN: 1, Type: walEntryBarrier}, 0, nil); done <- err }() } deadline := time.NewTimer(5 * time.Second) defer deadline.Stop() @@ -310,7 +310,7 @@ func TestWALIOV3_ConcurrentAppendsHaveUniqueCursors(t *testing.T) { } // The caller's allocator serializes the subsequent increasing stream. for lsn := uint64(2); lsn <= 40; lsn++ { - if _, err := w.append(walEntryV3{LSN: lsn, Type: walEntryBarrier}, 0); err != nil { + if _, err := w.append(walEntryV3{LSN: lsn, Type: walEntryBarrier}, 0, nil); err != nil { t.Fatal(err) } } @@ -327,7 +327,7 @@ func TestWALIOV3_CounterRefusalBeforePwrite(t *testing.T) { _, _, w := newWALIOTestV3(t, counterMaxV3-30, counterMaxV3-30) calls := 0 w.writeAt = func(b []byte, off int64) (int, error) { calls++; return len(b), nil } - if _, err := w.append(walEntryV3{LSN: 1, Type: walEntryBarrier}, 0); !errors.Is(err, ErrCounterExhausted) || calls != 0 { + if _, err := w.append(walEntryV3{LSN: 1, Type: walEntryBarrier}, 0, nil); !errors.Is(err, ErrCounterExhausted) || calls != 0 { t.Fatalf("counter error=%v writes=%d", err, calls) } } @@ -347,7 +347,7 @@ func TestWALIOV3_LastRepresentableRecordStillRecovers(t *testing.T) { start := uint64(counterMaxV3) - 70 f, p, w := newWALIOTestV3(t, start, start) d := p.current() - if _, err := w.append(walEntryV3{LSN: 1, Type: walEntryBarrier}, 0); err != nil { + if _, err := w.append(walEntryV3{LSN: 1, Type: walEntryBarrier}, 0, nil); err != nil { t.Fatal(err) } r, err := scanWALV3(f, d) @@ -357,14 +357,14 @@ func TestWALIOV3_LastRepresentableRecordStillRecovers(t *testing.T) { if len(r.Records) != 1 || r.Frontier != 1 || r.End != counterMaxV3 { t.Fatalf("last representable scan=%+v", r) } - if _, err := w.append(walEntryV3{LSN: 2, Type: walEntryBarrier}, 0); !errors.Is(err, ErrCounterExhausted) { + if _, err := w.append(walEntryV3{LSN: 2, Type: walEntryBarrier}, 0, nil); !errors.Is(err, ErrCounterExhausted) { t.Fatalf("next append=%v", err) } } func TestWALIOV3_RestoreCursorDoesNotPublishOrResetNonce(t *testing.T) { f, p, w := newWALIOTestV3(t, 0, 0) - if _, err := w.append(walEntryV3{LSN: 1, Type: walEntryBarrier}, 0); err != nil { + if _, err := w.append(walEntryV3{LSN: 1, Type: walEntryBarrier}, 0, nil); err != nil { t.Fatal(err) } r, err := scanWALV3(f, p.current()) @@ -420,7 +420,7 @@ func TestWALIOV3_UncertainPublisherStopsExistingAndNewWriters(t *testing.T) { } writes := 0 w.writeAt = func(b []byte, off int64) (int, error) { writes++; return f.WriteAt(b, off) } - if _, err := w.append(walEntryV3{LSN: 1, Type: walEntryBarrier}, 0); err == nil { + if _, err := w.append(walEntryV3{LSN: 1, Type: walEntryBarrier}, 0, nil); err == nil { t.Fatal("existing writer accepted uncertain publication") } if writes != 0 { diff --git a/seaweed-block/core/storage/wal_lsn_order_v3_test.go b/seaweed-block/core/storage/wal_lsn_order_v3_test.go index fa5dfaf3a1..174a3bb624 100644 --- a/seaweed-block/core/storage/wal_lsn_order_v3_test.go +++ b/seaweed-block/core/storage/wal_lsn_order_v3_test.go @@ -10,7 +10,7 @@ func TestWALLSNOrderV3_RefusesDuplicateAndLower(t *testing.T) { for _, lsn := range []uint64{9, 10} { t.Run(map[uint64]string{9: "lower", 10: "equal"}[lsn], func(t *testing.T) { f, p, w := newWALIOTestV3(t, 0, 0) - if _, e := w.append(walEntryV3{LSN: 10, Type: walEntryBarrier}, 0); e != nil { + if _, e := w.append(walEntryV3{LSN: 10, Type: walEntryBarrier}, 0, nil); e != nil { t.Fatal(e) } before := make([]byte, p.current().WALSize) @@ -18,7 +18,7 @@ func TestWALLSNOrderV3_RefusesDuplicateAndLower(t *testing.T) { t.Fatal(e) } head := w.logicalHeadV3() - if _, e := w.append(walEntryV3{LSN: lsn, Type: walEntryBarrier}, 0); !errors.Is(e, ErrWALLSNOrder) { + if _, e := w.append(walEntryV3{LSN: lsn, Type: walEntryBarrier}, 0, nil); !errors.Is(e, ErrWALLSNOrder) { t.Fatalf("non-increasing LSN %d verdict after10: %v", lsn, e) } after := make([]byte, len(before)) @@ -34,13 +34,13 @@ func TestWALLSNOrderV3_RefusesDuplicateAndLower(t *testing.T) { func TestWALLSNOrderV3_BatchConsumesFullRange(t *testing.T) { _, p, w := newWALIOTestV3(t, 0, 0) bs := p.current().BlockSize - if _, e := w.append(walEntryV3{LSN: 10, BatchCount: 2, Type: walEntryWriteBatch, Length: 2 * bs, Data: make([]byte, 2*bs)}, 0); e != nil { + if _, e := w.append(walEntryV3{LSN: 10, BatchCount: 2, Type: walEntryWriteBatch, Length: 2 * bs, Data: make([]byte, 2*bs)}, 0, nil); e != nil { t.Fatal(e) } - if _, e := w.append(walEntryV3{LSN: 11, Type: walEntryBarrier}, 0); !errors.Is(e, ErrWALLSNOrder) { + if _, e := w.append(walEntryV3{LSN: 11, Type: walEntryBarrier}, 0, nil); !errors.Is(e, ErrWALLSNOrder) { t.Fatalf("overlap with batch last LSN: %v", e) } - if _, e := w.append(walEntryV3{LSN: 12, Type: walEntryBarrier}, 0); e != nil { + if _, e := w.append(walEntryV3{LSN: 12, Type: walEntryBarrier}, 0, nil); e != nil { t.Fatal(e) } } @@ -56,7 +56,7 @@ func TestWALLSNOrderV3_RestoreUsesKeptNotDroppedFrontier(t *testing.T) { t.Fatal(e) } for _, lsn := range []uint64{101, 104} { - if _, e = w.append(walEntryV3{LSN: lsn, Type: walEntryBarrier}, 100); e != nil { + if _, e = w.append(walEntryV3{LSN: lsn, Type: walEntryBarrier}, 100, nil); e != nil { t.Fatal(e) } } @@ -80,10 +80,10 @@ func TestWALLSNOrderV3_RestoreUsesKeptNotDroppedFrontier(t *testing.T) { if e = recovered.restoreScanV3(r); e != nil { t.Fatal(e) } - if _, e = recovered.append(walEntryV3{LSN: 101, Type: walEntryBarrier}, 100); !errors.Is(e, ErrWALLSNOrder) { + if _, e = recovered.append(walEntryV3{LSN: 101, Type: walEntryBarrier}, 100, nil); !errors.Is(e, ErrWALLSNOrder) { t.Fatalf("restored kept frontier duplicate: %v", e) } - if _, e = recovered.append(walEntryV3{LSN: 102, Type: walEntryBarrier}, 100); e != nil { + if _, e = recovered.append(walEntryV3{LSN: 102, Type: walEntryBarrier}, 100, nil); e != nil { t.Fatalf("dropped104 pinned next102: %v", e) } } @@ -99,10 +99,10 @@ func TestWALLSNOrderV3_DescriptorFloorIsAlreadyConsumed(t *testing.T) { if e != nil { t.Fatal(e) } - if _, e = w.append(walEntryV3{LSN: 100, Type: walEntryBarrier}, 100); !errors.Is(e, ErrWALLSNOrder) { + if _, e = w.append(walEntryV3{LSN: 100, Type: walEntryBarrier}, 100, nil); !errors.Is(e, ErrWALLSNOrder) { t.Fatalf("descriptor floor100 not consumed: %v", e) } - if _, e = w.append(walEntryV3{LSN: 101, Type: walEntryBarrier}, 100); e != nil { + if _, e = w.append(walEntryV3{LSN: 101, Type: walEntryBarrier}, 100, nil); e != nil { t.Fatal(e) } } diff --git a/seaweed-block/core/storage/walstore_v3.go b/seaweed-block/core/storage/walstore_v3.go index 84b2312cab..a243862c41 100644 --- a/seaweed-block/core/storage/walstore_v3.go +++ b/seaweed-block/core/storage/walstore_v3.go @@ -673,7 +673,7 @@ func (s *WALStore) appendWriteV3(lba uint32, data []byte, lsn uint64, budget fun if err := s.v3BudgetAfterRollover(budget); err != nil { return 0, err } - phys, err := s.v3.w.append(e, s.v3.wack.Load()) + phys, err := s.v3.w.append(e, s.v3.wack.Load(), budget) if err != nil { if errors.Is(err, errWALPwrite) { s.latchV3(err) @@ -731,7 +731,7 @@ func (s *WALStore) writeBatchV3Locked(startLBA uint32, blocks [][]byte, firstLSN if err := s.v3BudgetAfterRollover(budget); err != nil { return nil, err } - phys, err := s.v3.w.append(e, s.v3.wack.Load()) + phys, err := s.v3.w.append(e, s.v3.wack.Load(), budget) s.instr.appendLatency.Observe(time.Since(start)) s.walMutation.Add(1) if err != nil { diff --git a/seaweed-block/core/storage/write_budget_rollover_controls_test.go b/seaweed-block/core/storage/write_budget_rollover_controls_test.go new file mode 100644 index 0000000000..19e56c13a7 --- /dev/null +++ b/seaweed-block/core/storage/write_budget_rollover_controls_test.go @@ -0,0 +1,157 @@ +package storage + +import ( + "context" + "errors" + "fmt" + "sync" + "testing" + "time" +) + +// A completed metadata rollover is retained, but it does not authorize new +// payload I/O after the command's original admission deadline. +func TestWALStoreV3WriteBudgetRechecksAfterRollover(t *testing.T) { + for _, batch := range []bool{false, true} { + for _, outcome := range []string{"expired", "healthy", "fault"} { + t.Run(fmt.Sprintf("batch=%t/%s", batch, outcome), func(t *testing.T) { + s, _ := newMappedCheckpointStoreV3(t) + s.SetRecoveryRetentionLSNs(2) + writeSynced(t, s, 0, 1) + writeSynced(t, s, 1, 2) + if err := s.flusher.flushOnce(); err != nil { + t.Fatal(err) + } + d := s.v3.pub.current() + s.SetRecoveryRetentionLSNs(1) + tail := s.v3.w.reclaimThroughV3(d.CheckpointLSN - 1) + if _, err := s.v3.pub.publish(nil, nil, func(n *descriptorV3) error { + n.RetainedTail = tail + n.RetainedHead = max(n.RetainedHead, tail) + return nil + }); err != nil { + t.Fatal(err) + } + if floor, ok := s.v3.pub.reuseFloor(); !ok || floor >= tail { + t.Fatal("no pinned fallback") + } + wait := 100 * time.Millisecond + if outcome == "healthy" { + wait = 5 * time.Second + } + ctx, cancel := context.WithTimeout(context.Background(), wait) + defer cancel() + boom := errors.New("rollover slot fault") + writeSlot := s.v3.pub.io.writeSlot + calls := 0 + s.v3.pub.io.writeSlot = func(off int64, b []byte) error { + calls++ + if outcome != "healthy" { + <-ctx.Done() + } + if outcome == "fault" { + return boom + } + return writeSlot(off, b) + } + defer func() { s.v3.pub.io.writeSlot = writeSlot }() + head, next, dirty := s.v3.w.logicalHeadV3(), s.NextLSN(), s.dm.len() + gen := s.v3.pub.current().SlotGen + var err error + if batch { + _, err = s.WriteBatchContext(ctx, 2, [][]byte{blk(3), blk(4)}) + } else { + _, err = s.WriteContext(ctx, 2, blk(3)) + } + if calls != 1 { + t.Fatalf("rollover calls=%d err=%v", calls, err) + } + if outcome == "healthy" { + if err != nil || s.NextLSN() <= next { + t.Fatalf("healthy write: %v", err) + } + return + } + if s.NextLSN() != next || s.v3.w.logicalHeadV3() != head || s.dm.len() != dirty { + t.Fatal("refused command started payload I/O") + } + if outcome == "fault" { + if !errors.Is(err, boom) || s.stickyIOFault() == nil { + t.Fatalf("terminal fault masked: %v", err) + } + return + } + if !errors.Is(err, ErrWALPressureTimeout) { + t.Fatalf("expired command: %v", err) + } + if s.v3.pub.current().SlotGen <= gen { + t.Fatal("completed rollover was rolled back") + } + if floor, ok := s.v3.pub.reuseFloor(); !ok || floor != tail { + t.Fatalf("completed rollover not retained: %d %v", floor, ok) + } + }) + } + } +} + +type budgetCaptureWaitContext struct { + context.Context + parked chan struct{} + once sync.Once +} + +func (c *budgetCaptureWaitContext) Done() <-chan struct{} { + c.once.Do(func() { close(c.parked) }) + return c.Context.Done() +} +func TestWALStoreV3LocalBudgetIncludesWitnessedCaptureWait(t *testing.T) { + for _, batch := range []bool{false, true} { + t.Run(fmt.Sprint(batch), func(t *testing.T) { + s, _ := newMappedCheckpointStoreV3(t) + s.admissionTimeout = 40 * time.Millisecond + ctx := &budgetCaptureWaitContext{Context: context.Background(), parked: make(chan struct{})} + s.captureMu.Lock() + locked := true + done := make(chan error, 1) + defer func() { + if locked { + s.captureMu.Unlock() + } + select { + case <-done: + case <-time.After(time.Second): + t.Error("writer failed to join after release") + } + }() + go func() { + var err error + if batch { + _, err = s.WriteBatchContext(ctx, 0, [][]byte{blk(1), blk(2)}) + } else { + _, err = s.WriteContext(ctx, 0, blk(1)) + } + done <- err + }() + select { + case <-ctx.parked: + case <-time.After(time.Second): + t.Fatal("capture waiter was not witnessed") + } + select { + case err := <-done: + done <- err + if !errors.Is(err, ErrWALPressureTimeout) { + t.Fatal(err) + } + case <-time.After(time.Second): + t.Fatal("local budget restarted behind capture lock") + } + s.captureMu.Unlock() + locked = false + if s.NextLSN() != 1 || s.dm.len() != 0 { + t.Fatal("expired local waiter mutated") + } + }) + } +} diff --git a/seaweed-block/core/storage/write_command_budget_p1_test.go b/seaweed-block/core/storage/write_command_budget_p1_test.go index 3236bb0c71..e670a2652d 100644 --- a/seaweed-block/core/storage/write_command_budget_p1_test.go +++ b/seaweed-block/core/storage/write_command_budget_p1_test.go @@ -62,7 +62,16 @@ func TestWALStoreV3WriteKeepsWriterPreferenceUnderReaders(t *testing.T) { s, _ := newMappedCheckpointStoreV3(t) var stop atomic.Bool var wg sync.WaitGroup - t.Cleanup(func() { stop.Store(true); wg.Wait() }) + t.Cleanup(func() { + stop.Store(true) + joined := make(chan struct{}) + go func() { wg.Wait(); close(joined) }() + select { + case <-joined: + case <-time.After(5 * time.Second): + t.Error("reader goroutines did not finish") + } + }) // steady overlapping readers of the store lock (each holds it ~2 ms, // staggered): some reader is almost always inside, as under heavy // read traffic. A blocking Lock registers as a waiting writer and @@ -120,7 +129,14 @@ func TestWALStoreV3ExpiredWriterRefusesAfterShortLockWait(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 30*time.Millisecond) defer cancel() done := make(chan error, 1) - t.Cleanup(func() { release(); <-done }) + t.Cleanup(func() { + release() + select { + case <-done: + case <-time.After(5 * time.Second): + t.Error("writer did not finish after the release") + } + }) go func() { _, err := s.WriteContext(ctx, 0, blk(1)); done <- err }() <-ctx.Done() // the command expires while the short lock is held release() @@ -135,3 +151,76 @@ func TestWALStoreV3ExpiredWriterRefusesAfterShortLockWait(t *testing.T) { }) } } + +// #252 residual P1: the budget is checked inside the WAL writer, after its +// descriptor snapshot and writer lock wait. A real concurrent Sync holds the +// descriptor lock (its slot write, without the store lock) until the command +// has expired; the append waiting behind it must then refuse before any +// payload write, and the Sync completes normally. +func TestWALStoreV3WriteBudgetRefusesAfterDescriptorWaitBehindSync(t *testing.T) { + for _, batch := range []bool{false, true} { + name := map[bool]string{false: "single", true: "batch"}[batch] + t.Run(name, func(t *testing.T) { + s, _ := newMappedCheckpointStoreV3(t) + if _, err := s.Write(7, blk(7)); err != nil { // unsynced: the Sync has a slot to publish + t.Fatal(err) + } + ctx, cancel := context.WithTimeout(context.Background(), 400*time.Millisecond) + defer cancel() + entered := make(chan struct{}) + var enterOnce sync.Once + s.v3.testBeforeSlotWrite = func() error { + enterOnce.Do(func() { close(entered) }) + <-ctx.Done() // the command expires while the Sync holds the descriptor lock + return nil + } + // The Sync runs first and parks at its leader point (past its store + // lock phase); the write's post-rollover hook releases it, so it takes + // the descriptor lock for its slot write after the write's rollover + // snapshot and before the write's own append snapshot. + atLeader, proceed := make(chan struct{}), make(chan struct{}) + var leaderOnce, proceedOnce sync.Once + release := func() { proceedOnce.Do(func() { close(proceed) }) } + s.v3.testLeaderWaiting = func() { + leaderOnce.Do(func() { close(atLeader); <-proceed }) + } + syncDone := make(chan error, 1) + t.Cleanup(func() { + release() + cancel() + select { + case <-syncDone: + case <-time.After(5 * time.Second): + t.Error("the concurrent Sync did not finish") + } + }) + go func() { _, err := s.Sync(); syncDone <- err }() + <-atLeader + s.v3.testAfterRollover = func() { + release() + <-entered + } + head := s.v3.w.head + var err error + if batch { + _, err = s.WriteBatchContext(ctx, 0, [][]byte{blk(1), blk(2)}) + } else { + _, err = s.WriteContext(ctx, 0, blk(1)) + } + if !errors.Is(err, ErrWALPressureTimeout) { + t.Fatalf("expired command after the descriptor wait: %v", err) + } + if s.v3.w.head != head { + t.Fatalf("expired command started payload WAL I/O after the descriptor wait: head %d -> %d", head, s.v3.w.head) + } + if err := <-syncDone; err != nil { + t.Fatalf("the concurrent Sync: %v", err) + } + syncDone <- nil + s.v3.testAfterRollover, s.v3.testBeforeSlotWrite, s.v3.testLeaderWaiting = nil, nil, nil + if _, err := s.WriteContext(context.Background(), 0, blk(3)); err != nil { + t.Fatalf("a fresh write after the refusal: %v", err) + } + }) + } +} diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 0d394ff0f2..9ee002abfa 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -332,7 +332,7 @@ The "Machine / transition" column refers to Part A. Notes under a table record w | `INV-WAL-V3-DESCRIPTOR-001` | A v3 descriptor slot is used only if it is valid. It needs a matching CRC32C (Castagnoli), every reserved byte zero, an accepted impl, a nonzero slotGen at most 2^64-2 and a nonzero nonce. Its geometry must be consistent with checked arithmetic, its BASE fields must follow their per-state rules, and CheckpointLSN ≤ mapCoveredCheckpoint ≤ W must hold. Of the two slots, the valid selectable one with the higher slotGen wins. A prepared migration slot is never selected. Equal generations with different bytes, or slots that disagree on identity or geometry, are refused. | M1 Opened (v3 descriptor selection) | `core/storage/superblock_v3.go` `decodeSlotV3`, `selectSlotV3`, `nextSlotGenV3` | `TestSlotV3VectorsDecodeAsExpected`, `TestSlotV3Selection`, `TestSlotV3CounterExhaustion`, `TestSlotV3InstalledMayHaveCursorBelowTail` (`core/storage/superblock_v3_test.go`) | — | STUB | | `INV-WAL-V3-RECORD-001` | An impl-3 record codec uses the fixed 62-byte prefix and 70-byte overhead, CRC32C and an explicit EntrySize. It refuses unknown types/flags, a zero nonce, invalid per-type geometry, overflowing count/LSN/cursor or LBA spans, nonzero padding, bad CRC/footer and truncation before allocating a payload. Codec success alone is not nonce/cursor/lap replay admission. | M1 v3 record framing | `core/storage/wal_entry_v3.go` `payloadSizeV3`, `encodeWALEntryV3`, `decodeWALEntryV3` | `TestWALEntryV3_CanonicalBarrierBytes`, `TestWALEntryV3_TypeFootprints`, `TestWALEntryV3_RefusesInvalidEncode`, `TestWALEntryV3_RefusesMalformedWire`, `FuzzWALEntryV3_DecodeNeverPanics` | `WALRecovery` abstract record validity; physical byte rules are code-test obligations | STUB | | `INV-WAL-V3-LSN-ORDER-001` | A v3 writer accepts only a first LSN above its highest consumed LSN; a batch consumes its whole validated range. Equal/lower requests return ErrWALLSNOrder before any pwrite or cursor change. Constructor coverage and a recovered kept frontier count as consumed; a fenced-away suffix does not. | M1 v3 append | `core/storage/wal_io_v3.go` `append`, `newWALWriterV3`, `restoreScanV3` | `TestWALLSNOrderV3_RefusesDuplicateAndLower`, `TestWALLSNOrderV3_BatchConsumesFullRange`, `TestWALLSNOrderV3_RestoreUsesKeptNotDroppedFrontier`, `TestWALLSNOrderV3_DescriptorFloorIsAlreadyConsumed`, `TestWALIOV3_ValidatedFrontierIntervals`, `TestWALIOV3_ConcurrentAppendsHaveUniqueCursors` | Physical LSN-strict prefix is a contract constraint; r16 model correspondence is pending | STUB | -| `INV-WAL-V3-ADMISSION-001` | Native v3 WAL pressure uses its physical writer head minus the both-slot reuse floor, never the inactive legacy writer. Existing soft/hard waits wake the flusher without holding store, descriptor or writer locks. A terminal I/O fault latched during a pressure or semaphore wait ends that wait with the original typed cause; timeout must not mask an already observed fault. One earliest command deadline spans adapter batches and bounded store admission locks/snapshots; expiry before append preserves the WAL/nextLSN/dirty state. Issued WAL I/O retains its existing lifecycle ownership. Pure caller expiry stays retryable through required-observer classification and NVMe; a provided physical cause remains terminal. No wait grants reuse or acknowledges writes. | M1 Serving (write admission) | `walstore.go` `walUsedFraction`, `openInitializedInternal`; `wal_admission.go` `Acquire`; `write_command_budget.go`; `StorageBackend.Write`; NVMe `handleWrite` | `TestWALStoreV3WriteBudgetIncludesPostAdmissionWait`, `TestWALStoreV3WriteContextDeadlineIncludesCaptureWait`, `TestStorageBackendWriteKeepsOneDeadlineAcrossBatches`, `TestSessionWriteBudgetIncludesDispatchQueue`, `TestWALStoreV3WriteBudgetBoundsAppendLockWait`, `TestWALStoreV3WriteBudgetBoundsPressureLocks`, `TestWALStoreV3WritePressureSampleMatchesOccupancy`, `TestStorageBackendExpiredWriteDoesNotAppend`, `TestStorageBackendRequiredObserverDeadlineStaysRetryable`; `TestWALStoreV3AdmissionUsesNativeOccupancy`; `TestWALStoreV3AdmissionReturnsFaultLatchedDuringPressureWait` (Write and WriteBatch); `TestWALStoreChunkV3_SequentialBurstFlush` (public provider and NVMe handler, default 64 MiB WAL, 320 MiB literal readback); `TestWALStoreChunkV3_BurstPatternBindsFullLBA` (32/64/256 MiB alias controls) | Existing reuse/durability rules unchanged; pressure/liveness is not a new model claim | ACTIVE | +| `INV-WAL-V3-ADMISSION-001` | Native v3 WAL pressure uses its physical writer head minus the both-slot reuse floor, never the inactive legacy writer. Existing soft/hard waits wake the flusher without holding store, descriptor or writer locks. A terminal I/O fault latched during a pressure or semaphore wait ends that wait with the original typed cause; timeout must not mask an already observed fault. One earliest command deadline spans adapter batches and the long store admission waits (capture, lifecycle); short locks (store, descriptor, WAL writer) are taken blocking and keep RWMutex writer preference, with the deadline checked once held. The deadline is checked again after a checkpoint rollover and inside the WAL writer after its descriptor snapshot, lock wait and encoding, before the first payload write: an expired command starts no new payload WAL I/O, and expiry before append preserves the WAL/nextLSN/dirty state. A batch that returns a committed prefix with a storage error keeps that error in the classified error set. Issued WAL I/O retains its existing lifecycle ownership. Pure caller expiry stays retryable through required-observer classification and NVMe; a provided physical cause remains terminal. No wait grants reuse or acknowledges writes. | M1 Serving (write admission) | `walstore.go` `walUsedFraction`, `openInitializedInternal`; `wal_admission.go` `Acquire`; `write_command_budget.go`; `StorageBackend.Write`; NVMe `handleWrite` | `TestWALStoreV3WriteBudgetIncludesPostAdmissionWait`, `TestWALStoreV3WriteContextDeadlineIncludesCaptureWait`, `TestStorageBackendWriteKeepsOneDeadlineAcrossBatches`, `TestSessionWriteBudgetIncludesDispatchQueue`, `TestWALStoreV3ExpiredWriterRefusesAfterShortLockWait`, `TestWALStoreV3WriteKeepsWriterPreferenceUnderReaders`, `TestWALStoreV3WriteBudgetRefusesNewPayloadAfterRollover`, `TestWALStoreV3WriteBudgetRechecksAfterRollover`, `TestWALStoreV3WriteBudgetRefusesAfterDescriptorWaitBehindSync`, `TestStorageBackendPartialBatchPhysicalFaultSurvivesObserverDeadline`, `TestWALStoreV3WritePressureSampleMatchesOccupancy`, `TestStorageBackendExpiredWriteDoesNotAppend`, `TestStorageBackendRequiredObserverDeadlineStaysRetryable`; `TestWALStoreV3AdmissionUsesNativeOccupancy`; `TestWALStoreV3AdmissionReturnsFaultLatchedDuringPressureWait` (Write and WriteBatch); `TestWALStoreChunkV3_SequentialBurstFlush` (public provider and NVMe handler, default 64 MiB WAL, 320 MiB literal readback); `TestWALStoreChunkV3_BurstPatternBindsFullLBA` (32/64/256 MiB alias controls) | Existing reuse/durability rules unchanged; pressure/liveness is not a new model claim | ACTIVE | | `INV-WAL-V3-RECLAIM-001` | A mapped v3 checkpoint releases only complete validated record ends covered by the checkpoint and outside the retention window; an installing BASE retains its install suffix. Physical recovery rebuilds the volatile boundary index only from the trusted kept scan, without restoring a disconnect cursor. Tail/head/map/checkpoint/W publish together, followed by metadata-only rollover; both slot tails still pin reuse. Failure grants no reuse and retains exact dirty retry identity. Checkpoint publication excludes writer admission through both-slot rollover and dirty-reference retirement. Idle, unchanged-checkpoint and admission settle pending rollover; catch-up revalidates tail/checkpoint before delivering its buffered scan. | M1 checkpoint / existing two-slot retirement | `wal_io_v3.go` `reclaimThroughV3`, `rememberReclaimScanV3`; `walstore_map_checkpoint_v3.go` `publishCheckpointV3`; `descriptor_v3.go` `rolloverIfPinned` | `TestWALStoreV3CheckpointReclaimsAcrossRingLaps`, `TestWALStoreV3ReclaimKeepsPartialBatchAndRetention`, `TestWALStoreV3ReclaimRebuildsIndexAfterPhysicalRecovery`, `TestWALStoreV3ReclaimAfterInstallingPhysicalReopen`, `TestWALStoreV3ReclaimSecondSlotFailureKeepsOldPin`, `TestWALStoreV3ReclaimRetiresReferencesBeforeReuse`, `TestWALStoreV3ReclaimRolloverProgressWithoutNewCheckpoint`, tagged `TestCatchUpV3AfterCheckpointRingReuse`, `TestCatchUpV3ScanOverlappingCheckpointReuseIsRecycled` | Existing dual-slot retirement and nonce/cursor contract; concrete index/recovery/caller wiring is a code-test obligation | STUB | | `INV-WAL-V3-OWNER-001` | v3 read/write open, offline readonly open and migrate-v3 acquire the same exclusive nonblocking OS file lock before reading slots or changing bytes. Contention refuses with volume locked; descriptor close releases it, allowing retry. | M1 open admission / offline migration precondition | `core/storage/volume_lock*.go`; `walstore_v3.go`; `walstore_readonly_v3.go`; `cmd/sw-block/migrate.go` | `TestMigrateV3RefusesAnOpenV3Volume`, `TestMigrateV3ExcludesOpenUntilCommitFinishes` (tag `swblock_format_v3_test`), `TestWALStoreV3CreatorKeepsOwnershipThroughPublication`, `TestWALStoreV3OwnerExcludesOpenAndReadOnly` | OS mutual exclusion is a caller obligation, outside the abstract crash model; existing open states unchanged | STUB | | `INV-WAL-V3-CATCHUP-001` | A dark v3 catch-up source refuses while installing, including an empty at-head request. Requests covered by an installed BASE require rebuild (typed WALRecycled); damage in retained WAL remains an integrity failure. Before emitting any entries the scan revalidates recovery generation, nonce, BASE state/ID and install epoch, so begin/complete/retire ABA cannot publish a superseded prefix. | M1 BASE lifecycle / M3 CatchingUp (dark callers) | `core/storage/walstore_recovery.go` `ScanLBAs`, `scanLBAsV3`, `v3CatchUpEntries` | `TestCatchUpV3InstallingAtHeadRefuses`, `TestCatchUpV3CompletedBASEUsesRebuild`, `TestCatchUpV3InstallRetireABARefusesOldScan`, `TestCatchUpV3CorruptFirstRecordFails`, `TestCatchUpV3CorruptMiddleRecordFails`, `TestCatchUpV3CompletedBASESuffix` (tag `swblock_format_v3_test`, actual catch-up sender) | Existing BASE and catch-up transitions unchanged; this physical scan/source-lifetime obligation is covered by deterministic caller tests | STUB |