phase167: coalesce stable checkpoint writes

This commit is contained in:
pingqiu committed 2026-07-29 20:16:20 -07:00
1 parent 8f8d369746
commit 293b030aca
7 files changed
+165 -34

No files matched your search

@@ -90,7 +90,8 @@ failure is known, then snapshots `H` and the per-lane published heads. It then:
When a lane exceeds its retained-slot threshold, `Sync` additionally:
1. writes only latest blocks with `LSN <= R` to the shared extent;
1. writes only latest blocks with `LSN <= R` to the shared extent, coalescing
contiguous LBAs into bounded 1 MiB positioned writes;
2. fsyncs the extent;
3. advances checkpoint and lane tails in the alternate header;
4. fsyncs that header;
@@ -90,8 +90,12 @@ func BenchmarkPhase167ParallelWALContention(b *testing.B) {
}
s.mu.RUnlock()
_, walTail, _ := s.Boundaries()
s.mu.RLock()
checkpointWriteOps := s.checkpointWriteOps
s.mu.RUnlock()
reportParallelLatencyPercentiles(b, latencies)
b.ReportMetric(float64(activeLanes), "active_lanes")
b.ReportMetric(float64(checkpointWriteOps), "checkpoint_write_ops")
b.ReportMetric(float64(walTail), "wal_tail")
b.ReportMetric(float64(b.N)/wallDuration.Seconds(), "write_ops/s")
})
@@ -51,6 +51,10 @@ func (h fileHeader) validate() error {
if h.BlockSize == 0 || h.NumBlocks == 0 {
return fmt.Errorf("%w: blockSize=%d numBlocks=%d", errBadGeometry, h.BlockSize, h.NumBlocks)
}
if h.BlockSize > maxCheckpointWriteBytes {
return fmt.Errorf("%w: blockSize=%d exceeds maximum=%d",
errBadGeometry, h.BlockSize, maxCheckpointWriteBytes)
}
if h.LaneCount == 0 || h.LaneCount > maxLaneCount {
return fmt.Errorf("%w: laneCount=%d", errBadGeometry, h.LaneCount)
}
+88 -33
View File
@@ -17,7 +17,10 @@ import (
"github.com/seaweedfs/seaweed-block/core/storage"
)
const defaultQueueDepth = 128
const (
defaultQueueDepth = 128
maxCheckpointWriteBytes = 1 << 20
)
var (
ErrNotRecovered = errors.New("parallelwal: store must be recovered before use")
@@ -83,30 +86,31 @@ type Store struct {
slotsPerLane uint64
retainPerLane uint64
mu sync.RWMutex
cond *sync.Cond
syncMu sync.Mutex
closed bool
closing bool
recovered bool
terminalErr error
reuseFence bool
nextLSN uint64
stableLSN uint64
checkpointLSN uint64
pendingBaseLSN uint64
baseCommitPending bool
walTail uint64
publishedLSN uint64
publishedHeads [maxLaneCount]uint64
inflightAppends int
pending map[uint64]*writeRequest
latest map[uint32]blockVersion
applied map[uint32]uint64
history map[uint64]walRecord
baseStageActive bool
baseStageSlot int
baseStage map[uint32][]byte
mu sync.RWMutex
cond *sync.Cond
syncMu sync.Mutex
closed bool
closing bool
recovered bool
terminalErr error
reuseFence bool
nextLSN uint64
stableLSN uint64
checkpointLSN uint64
pendingBaseLSN uint64
baseCommitPending bool
walTail uint64
publishedLSN uint64
publishedHeads [maxLaneCount]uint64
inflightAppends int
pending map[uint64]*writeRequest
latest map[uint32]blockVersion
applied map[uint32]uint64
history map[uint64]walRecord
baseStageActive bool
baseStageSlot int
baseStage map[uint32][]byte
checkpointWriteOps uint64
lanes []*lane
extentLocks [256]sync.RWMutex
@@ -720,14 +724,9 @@ func (s *Store) Sync() (uint64, error) {
return target, nil
}
for lba, data := range blocks {
lock := &s.extentLocks[lba%uint32(len(s.extentLocks))]
lock.Lock()
_, err := s.fd.WriteAt(data, s.extentOffsetFor(checkpointExtent, lba))
lock.Unlock()
if err != nil {
return 0, fmt.Errorf("parallelwal: checkpoint extent LBA %d: %w", lba, err)
}
checkpointWriteOps, err := s.writeCheckpointBlocks(checkpointExtent, blocks)
if err != nil {
return 0, err
}
if err := s.fd.Sync(); err != nil {
return 0, fmt.Errorf("parallelwal: sync checkpoint extent: %w", err)
@@ -755,6 +754,7 @@ func (s *Store) Sync() (uint64, error) {
s.pendingBaseLSN = 0
}
s.baseCommitPending = false
s.checkpointWriteOps = uint64(checkpointWriteOps)
if target > s.stableLSN {
s.stableLSN = target
}
@@ -782,6 +782,61 @@ func (s *Store) Sync() (uint64, error) {
return target, nil
}
func (s *Store) writeCheckpointBlocks(extent int, blocks map[uint32][]byte) (int, error) {
if len(blocks) == 0 {
return 0, nil
}
lbas := make([]uint32, 0, len(blocks))
for lba := range blocks {
lbas = append(lbas, lba)
}
sort.Slice(lbas, func(i, j int) bool { return lbas[i] < lbas[j] })
maxBlocks := maxCheckpointWriteBytes / int(s.blockSize)
if maxBlocks < 1 {
maxBlocks = 1
}
writeOps := 0
for first := 0; first < len(lbas); {
last := first + 1
for last < len(lbas) &&
last-first < maxBlocks &&
lbas[last] == lbas[last-1]+1 {
last++
}
lockIDs := make([]int, 0, last-first)
seenLocks := make(map[int]struct{}, last-first)
for _, lba := range lbas[first:last] {
lockID := int(lba % uint32(len(s.extentLocks)))
if _, exists := seenLocks[lockID]; !exists {
seenLocks[lockID] = struct{}{}
lockIDs = append(lockIDs, lockID)
}
}
sort.Ints(lockIDs)
for _, lockID := range lockIDs {
s.extentLocks[lockID].Lock()
}
buf := make([]byte, (last-first)*int(s.blockSize))
for i, lba := range lbas[first:last] {
copy(buf[i*int(s.blockSize):], blocks[lba])
}
_, err := s.fd.WriteAt(buf, s.extentOffsetFor(extent, lbas[first]))
for i := len(lockIDs) - 1; i >= 0; i-- {
s.extentLocks[lockIDs[i]].Unlock()
}
if err != nil {
return writeOps, fmt.Errorf("parallelwal: checkpoint extent LBA range [%d,%d]: %w",
lbas[first], lbas[last-1], err)
}
writeOps++
first = last
}
return writeOps, nil
}
func (s *Store) persistHeader(
durable, checkpoint uint64,
heads, tails [maxLaneCount]uint64,
@@ -1060,8 +1060,50 @@ func TestRecycledSlotsRemainRecoverableThroughHeaderFallback(t *testing.T) {
}
}
func TestCheckpointWritesCoalesceContiguousLBAs(t *testing.T) {
path := filepath.Join(t.TempDir(), "parallelwal.bin")
cfg := testConfig()
cfg.NumBlocks = 1024
cfg.BlockSize = 4096
s, err := CreateStoreWithConfig(path, cfg)
if err != nil {
t.Fatal(err)
}
defer s.Close()
blocks := make(map[uint32][]byte)
for lba := uint32(0); lba < 600; lba++ {
blocks[lba] = testBlock(byte(lba%251+1), s.BlockSize())
}
blocks[700] = testBlock(0xee, s.BlockSize())
writeOps, err := s.writeCheckpointBlocks(s.activeExtent, blocks)
if err != nil {
t.Fatal(err)
}
if writeOps != 4 {
t.Fatalf("checkpoint write ops=%d want=4 (three bounded contiguous writes plus one gap)", writeOps)
}
for _, lba := range []uint32{0, 255, 256, 599, 700} {
data := make([]byte, s.BlockSize())
if _, err := s.fd.ReadAt(data, s.extentOffsetFor(s.activeExtent, lba)); err != nil {
t.Fatal(err)
}
if want := blocks[lba][0]; data[0] != want {
t.Fatalf("LBA %d byte=%02x want=%02x", lba, data[0], want)
}
}
}
func TestHeaderForConfigRejectsPersistedGeometryOverflow(t *testing.T) {
tests := []Config{
{
NumBlocks: 1,
BlockSize: maxCheckpointWriteBytes + 1,
LaneCount: 1,
StripeBlocks: 1,
SlotsPerLane: 2,
QueueDepth: 1,
},
{
NumBlocks: 1,
BlockSize: int(uint64(^uint32(0)) + 1),
@@ -133,6 +133,24 @@ gate therefore records
redesign are required before RF3 or mounted promotion gates; the default
backend remains unchanged.
D4 Linux profiling at exact commit `ac2b4d5` passed the race suites and showed
why `io_uring` is not the first change:
- three same-run rounds measured the candidate at about `88-101 MiB/s` and
legacy `walstore` at `174-211 MiB/s`;
- an 8000-write candidate run issued `16009 pwrite64` calls versus `11852` for
legacy, because pressure checkpointing wrote each stable block separately;
- candidate CPU samples were dominated by syscall (`32%`), memory copy
(`21%`), CRC (`11%`), and lock spinning (`11%`);
- sustained loops could drive the local NVMe device above `90%` utilization,
so the evidence does not support treating the device as idle or adding an
asynchronous API without first removing avoidable write amplification.
The first D4 execution change therefore coalesces contiguous checkpoint LBAs
into bounded 1 MiB positioned writes. This is simpler than a new Linux-only
backend, preserves the established WAL/header protocol, and gives a direct
gate metric (`checkpoint_write_ops`) before any `io_uring` decision.
## Assumptions And Boundaries
- `walstore` remains the default backend until the candidate passes the full
@@ -126,11 +126,13 @@ for writers in 1 2 4 8; do
candidate_mibps="$(require_metric BenchmarkPhase167ParallelWALContention "${writers}" MB/s)"
candidate_p99="$(require_metric BenchmarkPhase167ParallelWALContention "${writers}" p99_ns)"
active_lanes="$(require_metric BenchmarkPhase167ParallelWALContention "${writers}" active_lanes)"
checkpoint_write_ops="$(require_metric BenchmarkPhase167ParallelWALContention "${writers}" checkpoint_write_ops)"
wal_tail="$(require_metric BenchmarkPhase167ParallelWALContention "${writers}" wal_tail)"
legacy_mibps="$(require_metric BenchmarkPhase167LegacyWALContentionControl "${writers}" MB/s)"
write_summary "candidate_writers_${writers}_mibps=${candidate_mibps}"
write_summary "candidate_writers_${writers}_p99_ns=${candidate_p99}"
write_summary "candidate_writers_${writers}_active_lanes=${active_lanes}"
write_summary "candidate_writers_${writers}_checkpoint_write_ops=${checkpoint_write_ops}"
write_summary "candidate_writers_${writers}_wal_tail=${wal_tail}"
write_summary "legacy_writers_${writers}_mibps=${legacy_mibps}"
done
@@ -141,6 +143,11 @@ write_summary "multiple_lanes_observed=true"
wal_tail_four="$(require_metric BenchmarkPhase167ParallelWALContention 4 wal_tail)"
awk -v value="${wal_tail_four}" 'BEGIN { if (value <= 1) exit 1 }'
write_summary "steady_state_recycle_observed=true"
checkpoint_ops_four="$(require_metric BenchmarkPhase167ParallelWALContention 4 checkpoint_write_ops)"
awk -v value="${checkpoint_ops_four}" -v writes="${iterations}" 'BEGIN {
if (value <= 0 || value >= writes / 16) exit 1
}'
write_summary "checkpoint_write_coalescing_observed=true"
candidate_1="$(require_metric BenchmarkPhase167ParallelWALContention 1 MB/s)"
candidate_4="$(require_metric BenchmarkPhase167ParallelWALContention 4 MB/s)"