diff --git a/seaweed-block/.github/model-code-trace.tsv b/seaweed-block/.github/model-code-trace.tsv index a32d734bea..e1ab381053 100644 --- a/seaweed-block/.github/model-code-trace.tsv +++ b/seaweed-block/.github/model-code-trace.tsv @@ -126,3 +126,7 @@ core/transport/replica.go ReplicationPeer.Ship core/storage/chunk_coverage.go SlotFence.Publish core/storage/chunk_coverage_map.go MoveWide2.Write core/storage/walstore_v3.go SlotFence2.OpenNew + +core/storage/wal_admission_fast.go WALHold.FastArrive +core/storage/wal_admission_fast.go WALHold.FastReEnter +core/storage/wal_admission_fast.go WALHold.FastResubmit diff --git a/seaweed-block/core/storage/wal_admission_fast.go b/seaweed-block/core/storage/wal_admission_fast.go new file mode 100644 index 0000000000..3fe7b0fcf4 --- /dev/null +++ b/seaweed-block/core/storage/wal_admission_fast.go @@ -0,0 +1,76 @@ +package storage + +import ( + "context" + "math" + "time" +) + +// lockFastWALAppend reserves this call's append capacity without a queue ticket. +// Success returns with s.mu held: no other production append can consume the +// observed room until this call appends or refuses. The queue check is atomic +// with that reservation under queueMu. A waiter arriving later must sample +// capacity under s.mu, after this reservation has finished. +// +// Lock order is s.mu -> descriptor snapshot -> writer snapshot -> queueMu; +// descriptor/writer locks are released before queueMu. queueMu covers no file +// I/O, callback or waiting lock. False returns with every lock released. +func (s *WALStore) lockFastWALAppend(ctx context.Context, deadline time.Time, blocks int) (bool, error) { + a := s.admission + if a == nil || s.v3 == nil { + return false, nil + } + started := time.Now() + s.mu.Lock() + s.instr.recordWriteCommitLockWait(time.Since(started)) + keep := false + defer func() { + if !keep { + s.mu.Unlock() + } + }() + if s.closed { + return false, errVolumeClosed + } + if err := s.writeBudgetError(ctx, deadline); err != nil { + return false, err + } + w := s.v3.w + if w == nil { + return false, nil + } + d, floor, valid := s.v3.pub.walSnapshotV3() + w.mu.Lock() + head, nonce := w.head, w.nonce + w.mu.Unlock() + if !valid || d.WALSize == 0 || d.BlockSize == 0 || nonce != d.Nonce || head < floor || head-floor > d.WALSize { + return false, nil + } + // The normal encoder remains the format/geometry authority. Do not overflow + // its size arithmetic when deciding whether this optional path is available. + if blocks <= 0 || uint64(blocks) > (math.MaxUint32-walEntryHeaderSizeV3)/uint64(d.BlockSize) { + return false, nil + } + size := uint64(walEntryHeaderSizeV3) + uint64(blocks)*uint64(d.BlockSize) + remaining := d.WALSize - head%d.WALSize + gap := uint64(0) + if size > remaining { + gap = remaining + } + free := d.WALSize - (head - floor) + if gap > free || size > free-gap || gap > counterMaxV3-head || size > counterMaxV3-head-gap { + return false, nil + } + a.queueMu.Lock() + if a.first != nil || a.active != nil || len(a.sem) != 0 { + a.queueMu.Unlock() + return false, nil + } + // s.mu is still held: this capacity cannot be consumed by another append. + keep = true + a.queueMu.Unlock() + if float64(head-floor)/float64(d.WALSize) >= a.softMark { + a.notifyFn() + } + return true, nil +} diff --git a/seaweed-block/core/storage/wal_admission_fast_test.go b/seaweed-block/core/storage/wal_admission_fast_test.go new file mode 100644 index 0000000000..0e352d62e9 --- /dev/null +++ b/seaweed-block/core/storage/wal_admission_fast_test.go @@ -0,0 +1,93 @@ +package storage + +import ( + "context" + "testing" + "testing/synctest" + "time" +) + +func TestWALAdmissionFastPathHasNoTicket(t *testing.T) { + for _, batch := range []bool{false, true} { + t.Run(map[bool]string{false: "write", true: "batch"}[batch], func(t *testing.T) { + s := admissionPressureV3(t, 0) + write := s.v3.w.writeAt + calls := 0 + s.v3.w.writeAt = func(p []byte, off int64) (int, error) { + calls++ + a := s.admission + a.queueMu.Lock() + queued := a.first != nil || a.last != nil || a.active != nil || len(a.sem) != 0 + a.queueMu.Unlock() + if queued { + t.Error("healthy append allocated or owns a queue ticket") + } + return write(p, off) + } + if batch { + if _, err := s.WriteBatch(0, [][]byte{blk(1), blk(2)}); err != nil { + t.Fatal(err) + } + } else { + if _, err := s.Write(0, blk(1)); err != nil { + t.Fatal(err) + } + } + if calls != 1 { + t.Fatalf("physical appends=%d", calls) + } + }) + } +} + +func TestWALAdmissionFastPathCannotPassAWaiter(t *testing.T) { + s := admissionPressureV3(t, 0) + synctest.Test(t, func(t *testing.T) { + // A full-WAL waiter may exist just as reclaim frees space. Room alone must + // never authorize a new call to bypass that waiter. + ticket := s.admission.enqueueTicket(nil) + pending := true + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + done := make(chan error, 1) + defer func() { + cancel() + if pending { + s.admission.removeTicket(ticket) + } + synctest.Wait() + }() + go func() { _, err := s.WriteContext(ctx, 0, blk(1)); done <- err }() + synctest.Wait() + select { + case err := <-done: + t.Fatalf("new append passed waiter: %v", err) + default: + } + s.admission.removeTicket(ticket) + pending = false + synctest.Wait() + if err := <-done; err != nil { + t.Fatal(err) + } + }) +} + +func TestWALAdmissionFastReservationKeepsAppendLock(t *testing.T) { + s := admissionPressureV3(t, 0) + // The reservation is the store's append lock, not a detachable semaphore + // token. Observe it at the actual pwrite boundary. + original := s.v3.w.writeAt + s.v3.w.writeAt = func(p []byte, off int64) (int, error) { + if s.mu.TryLock() { + s.mu.Unlock() + t.Error("capacity reservation released before append") + } + return original(p, off) + } + ctx, cancel := WithWALWriteHold(context.Background(), s, time.Now(), 25*time.Second, false) + defer cancel() + if _, err := s.WriteContext(ctx, 0, blk(1)); err != nil { + t.Fatal(err) + } +} diff --git a/seaweed-block/core/storage/wal_admission_fifo_test.go b/seaweed-block/core/storage/wal_admission_fifo_test.go index 65533565ec..2348757f57 100644 --- a/seaweed-block/core/storage/wal_admission_fifo_test.go +++ b/seaweed-block/core/storage/wal_admission_fifo_test.go @@ -107,7 +107,14 @@ func TestWALStoreAdmissionFIFOOrdersRealAppends(t *testing.T) { done[i] = make(chan answer, 1) go func() { n, err := s.Write(uint32(i), blk(byte(i+1))); done[i] <- answer{n, err} }() } + // Force the queued path with a prior admitted append. Healthy calls are + // now allowed the no-ticket path and need not enter this queue. + if err := s.admission.Acquire(time.Minute); err != nil { + t.Fatal(err) + } start(0) + synctest.Wait() + s.admission.Release() <-entered start(1) synctest.Wait() @@ -189,7 +196,9 @@ func TestWALHoldLargeWriteBatchesKeepCommandArrivalUnderPressure(t *testing.T) { } defer s.Close() s.DisableAutoFlushForRecoveryTest() - for i := 0; i < 224; i++ { + // Fill actual space, not just the hard watermark: after the first + // batch fewer than one small record fits, so the younger call must wait. + for i := 0; i < 235; i++ { if _, err := s.Write(uint32(i), blk(byte(i))); err != nil { t.Fatal(err) } diff --git a/seaweed-block/core/storage/walstore.go b/seaweed-block/core/storage/walstore.go index 8ec4c03012..6844a2d0cc 100644 --- a/seaweed-block/core/storage/walstore.go +++ b/seaweed-block/core/storage/walstore.go @@ -162,7 +162,8 @@ type WALStore struct { // failed. Leaf lock: taken last, nothing is acquired under it. fileSyncMu sync.Mutex // testAfterAdmit, when set, runs in Write, WriteBatch and ApplyEntry - // after their entry checks and before the append lock. Tests only. + // after entry/capacity checks. Queued calls have not taken the append + // lock; no-ticket fast calls already own it. Tests only. testAfterAdmit func() // testBeforeFileSync, when set, runs in syncFile just before fileSyncMu // is taken. Tests only. @@ -531,7 +532,11 @@ func (s *WALStore) WriteContext(ctx context.Context, lba uint32, data []byte) (u if err := s.writeBudgetError(ctx, deadline); err != nil { return 0, err } - if s.admission != nil { + fastLocked, err := s.lockFastWALAppend(ctx, deadline, 1) + if err != nil { + return 0, err + } + if !fastLocked && s.admission != nil { wait := s.admissionTimeout if holdFor(ctx, s) != nil { wait = 0 @@ -548,9 +553,11 @@ func (s *WALStore) WriteContext(ctx context.Context, lba uint32, data []byte) (u h() } - commitLockStart := time.Now() - s.mu.Lock() // a short lock: blocking keeps RWMutex writer preference (#252); the budget is checked below - s.instr.recordWriteCommitLockWait(time.Since(commitLockStart)) + if !fastLocked { + commitLockStart := time.Now() + s.mu.Lock() // blocking keeps RWMutex writer preference (#252) + s.instr.recordWriteCommitLockWait(time.Since(commitLockStart)) + } if s.closed { s.mu.Unlock() return 0, errors.New("storage: Write after Close") @@ -569,7 +576,6 @@ func (s *WALStore) WriteContext(ctx context.Context, lba uint32, data []byte) (u appendStart := time.Now() var walRelOff uint64 - var err error walRelOff, err = s.appendWriteV3(lba, data, lsn, func() error { return s.writeBudgetError(ctx, deadline) }) @@ -635,7 +641,11 @@ func (s *WALStore) WriteBatchContext(ctx context.Context, startLBA uint32, block if err := s.writeBudgetError(ctx, deadline); err != nil { return nil, err } - if s.admission != nil { + fastLocked, err := s.lockFastWALAppend(ctx, deadline, len(blocks)) + if err != nil { + return nil, err + } + if !fastLocked && s.admission != nil { wait := s.admissionTimeout if holdFor(ctx, s) != nil { wait = 0 @@ -652,9 +662,11 @@ func (s *WALStore) WriteBatchContext(ctx context.Context, startLBA uint32, block h() } - commitLockStart := time.Now() - s.mu.Lock() // a short lock: blocking keeps RWMutex writer preference (#252); the budget is checked below - s.instr.recordWriteCommitLockWait(time.Since(commitLockStart)) + if !fastLocked { + commitLockStart := time.Now() + s.mu.Lock() // blocking keeps RWMutex writer preference (#252) + s.instr.recordWriteCommitLockWait(time.Since(commitLockStart)) + } if s.closed { s.mu.Unlock() return nil, errors.New("storage: WriteBatch after Close") diff --git a/seaweed-block/core/storage/walstore_v3_test.go b/seaweed-block/core/storage/walstore_v3_test.go index f28637d12e..fe4c7984a1 100644 --- a/seaweed-block/core/storage/walstore_v3_test.go +++ b/seaweed-block/core/storage/walstore_v3_test.go @@ -423,6 +423,10 @@ func TestWALStoreV3SyncRechecksTheFaultAtTheAckBoundary(t *testing.T) { if _, err := s.Write(2, blk(2)); err != nil { t.Fatal(err) } + // This ACK-boundary schedule parks before the append lock. Disable + // admission so it does not reserve that lock via the no-ticket path; + // fast-path reservation and queued ordering have separate controls. + s.admission = nil prev := s.v3.wack.Load() parked, release := make(chan struct{}), make(chan struct{}) rel := sync.OnceFunc(func() { close(release) }) diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index c2dd708ef3..43a8fd9eb2 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -476,7 +476,10 @@ snapshot lifetime; local persistence does not bypass it. `AllWritten`/`NoStuckWaiter` in `REC_safe`/`REC_safe_big`; the no-internal-sync mutant violates liveness. Prior authored LIGHT receipts are referenced in `docs/spec/README.md`; this change does not claim a new TLC execution. -- Store Write/WriteBatch admission queues pending invocations by command arrival. +- Store Write/WriteBatch uses no ticket when there is room and no waiter. The + append lock retains that space through the append; the queue lock atomically + checks no waiter exists, then releases before file I/O. Otherwise admission + queues pending invocations by command arrival. A later batch of an older command precedes younger waiters, while an already admitted append cannot be preempted. Equal arrivals use a stable command order. The oldest ticket remains held through the append-capacity decision and is released by @@ -485,7 +488,7 @@ snapshot lifetime; local persistence does not bypass it. waiting, or appending. Each store call releases its ticket before returning to the adapter; it never spans an RMW read or a replica acknowledgement. - An NVMe WAL frontend command carries one arrival-based hold identity through - adapter batches. Each store call rejoins admission at its original command position and only + adapter batches. Each queued store call rejoins admission at its original command position and only its head consumes append capacity. Queue-head changes invalidate a prior pressure sample before a capacity grant. Command observations finish after all its store calls return. Caller cancellation and an earlier deadline @@ -686,7 +689,7 @@ The "Machine / transition" column refers to Part A. Notes under a table record w | `INV-WAL-V3-RECORD-REFUSE-001` | The impl-3 codec refuses unknown types or flags, a zero nonce, invalid per-type geometry, overflowing spans and truncation before allocating a payload; the scanner reads a record only after those checks bound its size, and refuses nonzero padding, a bad CRC or a bad footer before using its bytes. | M1 v3 record framing | `core/storage/wal_entry_v3.go` `payloadSizeV3`, `decodeWALEntryV3`; `core/storage/wal_io_v3.go` `scanWALV3Accepted` | `TestWALEntryV3_RefusesInvalidEncode`, `TestWALEntryV3_RefusesMalformedWire`, `FuzzWALEntryV3_DecodeNeverPanics` | — | 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 | ACTIVE | | `INV-WAL-V3-ADMISSION-001` | v3 write admission measures WAL pressure from the active v3 writer's physical head minus the both-slot reuse floor, as a fraction of WALSize. | M1 Serving (write admission) | `core/storage/walstore.go` `openInitializedV3`, `WALStore.walUsedFraction`; `core/storage/write_command_budget.go` `WALStore.writePressureSample` | `TestWALStoreV3AdmissionUsesNativeOccupancy` (`core/storage/walstore_admission_v3_test.go`); `TestWALStoreV3WritePressureSampleMatchesOccupancy` (`core/storage/write_command_budget_test.go`); liveness under pressure: `TestWALStoreChunkV3_SequentialBurstFlush` (public provider and NVMe handler, default 64 MiB WAL, 320 MiB literal readback), `TestWALStoreChunkV3_BurstPatternBindsFullLBA` (32/64/256 MiB alias controls) (`core/frontend/durable/provider_chunk_burst_test.go`) | Existing reuse/durability rules unchanged; pressure/liveness is not a new model claim | ACTIVE | -| `INV-WAL-V3-ADMISSION-FIFO-001` | Each store call takes a ticket ordered by command arrival; older later batches precede younger waiters. An admitted append is not preempted. The ticket releases before RMW reads or replica ACKs; cancellation removes a waiter. | M1 Serving (write admission) | `core/storage/wal_admission.go` `acquireContext`, `Release`; `core/storage/wal_admission_fifo.go` | `TestWALAdmissionFIFOOwnsCapacityThroughAppend`, `TestWALAdmissionFIFOCancelledWaiterDoesNotBlockNext`, `TestWALStoreAdmissionFIFOOrdersRealAppends`, `TestWALHoldOlderBatchReentersBeforeYoungerPressureWaiter`, `TestWALHoldLargeWriteBatchesKeepCommandArrivalUnderPressure`, `TestWALAdmissionResamplesAfterOlderBatchChangesHead`, `TestWALAdmissionActiveAppendPinsReorderedCancellation`, `TestWALHoldReleasesAdmissionBeforeObserverAck`, `TestWALHoldDoesNotOwnAdmissionWhileWaitingForRMW` | WALHold r2 rows 325-333; WALHold r3 two-batch command ordering (`batch_to_tail` mutation); r3 model gate required before merge | ACTIVE | +| `INV-WAL-V3-ADMISSION-FIFO-001` | Room with no waiter is reserved atomically without a ticket. Otherwise tickets keep command-arrival order across batches. Admitted appends cannot be preempted. Release precedes RMW/peer ACK waits; cancellation removes a waiter. | M1 Serving (write admission) | `core/storage/wal_admission.go` `acquireContext`, `Release`; `core/storage/wal_admission_fifo.go`; `core/storage/wal_admission_fast.go` `lockFastWALAppend` | `TestWALAdmissionFastPathHasNoTicket`, `TestWALAdmissionFastPathCannotPassAWaiter`, `TestWALAdmissionFastReservationKeepsAppendLock`, `TestWALAdmissionFIFOOwnsCapacityThroughAppend`, `TestWALAdmissionFIFOCancelledWaiterDoesNotBlockNext`, `TestWALStoreAdmissionFIFOOrdersRealAppends`, `TestWALHoldOlderBatchReentersBeforeYoungerPressureWaiter`, `TestWALHoldLargeWriteBatchesKeepCommandArrivalUnderPressure`, `TestWALAdmissionResamplesAfterOlderBatchChangesHead`, `TestWALAdmissionActiveAppendPinsReorderedCancellation`, `TestWALHoldReleasesAdmissionBeforeObserverAck`, `TestWALHoldDoesNotOwnAdmissionWhileWaitingForRMW` | WALHold r2 rows 325-333; WALHold r3b two-batch ordering (`batch_to_tail`); WALHold r3c fast path (`fast_ignores_waiters`); model qualification complete, native/performance gates separate | ACTIVE | | `INV-WAL-HOLD-WINDOW-001` | A command's WAL-pressure inactivity window starts no earlier than its own hold; a host retry gets a fresh window. Successful same-store reclaim or extent-byte increments renew it. | M1 Serving (write admission) | `core/storage/wal_write_hold.go` `start`, `check`; `wal_hold_window.go` | `TestWALWriteHoldStallIsTypedAndFreshPerCommand`, `TestWALWriteHoldMovingReclaimOutlastsOldAdmissionBudget`, `TestWALHoldWindowRetryGetsOwnStallWindow`, `TestWALHoldSamplerRenewsOnlySuccessfulByteProgress` | WALHold r2 rows 325-333, StallHoldsOwnWindow, ErrorOnlyOnStall | ACTIVE | | `INV-WAL-HOLD-CAP-001` | Progress does not renew a command's arrival-based hold cap. Startup refuses a non-positive network cap or a cap leaving less than five seconds before the declared host timeout. | M1 Serving (write admission) | `core/storage/wal_hold_window.go`; `core/frontend/wal_hold_config.go` | `TestWALWriteHoldCapWhileProgressMoves`, `TestWALHoldRealWALAgedBatchKeepsCapAndEarlierDeadline`, `TestWALHoldConfigHostTimeoutMargin`, `TestParseFlagsWALHoldHostTimeout` | WALHold r2 rows 325-333, NoHostTimeout, RetryOnlyAtCap | ACTIVE | | `INV-WAL-HOLD-DEGRADED-001` | Five seconds of WAL pressure without progress marks reclaim diagnostically degraded; it does not change authority or frontend readiness. | M1 Serving (diagnostics) | `core/storage/wal_write_hold.go` `check`; `wal_hold_status.go`; `core/host/volume/status_server.go` | `TestWALWriteHoldDegradedBeforeFinalStallAndCancellationJoins`, `TestWALHoldDegradedDoesNotChangeReadiness`, `TestWALHoldReleasesAdmissionBeforeObserverAck`, `TestWALHoldDoesNotOwnAdmissionWhileWaitingForRMW` | WALHold r2 window; diagnostic projection only | ACTIVE | diff --git a/seaweed-block/docs/operator-guide.md b/seaweed-block/docs/operator-guide.md index 78db6f48db..a4d45ceadc 100644 --- a/seaweed-block/docs/operator-guide.md +++ b/seaweed-block/docs/operator-guide.md @@ -681,7 +681,7 @@ The holder cannot discover an initiator's I/O timeout. Set `blockvolume --host-i For NVMe/TCP, the per-command WAL-pressure hold limit, `--wal-hold-timeout`, defaults to `25s`. Startup refuses a non-positive hold or a hold that leaves less than five seconds before `--host-io-timeout`: `hold + 5s <= host_io_timeout`. Thus the default `25s` hold and `30s` host timeout are valid. For a `15s` host timeout, set the hold to at most `10s`. The five-second margin allows for network and queueing delay; it does not configure the host. -For NVMe/TCP, each store append waiting on WAL capacity keeps its FIFO position until that append returns. A command keeps its arrival cap across batches, and each batch rejoins admission by the original command arrival: an older command precedes younger waiters, while an append already admitted completes first. The ticket is released before read-modify-write reads and replica acknowledgement waits. Reclaimed WAL bytes or successful extent writes renew that command's five-second inactivity window; identical samples and flusher phase changes do not. At the hold cap or a five-second reclaim stall, NVMe returns retryable SC `0x82` (CRD2 when ACRE is negotiated). Permanent storage faults keep their original failure classification. +For NVMe/TCP, a store append with enough space and no waiter proceeds without a queue ticket. Otherwise each store append waiting on WAL capacity keeps its FIFO position until that append returns; a new call cannot bypass a waiter even if reclaim has just made room. A command keeps its arrival cap across batches, and each batch rejoins admission by the original command arrival: an older command precedes younger waiters, while an append already admitted completes first. The ticket is released before read-modify-write reads and replica acknowledgement waits. Reclaimed WAL bytes or successful extent writes renew that command's five-second inactivity window; identical samples and flusher phase changes do not. At the hold cap or a five-second reclaim stall, NVMe returns retryable SC `0x82` (CRD2 when ACRE is negotiated). Permanent storage faults keep their original failure classification. A five-second reclaim stall also sets diagnostic `Degraded` in status. Read `GET /status/wal-hold?volume=` for atomic hold counters, reclaimed/extent bytes and flusher phase, or `GET /metrics?volume=` for numeric metrics. These endpoints share the status listener's access rules and avoid frontier locks. A degraded reclaim diagnostic does not remove authority or turn frontend readiness off. Successful reclaim/extent progress clears that diagnostic. Hold events name `wal_hold_cap`, `wal_reclaim_stalled`, completion, cancellation or a write failure, with accumulated admission-wait nanoseconds.