fix: retain FIFO WAL admission tickets through append

This commit is contained in:
pingqiu committed 2026-12-02 04:12:10 -08:00
1 parent 56289b4fdb
commit ebc0f5d3cd
5 files changed
+266 -8

No files matched your search

+28 -8
View File
@@ -4,6 +4,7 @@ import (
"context"
"errors"
"fmt"
"sync"
"sync/atomic"
"time"
)
@@ -34,13 +35,15 @@ var errVolumeClosed = errors.New("storage: volume closed during admission wait")
// for the hard watermark to clear reduces the budget available
// for semaphore acquisition.
type walAdmission struct {
sem chan struct{} // counting semaphore for concurrent appenders
walUsed func() float64
notifyFn func() // wakes flusher
softMark float64
hardMark float64
closedFn func() bool
faultFn func() error // lock-free terminal fault lookup; nil for controllers without a store
queueMu sync.Mutex
first, last *walAdmissionTicket
sem chan struct{} // counting semaphore for concurrent appenders
walUsed func() float64
notifyFn func() // wakes flusher
softMark float64
hardMark float64
closedFn func() bool
faultFn func() error // lock-free terminal fault lookup; nil for controllers without a store
sleepFn func(time.Duration) // replaceable for tests
@@ -113,6 +116,16 @@ func (a *walAdmission) acquireContext(ctx context.Context, timeout time.Duration
}
deadline := time.NewTimer(timeout)
defer deadline.Stop()
ticket := a.enqueueTicket()
granted := false
defer func() {
if !granted {
a.removeTicket(ticket)
}
}()
if err := a.waitForTicket(ctx, deadline, ticket, contextual); err != nil {
return err
}
pressure, err := sample()
if err != nil {
@@ -179,6 +192,7 @@ func (a *walAdmission) acquireContext(ctx context.Context, timeout time.Duration
// Acquire semaphore slot using the same deadline.
select {
case a.sem <- struct{}{}:
granted = true
return nil
default:
}
@@ -187,6 +201,7 @@ func (a *walAdmission) acquireContext(ctx context.Context, timeout time.Duration
for {
select {
case a.sem <- struct{}{}:
granted = true
return nil
case <-ctx.Done():
if err := a.terminalFault(); err != nil {
@@ -215,7 +230,12 @@ func (a *walAdmission) acquireContext(ctx context.Context, timeout time.Duration
}
// Release returns a write slot to the semaphore.
func (a *walAdmission) Release() { <-a.sem }
func (a *walAdmission) Release() {
<-a.sem
a.queueMu.Lock()
a.unlinkTicketLocked(a.first)
a.queueMu.Unlock()
}
// terminalFault is sampled only on waiting paths. The store supplies its atomic
// latch lookup; this does not acquire a store lock or perform persistence I/O.
@@ -0,0 +1,85 @@
package storage
import (
"context"
"time"
)
// A successful admission keeps its ticket until Release, after its append
// capacity decision. Granting the next ticket earlier permits it to consume
// the oldest writer's capacity even if semaphore grants were in FIFO order.
type walAdmissionTicket struct {
prev, next *walAdmissionTicket
ready chan struct{}
}
func (a *walAdmission) enqueueTicket() *walAdmissionTicket {
t := &walAdmissionTicket{ready: make(chan struct{})}
a.queueMu.Lock()
t.prev = a.last
if a.last != nil {
a.last.next = t
} else {
a.first = t
close(t.ready)
}
a.last = t
a.queueMu.Unlock()
return t
}
func (a *walAdmission) removeTicket(t *walAdmissionTicket) {
a.queueMu.Lock()
a.unlinkTicketLocked(t)
a.queueMu.Unlock()
}
func (a *walAdmission) unlinkTicketLocked(t *walAdmissionTicket) {
if t.prev != nil {
t.prev.next = t.next
} else {
a.first = t.next
if a.first != nil {
close(a.first.ready)
}
}
if t.next != nil {
t.next.prev = t.prev
} else {
a.last = t.prev
}
}
func (a *walAdmission) waitForTicket(ctx context.Context, deadline *time.Timer, t *walAdmissionTicket, contextual bool) error {
tick := time.NewTicker(5 * time.Millisecond)
defer tick.Stop()
for {
select {
case <-t.ready:
if err := ctx.Err(); err != nil {
if fault := a.terminalFault(); fault != nil {
return fault
}
return admissionContextError(err)
}
return nil
case <-ctx.Done():
if fault := a.terminalFault(); fault != nil {
return fault
}
return admissionContextError(ctx.Err())
case <-deadline.C:
if fault := a.terminalFault(); fault != nil {
return fault
}
return ErrWALPressureTimeout
case <-tick.C:
if fault := a.terminalFault(); fault != nil {
return fault
}
if !contextual && a.closedFn() {
return errVolumeClosed
}
}
}
}
@@ -0,0 +1,130 @@
package storage
import (
"bytes"
"context"
"sync"
"sync/atomic"
"testing"
"testing/synctest"
"time"
)
func TestWALAdmissionFIFOOwnsCapacityThroughAppend(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
a := newWALAdmission(walAdmissionConfig{MaxConcurrent: 4, SoftWatermark: .7, HardWatermark: .9, WALUsedFn: func() float64 { return 0 }, NotifyFn: func() {}, ClosedFn: func() bool { return false }})
if err := a.Acquire(time.Minute); err != nil {
t.Fatal(err)
}
// A has passed admission but is paused before consuming capacity. Younger
// writes must not append merely because A's semaphore token was granted.
appended := make(chan string, 2)
launch := func(name string, ctx context.Context) {
go func() {
if err := a.acquireContext(ctx, time.Minute, nil); err != nil {
appended <- "error:" + name
return
}
appended <- name // the protected append-capacity consumption
a.Release()
}()
}
launch("B", context.Background())
synctest.Wait()
launch("C", context.Background())
synctest.Wait()
select {
case name := <-appended:
t.Fatalf("younger append overtook A: %s", name)
default:
}
a.Release() // A consumed capacity before handing over its ticket.
synctest.Wait()
for _, want := range []string{"B", "C"} {
select {
case got := <-appended:
if got != want {
t.Fatalf("append order got%s want%s", got, want)
}
default:
t.Fatalf("missing append %s", want)
}
}
})
}
func TestWALAdmissionFIFOCancelledWaiterDoesNotBlockNext(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
a := newWALAdmission(walAdmissionConfig{MaxConcurrent: 4, SoftWatermark: .7, HardWatermark: .9, WALUsedFn: func() float64 { return 0 }, NotifyFn: func() {}, ClosedFn: func() bool { return false }})
if err := a.Acquire(time.Minute); err != nil {
t.Fatal(err)
}
ctx, cancel := context.WithCancel(context.Background())
done := make(chan error, 1)
go func() {
err := a.acquireContext(ctx, time.Minute, nil)
if err == nil {
a.Release()
}
done <- err
}()
synctest.Wait()
cancel()
synctest.Wait()
if err := <-done; err != context.Canceled {
t.Fatalf("cancelled waiter: %v", err)
}
a.Release()
if err := a.Acquire(time.Minute); err != nil {
t.Fatalf("cancelled ticket blocked next: %v", err)
}
a.Release()
})
}
func TestWALStoreAdmissionFIFOOrdersRealAppends(t *testing.T) {
s := admissionPressureV3(t, 0)
synctest.Test(t, func(t *testing.T) {
entered, resume := make(chan struct{}), make(chan struct{})
var once sync.Once
release := func() { once.Do(func() { close(resume) }) }
defer func() { release(); synctest.Wait() }()
var calls atomic.Int32
s.testAfterAdmit = func() {
if calls.Add(1) == 1 {
close(entered)
<-resume
}
}
before := s.NextLSN()
type answer struct {
lsn uint64
err error
}
done := make([]chan answer, 3)
start := func(i int) {
done[i] = make(chan answer, 1)
go func() { n, err := s.Write(uint32(i), blk(byte(i+1))); done[i] <- answer{n, err} }()
}
start(0)
<-entered
start(1)
synctest.Wait()
start(2)
synctest.Wait()
if got := s.NextLSN(); got != before {
t.Fatalf("younger write appended ahead of paused oldest: nextLSN%d want%d", got, before)
}
release()
synctest.Wait()
for i := 0; i < 3; i++ {
got := <-done[i]
if got.err != nil || got.lsn != before+uint64(i) {
t.Fatalf("write%d got LSN%d err%v; want%d", i, got.lsn, got.err, before+uint64(i))
}
if b, err := s.Read(uint32(i)); err != nil || !bytes.Equal(b, blk(byte(i+1))) {
t.Fatalf("readback%d: %v", i, err)
}
}
})
}
+16
View File
@@ -382,3 +382,19 @@ These are tracked for fixes. Most were raised by an independent review of this r
- **No authentication** on the control plane, the replication channel or the filer client. Frontends bind to loopback by default. **Planned:** mTLS and role checks for destructive operations.
- **blockmaster is a single instance.** There is no master high availability. A master outage longer than the lease stops I/O on every workspace, and recovery is then a forced move; Kubernetes volumes cannot fail over while it is down.
- **Formats are exact-version.** The superblock, HEAD and segment formats are checked exactly and fail closed; the walstore superblock has no CRC. A format change needs a dual-reader release.
### WAL admission order
Each store Write/WriteBatch invocation keeps its oldest ticket through the append-capacity decision. Handing out multiple FIFO tokens before append would let a younger write consume the older write's space. Waiting and physical I/O run without the queue mutex. Command-wide multi-batch hold integration is separate from this store invocation queue.
```mermaid
stateDiagram-v2
[*] --> Queued
Queued --> Oldest: prior invocation releases
Queued --> Removed: cancellation or refusal
Oldest --> Append: capacity available
Oldest --> Removed: cancellation or refusal
Append --> Released: append decision returns
Released --> [*]
Removed --> [*]
```
+7
View File
@@ -476,6 +476,12 @@ 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 invocations in FIFO order. The oldest
ticket remains held through the append-capacity decision and is released by
the existing post-write Release. A cancelled or refused invocation removes
its ticket and wakes the next. No queue mutex is held while sampling pressure,
waiting, or appending. The command-wide multi-batch hold is a separate caller
integration; this queue does not claim that completed layer yet.
- A v3 write carries one four-second command deadline through dispatch,
adapter batches, store admission locks and occupancy snapshots. Admission
reserves append headroom and expiry before append refuses without mutation.
@@ -674,6 +680,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` | Store write admission retains the oldest waiting ticket through its append-capacity decision; a cancelled waiter relinquishes its ticket without blocking later writes. | M1 Serving (write admission) | `core/storage/wal_admission.go` `acquireContext`, `Release`; `core/storage/wal_admission_fifo.go` | `TestWALAdmissionFIFOOwnsCapacityThroughAppend`, `TestWALAdmissionFIFOCancelledWaiterDoesNotBlockNext`, `TestWALStoreAdmissionFIFOOrdersRealAppends` | WALHold r2 rows 325-338, `AdmitInOrder`; command-wide multi-batch hold integration remains separate | ACTIVE |
| `INV-WAL-V3-ADMISSION-FAULT-001` | A terminal I/O fault latched while a v3 write waits on WAL pressure or for an admission slot ends that wait with the fault's original typed cause, also when the deadline has expired at the same check. | M1 Serving (write admission) | `core/storage/wal_admission.go` `walAdmission.acquireContext`, `walAdmission.terminalFault`; `core/storage/write_command_budget.go` `WALStore.writeBudgetError` | `TestWALStoreV3AdmissionReturnsFaultLatchedDuringPressureWait` (Write and WriteBatch); `TestWALStoreV3WriteBudgetKeepsTerminalFault` (`core/storage/write_command_budget_test.go`); also in `core/storage/wal_admission_fault_v3_test.go` | — | ACTIVE |
| `INV-WAL-V3-ADMISSION-DEADLINE-001` | One command deadline, the earlier of the caller's deadline and the command's arrival plus `WriteCommandBudget`, bounds every adapter batch of a write and its store waits for the capture and lifecycle locks, on the local clock. | M1 Serving (write admission) | `core/frontend/write_budget.go` `WithWriteBudget`; `core/frontend/durable/storage_adapter.go` `StorageBackend.Write`, `writeBytes`; `core/storage/write_command_budget.go` `WALStore.writeAdmissionDeadline`, `WALStore.acquireWriteLock`; `core/storage/walstore.go` `WALStore.WriteContext`, `WALStore.WriteBatchContext` | `TestStorageBackendWriteKeepsOneDeadlineAcrossBatches`, `TestWALStoreV3WriteContextDeadlineIncludesCaptureWait`, `TestWALStoreV3WriteBudgetIncludesPostAdmissionWait`, `TestSessionWriteBudgetIncludesDispatchQueue` | — | ACTIVE |
| `INV-WAL-V3-ADMISSION-SHORTLOCK-001` | A v3 write takes the store, descriptor and WAL writer locks blocking, never by polling, so RWMutex writer preference holds, and its command deadline is checked once they are held. | M1 Serving (write admission) | `core/storage/walstore.go` `WALStore.WriteContext`, `WALStore.WriteBatchContext`; `core/storage/write_command_budget.go` `WALStore.writePressureSample`; `core/storage/wal_io_v3.go` `walWriterV3.append` | `TestWALStoreV3ExpiredWriterRefusesAfterShortLockWait`, `TestWALStoreV3WriteKeepsWriterPreferenceUnderReaders`, `TestWALStoreV3WriteBudgetRefusesAfterDescriptorWaitBehindSync` | — | ACTIVE |