Merge main into the finalize change

This commit is contained in:
pingqiu committed 2026-12-02 08:27:11 -08:00
commit 7db6a75e65
42 files changed
+2723 -127

No files matched your search

+4
View File
@@ -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
1 # Exact repository-relative path<TAB>Module.Action; repeat a path for alternatives.
126 core/storage/chunk_coverage.go
127 core/storage/chunk_coverage_map.go
128 core/storage/walstore_v3.go
129 core/storage/wal_admission_fast.go
130 core/storage/wal_admission_fast.go
131 core/storage/wal_admission_fast.go
132
+8
View File
@@ -44,6 +44,7 @@ import (
)
type flags struct {
walHold frontend.WALHoldConfig
logLevel string
cpuProfileDir string
memoryLimitMiB int64
@@ -193,6 +194,9 @@ func parseFlags(args []string) (flags, error) {
func parseFlagsWithCgroup(args []string, readFile func(string) ([]byte, error)) (flags, error) {
var f flags
fs := flag.NewFlagSet("blockvolume", flag.ContinueOnError)
writePolicy := frontend.DefaultWALHoldConfig()
fs.DurationVar(&f.walHold.MaxHold, "wal-hold-timeout", writePolicy.MaxHold, "maximum per-command WAL-pressure hold; positive and at least 5s below --host-io-timeout")
fs.DurationVar(&f.walHold.HostIOTimeout, "host-io-timeout", writePolicy.HostIOTimeout, "operator-declared host I/O timeout (host_io_timeout); set to match your hosts when changing io_timeout")
fs.StringVar(&f.logLevel, "log-level", "info", "log verbosity: info or debug; timestamps are UTC with microseconds")
fs.Int64Var(&f.memoryLimitMiB, "memory-limit-mib", 4*storage.DefaultCutPayloadMemoryBudget/(1<<20), "process Go soft memory limit in MiB; unset: 90% of the effective cgroup v2 memory.max, or 256 MiB without a limit or when it cannot be derived (one WARN says why); 0 preserves GOMEMLIMIT; explicit GOMEMLIMIT is preserved unless this flag is set")
fs.StringVar(&f.masterAddr, "master", "", "master gRPC address (required)")
@@ -286,6 +290,9 @@ func parseFlagsWithCgroup(args []string, readFile func(string) ([]byte, error))
if err := fs.Parse(args); err != nil {
return flags{}, err
}
if err := f.walHold.Validate(); err != nil {
return flags{}, err
}
if err := logging.ValidateLevel(f.logLevel); err != nil {
return flags{}, err
}
@@ -734,6 +741,7 @@ func runVolume(f flags, exits *processExit) int {
blocks, blockSize, geometryErr := durableCreateGeometry(f)
var dp *durable.DurableProvider
cfg := durable.ProviderConfig{
WALHold: f.walHold,
RecoveryProgress: h.ReportRecoveryProgress,
AuthorityWait: h.ReportAuthorityWait,
Impl: durable.ImplName(f.durableImpl),
@@ -0,0 +1,42 @@
package main
import (
"errors"
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/frontend"
)
func TestParseFlagsWALHoldHostTimeout(t *testing.T) {
for _, tc := range []struct {
name string
args []string
hold, host time.Duration
valid bool
}{
{"defaults", nil, 25 * time.Second, 30 * time.Second, true},
{"explicit equality", []string{"--wal-hold-timeout", "10s", "--host-io-timeout", "15s"}, 10 * time.Second, 15 * time.Second, true},
{"host lowered without hold", []string{"--host-io-timeout", "29s"}, 0, 0, false},
{"hold above margin", []string{"--wal-hold-timeout", "25.000000001s"}, 0, 0, false},
{"zero hold", []string{"--wal-hold-timeout", "0"}, 0, 0, false},
} {
t.Run(tc.name, func(t *testing.T) {
args := append(requiredBlockvolumeArgs(), tc.args...)
f, err := parseFlags(args)
if tc.valid {
if err != nil {
t.Fatal(err)
}
if f.walHold.MaxHold != tc.hold || f.walHold.HostIOTimeout != tc.host {
t.Fatalf("parsed policy: %+v", f.walHold)
}
} else {
var invalid *frontend.WALHoldConfigError
if !errors.As(err, &invalid) {
t.Fatalf("want typed startup refusal, got %v", err)
}
}
})
}
}
@@ -0,0 +1,34 @@
package durable
import (
"context"
"errors"
"path/filepath"
"testing"
"testing/synctest"
"time"
"github.com/seaweedfs/seaweed-block/core/frontend"
"github.com/seaweedfs/seaweed-block/core/storage"
)
func TestDeviceLegacyBudgetDoesNotInstallARetryableWALHold(t *testing.T) {
s, err := storage.CreateWALStoreWithOptions(filepath.Join(t.TempDir(), "store"), 256, 4096, storage.WALStoreOptions{ChunkBlocks: 16})
if err != nil {
t.Fatal(err)
}
defer s.Close()
b := NewStorageBackend(s, holdCommandView{}, frontend.Identity{VolumeID: "v1", ReplicaID: "r1", Epoch: 1, EndpointVersion: 1})
synctest.Test(t, func(t *testing.T) {
ctx, cancel := frontend.WithLegacyWriteBudget(context.Background(), time.Now())
defer cancel()
ctx, cancelBackend := b.WriteCommandContext(ctx, time.Time{})
defer cancelBackend()
defer storage.FinishWALWriteHold(ctx, nil)
time.Sleep(5 * time.Second)
_, err := s.WriteContext(ctx, 0, make([]byte, 4096))
if !errors.Is(err, storage.ErrWALPressureTimeout) || errors.Is(err, storage.ErrWALHoldCap) {
t.Fatalf("legacy device budget became retryable hold: %v", err)
}
})
}
@@ -121,6 +121,7 @@ var ErrDetachOutcomeUnknown = errors.New("durable: detach outcome unknown; I/O s
// ProviderConfig configures a DurableProvider.
type ProviderConfig struct {
WALHold frontend.WALHoldConfig
// RecoveryProgress observes completed local-create and local-open work
// before RecoverVolume.
RecoveryProgress func(storage.RecoveryPhase, uint64)
@@ -397,6 +398,8 @@ type volHandle struct {
// handle. It intentionally exposes lineage and readiness facts without giving
// callers a control surface.
type VolumeStatus struct {
WALHold *storage.WALHoldStatus `json:",omitempty"` // WAL-pressure hold health and cumulative metrics
Degraded bool // diagnostic WAL reclaim stall; does not alter authority or readiness
UnknownOutcome map[layout.HeadWriteCause]uint64 // unknown HEAD-write answers by cause since catalog start; never implies persistence
HeadWrites map[layout.HeadWriteCause]uint64 // acknowledged HEAD writes by cause since holder catalog start; unknown replies excluded
VolumeID string // the volume
@@ -458,6 +461,12 @@ type CutScheduleStatus struct {
// source of authority lineage the provider is allowed to consult
// (sketch §9 boundary).
func NewDurableProvider(cfg ProviderConfig, view frontend.ProjectionView) (*DurableProvider, error) {
if cfg.WALHold == (frontend.WALHoldConfig{}) {
cfg.WALHold = frontend.DefaultWALHoldConfig()
}
if err := cfg.WALHold.Validate(); err != nil {
return nil, err
}
if cfg.StorageRoot == "" {
return nil, fmt.Errorf("durable: ProviderConfig.StorageRoot required")
}
@@ -1135,6 +1144,7 @@ func (p *DurableProvider) wrap(volumeID, path string, impl ImplName, s storage.L
EndpointVersion: proj.EndpointVersion,
}
b := NewStorageBackend(s, p.view, id)
b.walHold = p.cfg.WALHold
return &volHandle{storage: s, backend: b, path: path, impl: impl}, nil
}
@@ -1284,3 +1294,21 @@ func chunkSidecars(path string) ([]string, error) {
// Compile-time check.
var _ frontend.Provider = (*DurableProvider)(nil)
// WALHoldStatuses exposes only atomic hold/reclaim observations. It avoids the
// general durable status path's frontier locks while a slow disk is diagnosed.
func (p *DurableProvider) WALHoldStatuses() map[string]storage.WALHoldStatus {
p.mu.Lock()
stores := make(map[string]storage.LogicalStorage, len(p.volumes))
for id, h := range p.volumes {
stores[id] = h.storage
}
p.mu.Unlock()
out := make(map[string]storage.WALHoldStatus, len(stores))
for id, s := range stores {
if reporter, ok := s.(interface{ WALHoldStatus() storage.WALHoldStatus }); ok {
out[id] = reporter.WALHoldStatus()
}
}
return out
}
@@ -147,6 +147,7 @@ const maxFullBlockBatchBlocks = 64
// StorageBackend adapts a LogicalStorage into frontend.Backend.
type StorageBackend struct {
walHold frontend.WALHoldConfig
// testBeforeIOLock, test-only, runs in admit after the readiness check,
// right before the I/O lock (an arrival handshake for queued I/O).
testBeforeIOLock func()
@@ -214,11 +215,12 @@ type StorageBackend struct {
// seed) together with rebasing the observer, against installing an
// observer together with its rebase: whichever runs second sees the
// other's result. Lock order: observerMu, then mu.
observerMu sync.Mutex
observer WriteObserver // optional; nil = no replication fan-out
writeAck WriteAckPolicy
profile writeProfile
lbaWriteLocks [256]sync.Mutex
observerMu sync.Mutex
observer WriteObserver // optional; nil = no replication fan-out
writeAck WriteAckPolicy
profile writeProfile
lbaWriteLocks [256]sync.Mutex
testBeforeRMWRead func()
}
// NewStorageBackend constructs a backend. Starts NON-operational
@@ -230,6 +232,7 @@ type StorageBackend struct {
// impl changes it mid-session).
func NewStorageBackend(s storage.LogicalStorage, view frontend.ProjectionView, id frontend.Identity) *StorageBackend {
b := &StorageBackend{
walHold: frontend.DefaultWALHoldConfig(),
storage: s,
view: view,
id: id,
@@ -330,6 +333,11 @@ func (b *StorageBackend) durableStatus(volumeID, path, impl string) VolumeStatus
snapshot := reporter.CheckpointPersistence()
checkpoint = &snapshot
}
var walHold *storage.WALHoldStatus
if reporter, ok := b.storage.(interface{ WALHoldStatus() storage.WALHoldStatus }); ok {
st := reporter.WALHoldStatus()
walHold = &st
}
writeProfile := b.WriteProfile()
if instrumented, ok := b.storage.(storage.WriteInstrumented); ok {
storageProfile := instrumented.WriteInstrumentation()
@@ -362,6 +370,8 @@ func (b *StorageBackend) durableStatus(volumeID, path, impl string) VolumeStatus
storeID = hex.EncodeToString(id[:])
}
return VolumeStatus{
WALHold: walHold,
Degraded: walHold != nil && walHold.Degraded,
StoreID: storeID,
Warnings: warnings,
HolesSuspected: holes,
@@ -820,8 +830,8 @@ func (b *StorageBackend) attachReadyTimeout(cause error) error {
// writes perform a read-modify-write: fetch the current block,
// overlay the partial range, write the full block back.
// Every write is gated.
func (b *StorageBackend) Write(ctx context.Context, offset int64, p []byte) (int, error) {
ctx, cancel := frontend.WithWriteBudget(ctx, time.Time{})
func (b *StorageBackend) Write(ctx context.Context, offset int64, p []byte) (written int, writeErr error) {
ctx, cancel := b.WriteCommandContext(ctx, time.Time{})
defer cancel()
iolatency.BackendEnter(ctx)
defer iolatency.BackendExit(ctx)
@@ -831,6 +841,7 @@ func (b *StorageBackend) Write(ctx context.Context, offset int64, p []byte) (int
return 0, err
}
defer release()
defer func() { storage.FinishWALWriteHold(ctx, writeErr) }()
if len(p) == 0 {
return 0, nil
}
@@ -1113,6 +1124,9 @@ func (b *StorageBackend) writeBytes(ctx context.Context, offset int64, p []byte)
block = buf[:chunkLen]
} else {
// Partial-block: RMW.
if b.testBeforeRMWRead != nil {
b.testBeforeRMWRead()
}
existing, err := b.readStorageBlock(ctx, lba)
if err != nil {
writeLock.Unlock()
@@ -1295,3 +1309,20 @@ func expiredCommand(ctx context.Context) error {
}
return err
}
// WriteCommandContext is called at transport dispatch and again by direct
// backend callers. The context carries one identity through all store batches.
func (b *StorageBackend) WriteCommandContext(ctx context.Context, arrival time.Time) (context.Context, context.CancelFunc) {
if s, ok := b.storage.(*storage.WALStore); ok {
if frontend.UsesLegacyWriteBudget(ctx) {
ctx = storage.WithWALWriteArrival(ctx, s, arrival)
return frontend.WithWriteBudget(ctx, arrival)
}
cfg := b.walHold
if cfg == (frontend.WALHoldConfig{}) {
cfg = frontend.DefaultWALHoldConfig()
}
return storage.WithWALWriteHold(ctx, s, arrival, cfg.MaxHold, false)
}
return frontend.WithWriteBudget(ctx, arrival)
}
@@ -0,0 +1,139 @@
package durable
import (
"bytes"
"context"
"path/filepath"
"sync"
"sync/atomic"
"testing"
"testing/synctest"
"time"
"github.com/seaweedfs/seaweed-block/core/frontend"
"github.com/seaweedfs/seaweed-block/core/frontend/nvme"
"github.com/seaweedfs/seaweed-block/core/storage"
)
type holdCommandView struct{}
func (holdCommandView) Projection() frontend.Projection {
return frontend.Projection{VolumeID: "v1", ReplicaID: "r1", Epoch: 1, EndpointVersion: 1, Healthy: true}
}
func holdCommandBackend(t *testing.T) *StorageBackend {
t.Helper()
s, err := storage.CreateWALStore(filepath.Join(t.TempDir(), "volume"), 256, 4096)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = s.Close() })
b := NewStorageBackend(s, holdCommandView{}, frontend.Identity{VolumeID: "v1", ReplicaID: "r1", Epoch: 1, EndpointVersion: 1})
b.SetOperational(true, "ready")
return b
}
type holdCommandObserver struct {
called atomic.Bool
first func()
}
func (o *holdCommandObserver) Observe(ctx context.Context, _ uint32, _ uint64, _ []byte) error {
if o.called.CompareAndSwap(false, true) {
o.first()
}
return ctx.Err()
}
func (o *holdCommandObserver) ObserveBatch(ctx context.Context, _ uint32, _ []uint64, _ [][]byte) error {
if o.called.CompareAndSwap(false, true) {
o.first()
}
return ctx.Err()
}
func (o *holdCommandObserver) Sync(context.Context, uint64) error { return nil }
func TestWALHoldBudgetSurvivesNestedNVMeDispatch(t *testing.T) {
b := holdCommandBackend(t)
synctest.Test(t, func(t *testing.T) {
if err := b.SetWriteObserver(&holdCommandObserver{first: func() { time.Sleep(6 * time.Second) }}); err != nil {
t.Fatal(err)
}
b.SetWriteAckPolicy(WriteAckRequireObserverAck)
h := nvme.NewIOHandler(nvme.HandlerConfig{Backend: b, BlockSize: 4096, VolumeSize: 256 * 4096, NSID: 1})
ctx, cancel := frontend.WithBackendWriteBudget(context.Background(), time.Now(), b)
defer cancel()
got := h.Handle(ctx, nvme.IOCommand{Opcode: 1, NSID: 1, SLBA: 0, NLB: 1, Data: bytes.Repeat([]byte{7}, 4096)})
if err := got.AsError(); err != nil {
t.Fatal(err)
}
})
}
func TestWALHoldReleasesAdmissionBeforeObserverAck(t *testing.T) {
b := holdCommandBackend(t)
synctest.Test(t, func(t *testing.T) {
paused, resume := make(chan struct{}), make(chan struct{})
var once sync.Once
release := func() { once.Do(func() { close(resume) }) }
defer func() { release(); synctest.Wait() }()
if err := b.SetWriteObserver(&holdCommandObserver{first: func() { close(paused); <-resume }}); err != nil {
t.Fatal(err)
}
b.SetWriteAckPolicy(WriteAckRequireObserverAck)
doneA, doneB := make(chan error, 1), make(chan error, 1)
go func() { _, err := b.Write(context.Background(), 0, bytes.Repeat([]byte{1}, 128*4096)); doneA <- err }()
<-paused
go func() { _, err := b.Write(context.Background(), 192*4096, bytes.Repeat([]byte{2}, 4096)); doneB <- err }()
synctest.Wait()
select {
case err := <-doneB:
if err != nil {
t.Fatal(err)
}
default:
t.Fatal("unrelated append blocked behind replica acknowledgement")
}
time.Sleep(6 * time.Second) // an observer delay is not WAL-pressure inactivity
if st := b.storage.(*storage.WALStore).WALHoldStatus(); st.Degraded {
t.Fatalf("non-pressure queue delay degraded reclaim: %+v", st)
}
release()
synctest.Wait()
if err := <-doneA; err != nil {
t.Fatal(err)
}
got := make([]byte, 4096)
if _, err := b.Read(context.Background(), 192*4096, got); err != nil || !bytes.Equal(got, bytes.Repeat([]byte{2}, 4096)) {
t.Fatalf("younger bytes were overwritten: %v", err)
}
})
}
func TestWALHoldDoesNotOwnAdmissionWhileWaitingForRMW(t *testing.T) {
b := holdCommandBackend(t)
synctest.Test(t, func(t *testing.T) {
paused, resume := make(chan struct{}), make(chan struct{})
var once sync.Once
release := func() { once.Do(func() { close(resume) }) }
defer func() { release(); synctest.Wait() }()
b.testBeforeRMWRead = func() { close(paused); <-resume }
doneA, doneB := make(chan error, 1), make(chan error, 1)
go func() { _, err := b.Write(context.Background(), 1, []byte{7}); doneA <- err }()
<-paused
go func() { _, err := b.Write(context.Background(), 4096, bytes.Repeat([]byte{9}, 4096)); doneB <- err }()
synctest.Wait()
select {
case err := <-doneB:
if err != nil {
t.Fatal(err)
}
default:
t.Fatal("unrelated append blocked behind RMW read")
}
release()
synctest.Wait()
if err := <-doneA; err != nil {
t.Fatal(err)
}
})
}
@@ -40,6 +40,8 @@ func TestBackendErrorClassesAcrossFrontends(t *testing.T) {
status, key, asc, ascq, sct, sc uint8
deadline bool
}{
{name: "wal-hold-cap", err: fmt.Errorf("%w: %w", frontend.ErrBackendBusy, storage.ErrWALHoldCap), status: 0x08, sct: 0, sc: 0x82},
{name: "wal-reclaim-stalled", err: fmt.Errorf("%w: %w", frontend.ErrBackendBusy, storage.ErrWALReclaimStalled), status: 0x08, sct: 0, sc: 0x82},
{name: "wal-pressure", err: fmt.Errorf("%w: %w", frontend.ErrBackendBusy, storage.ErrWALPressureTimeout), status: 0x08, sct: 0, sc: 0x82},
{name: "hydration-pending", err: fmt.Errorf("%w: %w", frontend.ErrBackendBusy, storage.ErrChunkHydrationPending), status: 0x08, sct: 0, sc: 0x82},
{name: "observer-deadline", err: fmt.Errorf("%w: %w: %w", frontend.ErrBackendBusy, durable.ErrReplicationAckUnavailable, context.DeadlineExceeded), status: 0x08, sct: 0, sc: 0x82, deadline: true},
@@ -0,0 +1,39 @@
package iscsi
import (
"context"
"testing"
"testing/synctest"
"time"
"github.com/seaweedfs/seaweed-block/core/frontend"
)
type serialBudgetBackend struct {
frontend.Backend
legacy bool
deadline time.Time
}
func (b *serialBudgetBackend) Write(ctx context.Context, _ int64, p []byte) (int, error) {
b.legacy = frontend.UsesLegacyWriteBudget(ctx)
b.deadline, _ = ctx.Deadline()
return len(p), nil
}
func (b *serialBudgetBackend) WriteCommandContext(ctx context.Context, _ time.Time) (context.Context, context.CancelFunc) {
return context.WithTimeout(ctx, 25*time.Second)
}
func TestSerialISCSIWriteKeepsLegacyBudget(t *testing.T) {
// Budget creation happens after doWrite is called. Freeze time so that
// scheduling between this timestamp and WithTimeout cannot make the correct
// four-second budget look longer than four seconds.
synctest.Test(t, func(t *testing.T) {
b := &serialBudgetBackend{}
h := &SCSIHandler{backend: b, blockSize: 4096, volumeSize: 4096}
start := time.Now()
r := h.doWrite(context.Background(), 0, 1, make([]byte, 4096))
if r.Status != StatusGood || !b.legacy || b.deadline.IsZero() || b.deadline.After(start.Add(4*time.Second)) {
t.Fatalf("serial write status=%d legacy=%v deadline=%v", r.Status, b.legacy, b.deadline)
}
})
}
@@ -7,6 +7,7 @@ import (
"encoding/hex"
"fmt"
"log"
"time"
"github.com/seaweedfs/seaweed-block/core/frontend"
)
@@ -277,6 +278,10 @@ func (h *SCSIHandler) doRead(ctx context.Context, lba uint64, transferLen uint32
}
func (h *SCSIHandler) doWrite(ctx context.Context, lba uint64, transferLen uint32, dataOut []byte) SCSIResult {
// The serial session must return to its reader before the initiator NOP window.
// Extended WAL holds require concurrent per-command session handling.
ctx, cancel := frontend.WithLegacyWriteBudget(ctx, time.Time{})
defer cancel()
// G5-5 instrumentation: log every SCSI WRITE arrival at the
// handler. If this line doesn't fire when the kernel initiator
// writes, the iSCSI session/login layer is rejecting the
@@ -0,0 +1,111 @@
package nbd
import (
"bytes"
"context"
"github.com/seaweedfs/seaweed-block/core/frontend"
"io"
"testing"
"time"
)
type deviceBudgetBackend struct {
memoryBackend
writeCtx context.Context
syncCtx context.Context
onSync func(context.Context)
}
func (b *deviceBudgetBackend) Write(ctx context.Context, _ int64, p []byte) (int, error) {
b.writeCtx = ctx
return len(p), ctx.Err()
}
func (b *deviceBudgetBackend) Sync(ctx context.Context) error {
b.syncCtx = ctx
if b.onSync != nil {
b.onSync(ctx)
}
return nil
}
type deviceBudgetValueKey struct{}
func TestDeviceWriteKeepsLegacyBudget(t *testing.T) {
for _, op := range []string{"write", "fua", "flush"} {
for _, policy := range []string{"unbounded", "earlier_deadline", "cancel_during_sync"} {
t.Run(op+"/"+policy, func(t *testing.T) {
parent := context.WithValue(context.Background(), deviceBudgetValueKey{}, "caller")
var cancel context.CancelFunc
if policy == "earlier_deadline" {
parent, cancel = context.WithTimeout(parent, time.Second)
} else {
parent, cancel = context.WithCancel(parent)
}
defer cancel()
b := &deviceBudgetBackend{}
if policy == "cancel_during_sync" {
b.onSync = func(ctx context.Context) {
cancel()
if ctx.Err() != context.Canceled {
t.Fatalf("Sync lost caller cancellation: %v", ctx.Err())
}
}
}
start := time.Now()
req, reply := new(bytes.Buffer), new(bytes.Buffer)
command := nbdCmdWrite
if op == "fua" {
command |= nbdCmdFUA
}
payload := make([]byte, 4096)
if op == "flush" {
command = nbdCmdFlush
payload = nil
}
writeRequest(t, req, command, [8]byte{1}, 0, payload)
writeRequest(t, req, nbdCmdDisc, [8]byte{2}, 0, nil)
if err := (protocolServer{backend: b, size: 4096}).serve(parent, struct {
io.Reader
io.Writer
}{req, reply}); err != nil {
t.Fatal(err)
}
if op != "flush" {
if b.writeCtx == nil || !frontend.UsesLegacyWriteBudget(b.writeCtx) {
t.Fatal("Write lost legacy transport marker")
}
deadline, bounded := b.writeCtx.Deadline()
if !bounded || !deadline.After(start) || deadline.After(time.Now().Add(4*time.Second)) {
t.Fatalf("Write deadline=%v bounded=%v", deadline, bounded)
}
if prior, ok := parent.Deadline(); ok && !deadline.Equal(prior) {
t.Fatalf("Write lost earlier deadline: %v want %v", deadline, prior)
}
if policy != "earlier_deadline" && b.writeCtx.Err() != context.Canceled {
t.Fatalf("Write context not released: %v", b.writeCtx.Err())
}
} else if b.writeCtx != nil {
t.Fatal("flush called Write")
}
if op != "write" {
if b.syncCtx == nil {
t.Fatal("Sync not called")
}
if frontend.UsesLegacyWriteBudget(b.syncCtx) {
t.Fatal("Sync inherited Write-only marker")
}
got, gotOK := b.syncCtx.Deadline()
want, wantOK := parent.Deadline()
if gotOK != wantOK || !got.Equal(want) {
t.Fatalf("Sync deadline=%v/%v want caller %v/%v", got, gotOK, want, wantOK)
}
if b.syncCtx.Value(deviceBudgetValueKey{}) != "caller" {
t.Fatal("Sync lost caller values")
}
} else if b.syncCtx != nil {
t.Fatal("plain Write called Sync")
}
})
}
}
}
+6 -1
View File
@@ -7,6 +7,9 @@ import (
"fmt"
"io"
"syscall"
"time"
"github.com/seaweedfs/seaweed-block/core/frontend"
)
const (
@@ -93,7 +96,9 @@ func (s protocolServer) serve(ctx context.Context, rw io.ReadWriter) error {
if _, err := io.ReadFull(rw, data); err != nil {
return err
}
n, err := s.backend.Write(ctx, int64(offset), data)
writeCtx, cancel := frontend.WithLegacyWriteBudget(ctx, time.Now())
n, err := s.backend.Write(writeCtx, int64(offset), data)
cancel()
if err == nil && n == len(data) && command&nbdCmdFUA != 0 {
err = s.backend.Sync(ctx)
}
+1 -1
View File
@@ -262,7 +262,7 @@ func (h *IOHandler) read(ctx context.Context, cmd IOCommand) IOResult {
}
func (h *IOHandler) write(ctx context.Context, cmd IOCommand) IOResult {
ctx, cancel := frontend.WithWriteBudget(ctx, time.Time{})
ctx, cancel := frontend.WithBackendWriteBudget(ctx, time.Time{}, h.backend)
defer cancel()
if cmd.NLB == 0 {
return IOResult{SCT: SCTGeneric, SC: SCInvalidField, Reason: "NLB=0"}
+1 -1
View File
@@ -605,7 +605,7 @@ func (s *Session) handleWrite(ctx context.Context, req *Request) {
if arrival.IsZero() {
arrival = req.dispatchReadyAt
}
ctx, cancel := frontend.WithWriteBudget(ctx, arrival)
ctx, cancel := frontend.WithBackendWriteBudget(ctx, arrival, s.handler.backend)
defer cancel()
s.recordWriteCommand()
s.recordWriteDispatchWait(time.Since(req.dispatchReadyAt))
@@ -0,0 +1,103 @@
package ublk
import (
"context"
"github.com/seaweedfs/seaweed-block/core/frontend"
"testing"
"time"
)
type deviceBudgetBackend struct {
failingBackend
writeCtx context.Context
syncCtx context.Context
onSync func(context.Context)
}
func (b *deviceBudgetBackend) Write(ctx context.Context, _ int64, p []byte) (int, error) {
b.writeCtx = ctx
return len(p), ctx.Err()
}
func (b *deviceBudgetBackend) Sync(ctx context.Context) error {
b.syncCtx = ctx
if b.onSync != nil {
b.onSync(ctx)
}
return nil
}
type deviceBudgetValueKey struct{}
func TestDeviceWriteKeepsLegacyBudget(t *testing.T) {
for _, op := range []string{"write", "fua", "flush"} {
for _, policy := range []string{"unbounded", "earlier_deadline", "cancel_during_sync"} {
t.Run(op+"/"+policy, func(t *testing.T) {
parent := context.WithValue(context.Background(), deviceBudgetValueKey{}, "caller")
var cancel context.CancelFunc
if policy == "earlier_deadline" {
parent, cancel = context.WithTimeout(parent, time.Second)
} else {
parent, cancel = context.WithCancel(parent)
}
defer cancel()
b := &deviceBudgetBackend{}
if policy == "cancel_during_sync" {
b.onSync = func(ctx context.Context) {
cancel()
if ctx.Err() != context.Canceled {
t.Fatalf("Sync lost caller cancellation: %v", ctx.Err())
}
}
}
start := time.Now()
r := request{op: ioOpWrite, nrSectors: 8}
want := int32(4096)
if op == "fua" {
r.flags = ioFlagFUA
}
if op == "flush" {
r = request{op: ioOpFlush}
want = 0
}
if got := newTestHandler(b).handle(parent, r, make([]byte, 4096)); got != want {
t.Fatalf("result=%d want=%d", got, want)
}
if op != "flush" {
if b.writeCtx == nil || !frontend.UsesLegacyWriteBudget(b.writeCtx) {
t.Fatal("Write lost legacy transport marker")
}
deadline, bounded := b.writeCtx.Deadline()
if !bounded || !deadline.After(start) || deadline.After(time.Now().Add(4*time.Second)) {
t.Fatalf("Write deadline=%v bounded=%v", deadline, bounded)
}
if prior, ok := parent.Deadline(); ok && !deadline.Equal(prior) {
t.Fatalf("Write lost earlier deadline: %v want %v", deadline, prior)
}
if policy != "earlier_deadline" && b.writeCtx.Err() != context.Canceled {
t.Fatalf("Write context not released: %v", b.writeCtx.Err())
}
} else if b.writeCtx != nil {
t.Fatal("flush called Write")
}
if op != "write" {
if b.syncCtx == nil {
t.Fatal("Sync not called")
}
if frontend.UsesLegacyWriteBudget(b.syncCtx) {
t.Fatal("Sync inherited Write-only marker")
}
got, gotOK := b.syncCtx.Deadline()
want, wantOK := parent.Deadline()
if gotOK != wantOK || !got.Equal(want) {
t.Fatalf("Sync deadline=%v/%v want caller %v/%v", got, gotOK, want, wantOK)
}
if b.syncCtx.Value(deviceBudgetValueKey{}) != "caller" {
t.Fatal("Sync lost caller values")
}
} else if b.syncCtx != nil {
t.Fatal("plain Write called Sync")
}
})
}
}
}
+3 -1
View File
@@ -148,7 +148,9 @@ func (h handler) serve(ctx context.Context, r request, buf []byte) (result int32
ctx, trace := frontend.BeginDurabilityRequest(ctx, h.backend, kind)
trace.IncludeReceive(received)
defer func() { trace.Finish(result < 0) }()
n, err := h.backend.Write(ctx, int64(offset), data)
writeCtx, cancel := frontend.WithLegacyWriteBudget(ctx, received)
n, err := h.backend.Write(writeCtx, int64(offset), data)
cancel()
if err != nil || n != len(data) {
return errno(syscall.EIO)
}
@@ -0,0 +1,36 @@
package frontend
import (
"fmt"
"time"
)
const walHoldHostMargin = 5 * time.Second
// WALHoldConfig describes the host timeout declared by the operator and the
// maximum time one command may wait for WAL capacity. A target cannot discover
// the initiator's timeout; HostIOTimeout must match the hosts using the volume.
type WALHoldConfig struct {
MaxHold time.Duration
HostIOTimeout time.Duration
}
func DefaultWALHoldConfig() WALHoldConfig {
return WALHoldConfig{MaxHold: 25 * time.Second, HostIOTimeout: 30 * time.Second}
}
// WALHoldConfigError is a startup refusal, not a runtime pressure outcome.
type WALHoldConfigError struct{ Config WALHoldConfig }
func (e *WALHoldConfigError) Error() string {
return fmt.Sprintf("frontend: invalid WAL hold configuration: hold=%s host_io_timeout=%s; require positive hold and hold + 5s <= host_io_timeout", e.Config.MaxHold, e.Config.HostIOTimeout)
}
func (c WALHoldConfig) Validate() error {
// Subtract only after checking the host value. Adding the margin to a
// user-supplied duration could overflow and accept an unsafe configuration.
if c.MaxHold <= 0 || c.HostIOTimeout <= walHoldHostMargin || c.MaxHold > c.HostIOTimeout-walHoldHostMargin {
return &WALHoldConfigError{Config: c}
}
return nil
}
@@ -0,0 +1,54 @@
package frontend
import (
"errors"
"math"
"strings"
"testing"
"time"
)
func TestWALHoldConfigHostTimeoutMargin(t *testing.T) {
cfg := DefaultWALHoldConfig()
if cfg.MaxHold != 25*time.Second || cfg.HostIOTimeout != 30*time.Second {
t.Fatalf("defaults: %+v", cfg)
}
for _, tc := range []struct {
name string
hold, host time.Duration
valid bool
}{
{"default equality", 25 * time.Second, 30 * time.Second, true},
{"raised host", 40 * time.Second, 45 * time.Second, true},
{"lowered host", 10 * time.Second, 15 * time.Second, true},
{"one nanosecond short", 25 * time.Second, 30*time.Second - time.Nanosecond, false},
{"zero hold", 0, 30 * time.Second, false},
{"negative hold", -time.Second, 30 * time.Second, false},
{"zero host", 25 * time.Second, 0, false},
{"negative host", time.Second, -time.Second, false},
{"no room for hold", time.Nanosecond, 5 * time.Second, false},
{"overflow must refuse", time.Duration(math.MaxInt64), 30 * time.Second, false},
{"largest valid", time.Duration(math.MaxInt64) - 5*time.Second, time.Duration(math.MaxInt64), true},
} {
t.Run(tc.name, func(t *testing.T) {
cfg := WALHoldConfig{MaxHold: tc.hold, HostIOTimeout: tc.host}
err := cfg.Validate()
if tc.valid {
if err != nil {
t.Fatal(err)
}
} else {
var invalid *WALHoldConfigError
if !errors.As(err, &invalid) {
t.Fatalf("want typed config refusal, got %v", err)
}
if invalid.Config != cfg {
t.Fatalf("refusal lost supplied configuration: %+v", invalid)
}
if !strings.Contains(err.Error(), "host_io_timeout") {
t.Fatalf("missing operator setting: %v", err)
}
}
})
}
}
@@ -47,3 +47,31 @@ func deadlineCausesOnly(err error) bool {
}
return deadlineCausesOnly(errors.Unwrap(err))
}
// WithBackendWriteBudget lets a durable backend apply its command-wide WAL
// hold policy before installing a legacy internal deadline. Earlier caller
// deadlines and cancellation are always retained.
func WithBackendWriteBudget(ctx context.Context, arrival time.Time, b Backend) (context.Context, context.CancelFunc) {
if budget, ok := b.(interface {
WriteCommandContext(context.Context, time.Time) (context.Context, context.CancelFunc)
}); ok {
return budget.WriteCommandContext(ctx, arrival)
}
return WithWriteBudget(ctx, arrival)
}
type legacyWriteBudgetKey struct{}
// WithLegacyWriteBudget keeps final-error device bridges outside the retryable
// WAL hold policy until their device timeout and no-retry policy are wired.
func WithLegacyWriteBudget(ctx context.Context, arrival time.Time) (context.Context, context.CancelFunc) {
ctx = context.WithValue(ctx, legacyWriteBudgetKey{}, true)
return WithWriteBudget(ctx, arrival)
}
// UsesLegacyWriteBudget reports an explicit transport choice; backends must not
// replace it with the retryable-protocol WAL hold policy.
func UsesLegacyWriteBudget(ctx context.Context) bool {
legacy, _ := ctx.Value(legacyWriteBudgetKey{}).(bool)
return legacy
}
@@ -16,6 +16,7 @@ import (
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore"
"github.com/seaweedfs/seaweed-block/core/frontend/durable"
"github.com/seaweedfs/seaweed-block/core/replication"
"github.com/seaweedfs/seaweed-block/core/storage"
)
// statusRoutes are the status routes and the type each one encodes. The
@@ -28,6 +29,7 @@ var statusRoutes = []struct {
{"/status", "the volume's authority and health projection", reflect.TypeOf(StatusProjection{})},
{"/status/peers", "replication peers of the served volume", reflect.TypeOf(peersStatusBody{})},
{"/status/durable", "durable store state of the served volume", reflect.TypeOf(durableStatusBody{})},
{"/status/wal-hold", "atomic WAL hold observations scoped to this process and store open", reflect.TypeOf(walHoldStatusBody{})},
{"/status/recovery", "the engine's replica projection (only with recovery enabled)", reflect.TypeOf(engine.ReplicaProjection{})},
{"/status/chunk", "chunk store usage of a walstore-chunk volume (only with --chunk-control-endpoint)", reflect.TypeOf(chunkstore.Usage{})},
{"/status/nvme", "NVMe/TCP frontend counters", reflect.TypeOf(NVMeStatus{})},
@@ -36,6 +38,12 @@ var statusRoutes = []struct {
{"/status/frontend-capabilities", "the frontends this host can serve", reflect.TypeOf(FrontendCapabilitiesStatus{})},
}
type walHoldStatusBody struct {
ProcessID string // holder process incarnation
VolumeID string // the served volume
WALHold storage.WALHoldStatus // atomic store-open observations
}
type peersStatusBody struct {
VolumeID string // the served volume
ReplicaID string // this host's replica
@@ -189,6 +189,8 @@ const (
// adds G9A control-plane vocabulary so operators/tests do not infer
// replica readiness from authority movement.
type StatusProjection struct {
Degraded bool // WAL reclaim stalled for at least five seconds; diagnostic, not an authority or readiness change
DegradedReason string `json:",omitempty"`
frontend.Projection
// Version is the build revision plus modified flag, matching master product_revision.
// Unknown provenance does not prove that two builds are equal.
@@ -396,6 +398,8 @@ func (s *StatusServer) Start(addr string) (string, error) {
mux := http.NewServeMux()
registerLabHeapProfile(mux)
mux.HandleFunc("/status", s.handleStatus)
mux.HandleFunc("/metrics", s.handleWALHoldMetrics)
mux.HandleFunc("/status/wal-hold", s.handleWALHoldStatus)
mux.HandleFunc("/status/peers", s.handleStatusPeers)
mux.HandleFunc("/status/durable", s.handleStatusDurable)
mux.HandleFunc("/status/nvme", s.handleStatusNVMe)
@@ -611,6 +615,10 @@ func (s *StatusServer) statusProjection() StatusProjection {
for _, st := range src.DurableStatuses() {
if st.VolumeID == p.VolumeID {
p.Warnings = append(p.Warnings, st.Warnings...)
if st.Degraded {
p.Degraded = true
p.DegradedReason = "wal_reclaim_stalled"
}
}
}
// The frontend readiness rule: the backend's one "may serve" function decides; an
@@ -0,0 +1,79 @@
package volume
import (
"encoding/json"
"fmt"
"net/http"
"github.com/seaweedfs/seaweed-block/core/storage"
)
// This read-only route shares the status listener's access policy. There are
// no per-request or per-LBA labels; counters are scoped to a volume's open.
func (s *StatusServer) handleWALHoldMetrics(w http.ResponseWriter, r *http.Request) {
s.serveWALHold(w, r, true)
}
func (s *StatusServer) handleWALHoldStatus(w http.ResponseWriter, r *http.Request) {
s.serveWALHold(w, r, false)
}
func (s *StatusServer) serveWALHold(w http.ResponseWriter, r *http.Request, metrics bool) {
if r.Method != http.MethodGet {
http.Error(w, "metrics requires GET", http.StatusMethodNotAllowed)
return
}
if !s.externalAccessAllowed() && !isLoopbackRemote(r.RemoteAddr) {
http.Error(w, "metrics restricted to loopback", http.StatusForbidden)
return
}
id := r.URL.Query().Get("volume")
if id == "" {
http.Error(w, "missing volume", http.StatusBadRequest)
return
}
p := s.authorityProjection()
if id != p.VolumeID {
http.NotFound(w, r)
return
}
s.mu.Lock()
src := s.durableSource
s.mu.Unlock()
reporter, ok := src.(interface {
WALHoldStatuses() map[string]storage.WALHoldStatus
})
if !ok {
http.NotFound(w, r)
return
}
st, ok := reporter.WALHoldStatuses()[id]
if !ok {
http.NotFound(w, r)
return
}
if !metrics {
processID := ""
if host, ok := s.view.probe.(*Host); ok && host != nil {
processID = host.incarnation
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(struct {
ProcessID string
VolumeID string
WALHold storage.WALHoldStatus
}{processID, id, st})
return
}
degraded := 0
if st.Degraded {
degraded = 1
}
w.Header().Set("Content-Type", "text/plain; version=0.0.4; charset=utf-8")
fmt.Fprintf(w, "swblock_wal_reclaim_degraded{volume=%q} %d\n", id, degraded)
fmt.Fprintf(w, "swblock_wal_reclaimed_bytes_total{volume=%q} %d\n", id, st.ReclaimedBytes)
fmt.Fprintf(w, "swblock_wal_extent_bytes_total{volume=%q} %d\n", id, st.ExtentBytes)
fmt.Fprintf(w, "swblock_wal_hold_active{volume=%q} %d\n", id, st.ActiveWaiters)
fmt.Fprintf(w, "swblock_wal_hold_commands_total{volume=%q} %d\n", id, st.Commands)
fmt.Fprintf(w, "swblock_wal_reclaim_stalled_total{volume=%q} %d\n", id, st.StallAnswers)
fmt.Fprintf(w, "swblock_wal_hold_cap_total{volume=%q} %d\n", id, st.CapAnswers)
fmt.Fprintf(w, "swblock_wal_hold_wait_nanoseconds_total{volume=%q} %d\n", id, st.WaitNanos)
}
@@ -0,0 +1,72 @@
package volume
import (
"net/http/httptest"
"strings"
"testing"
"github.com/seaweedfs/seaweed-block/core/frontend/durable"
"github.com/seaweedfs/seaweed-block/core/storage"
)
type holdMetricsSource struct {
stubDurableStatusSource
holds map[string]storage.WALHoldStatus
}
func (s holdMetricsSource) WALHoldStatuses() map[string]storage.WALHoldStatus { return s.holds }
type atomicOnlyHoldSource struct{ holdMetricsSource }
func (atomicOnlyHoldSource) DurableStatuses() []durable.VolumeStatus {
panic("metrics must not read locked frontiers")
}
func TestWALHoldMetricsAtomicSourceAndAccess(t *testing.T) {
s := NewStatusServer(NewAdapterProjectionView(stubProjector{}, "v1", "r1", nil))
s.SetDurableStatusSource(atomicOnlyHoldSource{holdMetricsSource{holds: map[string]storage.WALHoldStatus{"v1": {Degraded: true, ActiveWaiters: 1, Commands: 3, StallAnswers: 2, CapAnswers: 1, WaitNanos: 123}}}})
for _, tc := range []struct {
query, remote string
want int
}{
{"?volume=v1", "127.0.0.1:9000", 200}, {"?volume=other", "127.0.0.1:9000", 404}, {"", "127.0.0.1:9000", 400}, {"?volume=v1", "192.0.2.1:9000", 403},
} {
r := httptest.NewRequest("GET", "/metrics"+tc.query, nil)
r.RemoteAddr = tc.remote
w := httptest.NewRecorder()
s.handleWALHoldMetrics(w, r)
if w.Code != tc.want {
t.Fatalf("%s %s status%d want%d", tc.remote, tc.query, w.Code, tc.want)
}
if tc.want == 200 && !strings.Contains(w.Body.String(), "swblock_wal_reclaim_degraded{volume=\"v1\"} 1\n") {
t.Fatalf("missing degraded metric: %s", w.Body.String())
}
}
}
func TestWALHoldDegradedDoesNotChangeReadiness(t *testing.T) {
s := NewStatusServer(NewAdapterProjectionView(stubProjector{}, "v1", "r1", nil))
source := holdMetricsSource{stubDurableStatusSource: stubDurableStatusSource{vols: []durable.VolumeStatus{{VolumeID: "v1", Operational: true}}}}
s.SetDurableStatusSource(source)
before := s.statusProjection()
source.vols[0].Degraded = true
after := s.statusProjection()
if !after.Degraded || after.DegradedReason != "wal_reclaim_stalled" {
t.Fatalf("degraded status: %+v", after)
}
if after.FrontendPrimaryReady != before.FrontendPrimaryReady || after.Healthy != before.Healthy {
t.Fatal("diagnostic changed authority/readiness")
}
}
func TestWALHoldAtomicStatusDoesNotReadFrontiers(t *testing.T) {
s := NewStatusServer(NewAdapterProjectionView(stubProjector{}, "v1", "r1", nil))
s.SetDurableStatusSource(atomicOnlyHoldSource{holdMetricsSource{holds: map[string]storage.WALHoldStatus{"v1": {Degraded: true, ReclaimedBytes: 4096}}}})
r := httptest.NewRequest("GET", "/status/wal-hold?volume=v1", nil)
r.RemoteAddr = "127.0.0.1:9000"
w := httptest.NewRecorder()
s.handleWALHoldStatus(w, r)
if w.Code != 200 || !strings.Contains(w.Body.String(), "\"Degraded\":true") || !strings.Contains(w.Body.String(), "\"ReclaimedBytes\":4096") {
t.Fatalf("atomic status: %d %s", w.Code, w.Body.String())
}
}
@@ -35,7 +35,7 @@ var walStoreMethods = map[string]string{
"Coverage": "read (atomic local bitmap coverage and chunk position)",
"AllBlocks": "read", "AppliedLSNs": "read", "CanSeedChunkFrontier": "read (the seed precondition, no write)", "BlockSize": "read", "StoreID": "read (the superblock UUID)", "ChunkBlocks": "read (immutable local map shape)", "ChunkStateMarker": "read (the descriptor's chunk-state marker)", "Boundaries": "read", "CheckpointLSN": "read",
"CheckpointLSNForPOC": "read", "CheckpointPersistence": "read", "ChunkMapStatsV3": "read", "DataSyncPolicy": "read",
"DurabilityLatency": "read", "ExtentDrainHeld": "read", "FlushCount": "read", "FlusherInstrumentation": "read", "HolesSuspected": "read", "ReclaimProgress": "read",
"DurabilityLatency": "read", "ExtentDrainHeld": "read", "FlushCount": "read", "FlusherInstrumentation": "read", "HolesSuspected": "read", "ReclaimProgress": "read", "WALHoldStatus": "read (atomic diagnostic hold metrics)",
"InstalledBaseLSN": "read", "LayoutIdentity": "read", "NextLSN": "read", "NumBlocks": "read",
"OwnerChunkAttachDurableV3": "read", "Read": "read", "ReadContext": "read", "RecoveryMode": "read",
"RecoveryRetentionLSNs": "read", "RecoveryWarnings": "read", "ScanLBAs": "read", "WALCapacityBytes": "read",
+134 -94
View File
@@ -4,6 +4,7 @@ import (
"context"
"errors"
"fmt"
"sync"
"sync/atomic"
"time"
)
@@ -34,13 +35,19 @@ 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
hardBlocked atomic.Bool // last head pressure sample; retained until a head observes capacity
queueMu sync.Mutex
first, last *walAdmissionTicket
active *walAdmissionTicket // an admitted append cannot be preempted
nextOrder atomic.Uint64
headVersion uint64
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
@@ -109,100 +116,127 @@ func (a *walAdmission) acquireContext(ctx context.Context, timeout time.Duration
if fault := a.terminalFault(); fault != nil {
return fault
}
return admissionContextError(err)
return a.commandWaitError(ctx, admissionContextError(err))
}
deadline := time.NewTimer(timeout)
defer deadline.Stop()
pressure, err := sample()
if err != nil {
return err
hold := admissionHold(ctx, a)
if hold != nil {
started := time.Now()
defer func() { hold.waitNanos += time.Since(started).Nanoseconds(); hold.endWait() }()
}
deadline := &time.Timer{}
if timeout > 0 || hold == nil {
deadline = time.NewTimer(timeout)
defer deadline.Stop()
}
ticket := a.enqueueTicket(admissionArrival(ctx, a))
granted := false
defer func() {
if !granted {
a.removeTicket(ticket)
}
}()
// Hard watermark: wait for flusher to drain before competing
// for the semaphore.
if pressure >= a.hardMark {
a.notifyFn()
hardStart := time.Now()
for {
pressure, err = sample()
if err != nil {
return err
}
if pressure < a.hardMark {
break
}
if err := a.terminalFault(); err != nil {
a.hardPressureWaitNs.Add(time.Since(hardStart).Nanoseconds())
return err
}
if !contextual && a.closedFn() {
a.hardPressureWaitNs.Add(time.Since(hardStart).Nanoseconds())
return errVolumeClosed
retry:
for {
if err := a.waitForTicket(ctx, deadline, ticket, contextual); err != nil {
return err
}
first, _, version := a.headState(ticket)
if !first {
continue
}
pressure, err := sample()
if err != nil {
return err
}
a.hardBlocked.Store(pressure >= a.hardMark)
// Hard watermark: wait for flusher to drain before competing
// for the semaphore.
if pressure >= a.hardMark {
if hold != nil {
hold.start()
}
a.notifyFn()
hardStart := time.Now()
for {
if first, _, current := a.headState(ticket); !first || current != version {
a.hardPressureWaitNs.Add(time.Since(hardStart).Nanoseconds())
continue retry
}
if hold != nil {
if err := hold.check(); err != nil {
return err
}
}
pressure, err = sample()
if err != nil {
return err
}
a.hardBlocked.Store(pressure >= a.hardMark)
if pressure < a.hardMark {
break
}
if err := a.terminalFault(); err != nil {
a.hardPressureWaitNs.Add(time.Since(hardStart).Nanoseconds())
return err
}
if !contextual && a.closedFn() {
a.hardPressureWaitNs.Add(time.Since(hardStart).Nanoseconds())
return errVolumeClosed
}
a.notifyFn()
select {
case <-ctx.Done():
a.hardPressureWaitNs.Add(time.Since(hardStart).Nanoseconds())
if err := a.terminalFault(); err != nil {
return err
}
return a.commandWaitError(ctx, admissionContextError(ctx.Err()))
case <-deadline.C:
a.hardPressureWaitNs.Add(time.Since(hardStart).Nanoseconds())
if err := a.terminalFault(); err != nil {
return err
}
return a.commandWaitError(ctx, ErrWALPressureTimeout)
default:
}
a.sleepFn(2 * time.Millisecond)
}
a.hardPressureWaitNs.Add(time.Since(hardStart).Nanoseconds())
// Pressure dropped — fall through to semaphore acquisition.
} else if pressure >= a.softMark {
// Soft watermark: small delay to desynchronize writer herd.
a.notifyFn()
scale := (pressure - a.softMark) / (a.hardMark - a.softMark)
if scale > 1 {
scale = 1
}
// Scale: softMark→0ms, hardMark→5ms.
delay := time.Duration(scale * 5 * float64(time.Millisecond))
if delay > 0 {
softStart := time.Now()
a.sleepFn(delay)
a.softPressureWaitNs.Add(time.Since(softStart).Nanoseconds())
}
}
// Revalidate queue authority at the capacity grant: an older command's
// next batch may have entered while this invocation sampled or slept.
if a.tryGrantTicket(ticket, version) {
granted = true
return nil
}
if first, _, current := a.headState(ticket); first && current == version {
// A semaphore-only waiter still yields to cancellation, Close and
// terminal-fault sampling; it must not busy-spin on a full token set.
select {
case <-ctx.Done():
a.hardPressureWaitNs.Add(time.Since(hardStart).Nanoseconds())
if err := a.terminalFault(); err != nil {
return err
}
return admissionContextError(ctx.Err())
return a.commandWaitError(ctx, admissionContextError(ctx.Err()))
case <-deadline.C:
a.hardPressureWaitNs.Add(time.Since(hardStart).Nanoseconds())
if err := a.terminalFault(); err != nil {
return err
}
return ErrWALPressureTimeout
default:
}
a.sleepFn(2 * time.Millisecond)
}
a.hardPressureWaitNs.Add(time.Since(hardStart).Nanoseconds())
// Pressure dropped — fall through to semaphore acquisition.
} else if pressure >= a.softMark {
// Soft watermark: small delay to desynchronize writer herd.
a.notifyFn()
scale := (pressure - a.softMark) / (a.hardMark - a.softMark)
if scale > 1 {
scale = 1
}
// Scale: softMark→0ms, hardMark→5ms.
delay := time.Duration(scale * 5 * float64(time.Millisecond))
if delay > 0 {
softStart := time.Now()
a.sleepFn(delay)
a.softPressureWaitNs.Add(time.Since(softStart).Nanoseconds())
}
}
// Acquire semaphore slot using the same deadline.
select {
case a.sem <- struct{}{}:
return nil
default:
}
closeTick := time.NewTicker(5 * time.Millisecond)
defer closeTick.Stop()
for {
select {
case a.sem <- struct{}{}:
return nil
case <-ctx.Done():
if err := a.terminalFault(); err != nil {
return err
}
return admissionContextError(ctx.Err())
case <-deadline.C:
if err := a.terminalFault(); err != nil {
return err
}
return ErrWALPressureTimeout
case <-closeTick.C:
if contextual {
if _, err := sample(); err != nil {
return err
}
return a.commandWaitError(ctx, ErrWALPressureTimeout)
case <-time.After(5 * time.Millisecond):
}
if err := a.terminalFault(); err != nil {
return err
@@ -215,7 +249,13 @@ 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.active = nil
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,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
}
@@ -0,0 +1,197 @@
package storage
import (
"context"
"sync"
"sync/atomic"
"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)
}
}
// A competing real append must not consume reserved room between admission and
// pwrite. Checking TryLock only at pwrite misses a release followed by reacquire.
func TestWALAdmissionFastReservationExcludesCompetingAppend(t *testing.T) {
// Even store cleanup can block after a lock regression. The parent kills
// and joins this child at its own bound rather than hanging the package.
if !inBoundedChild(t) {
if err := runBoundedChild(t.Name(), 20*time.Second); err != nil {
t.Fatal(err)
}
return
}
for _, batch := range []bool{false, true} {
t.Run(map[bool]string{false: "write", true: "batch"}[batch], func(t *testing.T) {
s := admissionPressureV3(t, 0)
reserved, release, competingAdmitted := make(chan struct{}), make(chan struct{}), make(chan struct{})
var calls atomic.Int32
s.testAfterAdmit = func() {
switch calls.Add(1) {
case 1:
close(reserved)
<-release
case 2:
close(competingAdmitted)
}
}
type result struct {
lsn uint64
err error
}
first, second := make(chan result, 1), make(chan result, 1)
var releaseOnce sync.Once
unblock := func() { releaseOnce.Do(func() { close(release) }) }
join := func(name string, done <-chan result) result {
select {
case got := <-done:
return got
case <-time.After(2 * time.Second):
t.Errorf("%s append did not finish within 2s after release", name)
return result{}
}
}
firstJoined, secondStarted, secondJoined := false, false, false
defer func() {
unblock()
if !firstJoined {
join("first", first)
}
if secondStarted && !secondJoined {
join("competing", second)
}
}()
go func() {
if batch {
lsns, err := s.WriteBatch(0, [][]byte{blk(1), blk(2)})
var lsn uint64
if len(lsns) > 0 {
lsn = uint64(lsns[0])
}
first <- result{lsn, err}
} else {
lsn, err := s.Write(0, blk(1))
first <- result{uint64(lsn), err}
}
}()
select {
case <-reserved:
case got := <-first:
firstJoined = true
t.Errorf("first append returned before reservation hook: %+v", got)
return
case <-time.After(2 * time.Second):
t.Error("first append did not enter reservation hook within 2s")
return
}
competingStarted := make(chan struct{})
secondStarted = true
go func() { close(competingStarted); lsn, err := s.Write(8, blk(8)); second <- result{uint64(lsn), err} }()
select {
case <-competingStarted:
case <-time.After(2 * time.Second):
t.Error("competing append did not start within 2s")
return
}
// A real mutex wait is not a durably blocked synctest operation. Keep the
// competing append scheduled against the paused reservation for a bounded
// real interval; the detached-reservation mutant signals admitted instead.
overtook := false
select {
case <-competingAdmitted:
overtook = true
case <-time.After(100 * time.Millisecond):
}
unblock()
a, b := join("first", first), join("competing", second)
firstJoined, secondJoined = true, true
if overtook || a.err != nil || b.err != nil || a.lsn >= b.lsn {
t.Fatalf("reservation continuity: overtook=%v first=%+v competitor=%+v", overtook, a, b)
}
})
}
}
@@ -0,0 +1,168 @@
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 {
ready chan struct{}
prev, next *walAdmissionTicket
arrival time.Time
order uint64
}
func (a *walAdmission) newCommandOrder() uint64 { return a.nextOrder.Add(1) }
// Pending batches retain their command arrival order. An append that already
// owns capacity remains pinned at the head until its store call returns.
func (a *walAdmission) enqueueTicket(arrival *walWriteArrival) *walAdmissionTicket {
a.queueMu.Lock()
defer a.queueMu.Unlock()
t := &walAdmissionTicket{arrival: time.Now(), ready: make(chan struct{}, 1)}
if arrival != nil {
t.arrival, t.order = arrival.arrival, arrival.order
} else {
t.order = a.newCommandOrder()
}
priorFirst := a.first
before := a.last
for before != nil && before != a.active && (t.arrival.Before(before.arrival) || (t.arrival.Equal(before.arrival) && t.order < before.order)) {
before = before.prev
}
t.prev = before
if before == nil {
t.next = a.first
a.first = t
} else {
t.next = before.next
before.next = t
}
if t.next != nil {
t.next.prev = t
} else {
a.last = t
}
if a.first != priorFirst {
a.notifyHeadLocked()
}
return t
}
func (a *walAdmission) notifyHeadLocked() {
a.headVersion++
if a.first != nil {
// Only the new head needs to wake. A buffered notification also covers
// a previously displaced head without waking every queued command.
select {
case a.first.ready <- struct{}{}:
default:
}
}
}
func (a *walAdmission) headState(t *walAdmissionTicket) (bool, <-chan struct{}, uint64) {
a.queueMu.Lock()
defer a.queueMu.Unlock()
return a.first == t, t.ready, a.headVersion
}
func (a *walAdmission) tryGrantTicket(t *walAdmissionTicket, version uint64) bool {
a.queueMu.Lock()
defer a.queueMu.Unlock()
if a.first != t || a.active != nil || a.headVersion != version {
return false
}
select {
case a.sem <- struct{}{}:
a.active = t
return true
default:
return false
}
}
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
a.notifyHeadLocked()
}
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()
hold := admissionHold(ctx, a)
for {
if hold != nil {
if a.hardBlocked.Load() {
hold.start()
} else {
hold.endWait()
}
if err := hold.check(); err != nil {
return err
}
}
first, changed, _ := a.headState(t)
if first {
if err := ctx.Err(); err != nil {
return a.commandWaitError(ctx, admissionContextError(err))
}
return nil
}
select {
case <-changed:
continue
case <-ctx.Done():
if fault := a.terminalFault(); fault != nil {
return fault
}
return a.commandWaitError(ctx, admissionContextError(ctx.Err()))
case <-deadline.C:
if fault := a.terminalFault(); fault != nil {
return fault
}
return a.commandWaitError(ctx, ErrWALPressureTimeout)
case <-tick.C:
if fault := a.terminalFault(); fault != nil {
return fault
}
if !contextual && a.closedFn() {
return errVolumeClosed
}
}
}
}
func (a *walAdmission) commandWaitError(ctx context.Context, fallback error) error {
if fault := a.terminalFault(); fault != nil {
return fault
}
if ctx.Err() == context.Canceled {
return context.Canceled
}
if h := admissionHold(ctx, a); h != nil {
if err := h.check(); err != nil {
return err
}
}
return fallback
}
@@ -0,0 +1,376 @@
package storage
import (
"bytes"
"context"
"path/filepath"
"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} }()
}
// 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()
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)
}
}
})
}
// An older command returns for its second batch while a younger command is
// already waiting on hard WAL pressure. Reclaim must serve the older batch first.
func TestWALHoldOlderBatchReentersBeforeYoungerPressureWaiter(t *testing.T) {
for _, legacy := range []bool{false, true} {
t.Run(map[bool]string{false: "hold", true: "legacy"}[legacy], func(t *testing.T) {
s := admissionPressureV3(t, 14)
synctest.Test(t, func(t *testing.T) {
older, cancelOld := WithWALWriteHold(context.Background(), s, time.Now(), 25*time.Second, false)
if legacy {
older = WithWALWriteArrival(context.Background(), s, time.Now())
}
defer cancelOld()
defer FinishWALWriteHold(older, nil)
first, err := s.WriteContext(older, 16, blk(16))
if err != nil {
t.Fatal(err)
}
time.Sleep(time.Millisecond)
younger, cancelYoung := WithWALWriteHold(context.Background(), s, time.Now(), 25*time.Second, false)
if legacy {
younger = WithWALWriteArrival(context.Background(), s, time.Now())
}
defer cancelYoung()
defer FinishWALWriteHold(younger, nil)
type result struct {
lsn uint64
err error
}
youngDone, oldDone := make(chan result, 1), make(chan result, 1)
go func() { l, e := s.WriteContext(younger, 18, blk(18)); youngDone <- result{l, e} }()
synctest.Wait()
go func() { l, e := s.WriteContext(older, 17, blk(17)); oldDone <- result{l, e} }()
synctest.Wait()
if err := s.flusher.flushOnce(); err != nil {
t.Fatal(err)
}
synctest.Wait()
old, young := <-oldDone, <-youngDone
if old.err != nil || young.err != nil || old.lsn != first+1 || young.lsn != first+2 {
t.Fatalf("older multi-batch command was passed: first=%d older=%+v younger=%+v", first, old, young)
}
for _, i := range []uint32{16, 17, 18} {
got, e := s.Read(i)
if e != nil || !bytes.Equal(got, blk(byte(i))) {
t.Fatalf("readback %d: %v", i, e)
}
}
})
})
}
}
func TestWALHoldLargeWriteBatchesKeepCommandArrivalUnderPressure(t *testing.T) {
s, err := createMappedWALStoreV3ForTest(filepath.Join(t.TempDir(), "volume"), 512, 4096, 1<<20, WModeStrict, 16)
if err != nil {
t.Fatal(err)
}
defer s.Close()
s.DisableAutoFlushForRecoveryTest()
// 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)
}
}
synctest.Test(t, func(t *testing.T) {
older, cancelOld := WithWALWriteHold(context.Background(), s, time.Now(), 25*time.Second, false)
defer cancelOld()
defer FinishWALWriteHold(older, nil)
blocks := make([][]byte, 16)
for i := range blocks {
blocks[i] = blk(byte(i + 1))
}
first, err := s.WriteBatchContext(older, 256, blocks)
if err != nil {
t.Fatal(err)
}
time.Sleep(time.Millisecond)
younger, cancelYoung := WithWALWriteHold(context.Background(), s, time.Now(), 25*time.Second, false)
defer cancelYoung()
defer FinishWALWriteHold(younger, nil)
type answer struct {
lsn uint64
err error
}
youngDone, oldDone := make(chan answer, 1), make(chan answer, 1)
go func() { l, e := s.WriteContext(younger, 300, blk(99)); youngDone <- answer{l, e} }()
synctest.Wait()
go func() {
ls, e := s.WriteBatchContext(older, 272, blocks)
var last uint64
if len(ls) > 0 {
last = ls[len(ls)-1]
}
oldDone <- answer{last, e}
}()
synctest.Wait()
if s.NextLSN() != first[len(first)-1]+1 {
t.Fatal("pressure wait did not retain both commands")
}
if err := s.flusher.flushOnce(); err != nil {
t.Fatal(err)
}
synctest.Wait()
old, young := <-oldDone, <-youngDone
if old.err != nil || young.err != nil || old.lsn != first[len(first)-1]+16 || young.lsn != old.lsn+1 {
t.Fatalf("large write overtaken: first=%v old=%+v young=%+v", first, old, young)
}
for i := 0; i < 32; i++ {
got, e := s.Read(uint32(256 + i))
if e != nil || !bytes.Equal(got, blocks[i%16]) {
t.Fatalf("large readback %d: %v", i, e)
}
}
})
}
func TestWALAdmissionResamplesAfterOlderBatchChangesHead(t *testing.T) {
s := admissionPressureV3(t, 0)
synctest.Test(t, func(t *testing.T) {
older, co := WithWALWriteHold(context.Background(), s, time.Now(), 25*time.Second, false)
defer co()
time.Sleep(time.Millisecond)
younger, cy := WithWALWriteHold(context.Background(), s, time.Now(), 25*time.Second, false)
defer cy()
sampled, resume := make(chan struct{}), make(chan struct{})
var once sync.Once
release := func() { once.Do(func() { close(resume) }) }
defer func() { release(); synctest.Wait() }()
var samples atomic.Int32
done := make(chan error, 1)
go func() {
err := s.admission.acquireContext(younger, time.Minute, func() (float64, error) {
if samples.Add(1) == 1 {
close(sampled)
<-resume
}
return 0, nil
})
if err == nil {
s.admission.Release()
}
done <- err
}()
<-sampled
if err := s.admission.acquireContext(older, time.Minute, func() (float64, error) { return 0, nil }); err != nil {
t.Fatal(err)
}
s.admission.Release()
release()
synctest.Wait()
if err := <-done; err != nil {
t.Fatal(err)
}
if samples.Load() < 2 {
t.Fatal("capacity granted from a sample predating an intervening append")
}
})
}
func TestWALAdmissionActiveAppendPinsReorderedCancellation(t *testing.T) {
s := admissionPressureV3(t, 0)
synctest.Test(t, func(t *testing.T) {
older := WithWALWriteArrival(context.Background(), s, time.Now())
older, cancelOld := context.WithCancel(older)
defer cancelOld()
time.Sleep(time.Millisecond)
active := WithWALWriteArrival(context.Background(), s, time.Now())
if err := s.admission.acquireContext(active, time.Minute, nil); err != nil {
t.Fatal(err)
}
released := false
younger, cancelYoung := context.WithCancel(context.Background())
defer cancelYoung()
oldDone, youngDone := make(chan error, 1), make(chan error, 1)
defer func() {
cancelOld()
cancelYoung()
if !released {
s.admission.Release()
}
synctest.Wait()
}()
go func() {
err := s.admission.acquireContext(younger, time.Minute, nil)
if err == nil {
s.admission.Release()
}
youngDone <- err
}()
synctest.Wait()
go func() {
err := s.admission.acquireContext(older, time.Minute, nil)
if err == nil {
s.admission.Release()
}
oldDone <- err
}()
synctest.Wait()
// An older re-entry may reorder pending tickets, never the append that has
// already been admitted. Cancelling that re-entry must retain the live head.
a := s.admission
a.queueMu.Lock()
pinned := a.first == a.active && a.first != nil && a.first.next != nil && a.first.next.order == admissionArrival(older, a).order
a.queueMu.Unlock()
if !pinned {
t.Fatal("older re-entry displaced the active append")
}
cancelOld()
synctest.Wait()
if err := <-oldDone; err != context.Canceled {
t.Fatalf("cancelled re-entry: %v", err)
}
select {
case err := <-youngDone:
t.Fatalf("younger append passed active head: %v", err)
default:
}
a.queueMu.Lock()
pinned = a.first == a.active && a.first.next == a.last
a.queueMu.Unlock()
if !pinned {
t.Fatal("reordered cancellation damaged the active head")
}
a.Release()
released = true
synctest.Wait()
if err := <-youngDone; err != nil {
t.Fatal(err)
}
if err := a.Acquire(time.Second); err != nil {
t.Fatalf("queue not drained: %v", err)
}
a.Release()
})
}
@@ -0,0 +1,179 @@
package storage
import (
"context"
"errors"
"testing"
"testing/synctest"
"time"
)
// Exercise the real v3 append path twice with one command, rather than the
// legacy wrapper: time outside admission and prior batches consume its cap.
func TestWALHoldRealWALAgedBatchKeepsCapAndEarlierDeadline(t *testing.T) {
for _, earlier := range []bool{false, true} {
t.Run(map[bool]string{false: "arrival_cap", true: "earlier_caller"}[earlier], func(t *testing.T) {
s := admissionPressureV3(t, 14)
synctest.Test(t, func(t *testing.T) {
arrival := time.Now()
parent, stopParent := context.WithCancel(context.Background())
if earlier {
stopParent()
parent, stopParent = context.WithDeadline(context.Background(), arrival.Add(23*time.Second))
}
defer stopParent()
ctx, cancel := WithWALWriteHold(parent, s, arrival, 25*time.Second, false)
defer cancel()
first, err := s.WriteContext(ctx, 16, blk(16))
if err != nil {
t.Fatal(err)
}
time.Sleep(21 * time.Second)
stop, joined := make(chan struct{}), make(chan struct{})
go func() {
defer close(joined)
// This producer ends independently of the write, even if a cap regresses.
for i := 0; i < 8; i++ {
select {
case <-stop:
return
case <-time.After(time.Second):
s.flusher.instr.extentWriteBytes.Add(4096)
}
}
}()
// Independently bounded cleanup also catches a broken admission deadline.
watchdogDone := make(chan struct{})
go func() {
defer close(watchdogDone)
select {
case <-stop:
return
case <-time.After(10 * time.Second):
cancel()
}
}()
defer func() { close(stop); cancel(); <-joined; <-watchdogDone }()
_, err = s.WriteContext(ctx, 17, blk(17))
FinishWALWriteHold(ctx, err)
want := 25 * time.Second
if earlier {
want = 23 * time.Second
if !errors.Is(err, ErrWALPressureTimeout) || errors.Is(err, ErrWALHoldCap) {
t.Fatalf("earlier caller outcome: %v", err)
}
} else if !errors.Is(err, ErrWALHoldCap) {
t.Fatalf("cap outcome: %v", err)
}
if elapsed := time.Since(arrival); elapsed < want || elapsed > want+20*time.Millisecond {
t.Fatalf("second batch returned at %s want %s", elapsed, want)
}
if s.NextLSN() != first+1 {
t.Fatal("expired suffix appended")
}
})
})
}
}
// A nonzero counter is historical evidence, not continuing progress. Once it
// stops changing, the actual held append must get only one renewed window.
func TestWALHoldSamplerFixedNonzeroProgressExpires(t *testing.T) {
for _, kind := range []string{"reclaim", "extent"} {
t.Run(kind, func(t *testing.T) {
s := admissionPressureV3(t, 15)
synctest.Test(t, func(t *testing.T) {
ctx, cancel := WithWALWriteHold(context.Background(), s, time.Now(), 25*time.Second, false)
defer cancel()
start := time.Now()
done := make(chan error, 1)
go func() { _, err := s.WriteContext(ctx, 16, blk(16)); FinishWALWriteHold(ctx, err); done <- err }()
synctest.Wait()
time.Sleep(4 * time.Second)
if kind == "reclaim" {
s.flusher.instr.reclaimedBytes.Add(4096)
} else {
s.flusher.instr.extentWriteBytes.Add(4096)
}
// This watchdog is independent of the counter and of the hold outcome.
stop, joined := make(chan struct{}), make(chan struct{})
go func() {
defer close(joined)
select {
case <-stop:
case <-time.After(8 * time.Second):
cancel()
}
}()
defer func() { close(stop); cancel(); <-joined }()
time.Sleep(2 * time.Second)
select {
case err := <-done:
t.Fatalf("progress did not renew once: %v", err)
default:
}
err := <-done
if elapsed := time.Since(start); !errors.Is(err, ErrWALReclaimStalled) || elapsed < 9*time.Second || elapsed > 9*time.Second+20*time.Millisecond {
t.Fatalf("fixed %s sample: elapsed=%s error=%v; want stall after 5s silence", kind, elapsed, err)
}
if s.WALHoldStatus().ActiveWaiters != 0 {
t.Fatal("hold waiter leaked")
}
})
})
}
}
// Drive the actual atomic sampler used by a pressure-held store append.
func TestWALHoldSamplerRenewsOnlySuccessfulByteProgress(t *testing.T) {
for _, kind := range []string{"reclaim", "extent", "unchanged", "phase", "empty_cycle", "failed_write"} {
t.Run(kind, func(t *testing.T) {
s := admissionPressureV3(t, 15)
synctest.Test(t, func(t *testing.T) {
ctx, cancel := WithWALWriteHold(context.Background(), s, time.Now(), 25*time.Second, false)
defer cancel()
done := make(chan error, 1)
go func() { _, err := s.WriteContext(ctx, 16, blk(16)); FinishWALWriteHold(ctx, err); done <- err }()
synctest.Wait()
time.Sleep(4 * time.Second)
switch kind {
case "reclaim":
s.flusher.instr.reclaimedBytes.Add(4096)
case "extent":
s.flusher.instr.extentWriteBytes.Add(4096)
case "phase":
s.flusher.instr.phase.Store(int32(flusherWriting))
case "empty_cycle":
s.flusher.instr.cyclesStarted.Add(1)
s.flusher.instr.cyclesSucceeded.Add(1)
case "failed_write":
s.flusher.instr.cyclesFailed.Add(1)
s.flusher.instr.checkpointFailures.Add(1)
}
time.Sleep(2 * time.Second)
positive := kind == "reclaim" || kind == "extent"
select {
case err := <-done:
if positive || !errors.Is(err, ErrWALReclaimStalled) {
t.Fatalf("at 6s kind=%s outcome=%v", kind, err)
}
default:
if !positive {
cancel()
synctest.Wait()
<-done
t.Fatalf("%s renewed the stalled window", kind)
}
cancel()
synctest.Wait()
if err := <-done; !errors.Is(err, context.Canceled) {
t.Fatalf("joined hold=%v", err)
}
}
if s.WALHoldStatus().ActiveWaiters != 0 {
t.Fatal("hold waiter leaked")
}
})
})
}
}
@@ -0,0 +1,58 @@
package storage
import "sync/atomic"
// WALHoldStatus is diagnostic back-pressure health, not authority or admission.
// Counters are cumulative for this open; changing them grants no capacity.
type WALHoldStatus struct {
OpenSequence uint64 // process-local store-open observation scope; compare with the status process identity
ReclaimedBytes uint64
ExtentBytes uint64
Degraded bool
Reason string
ActiveWaiters int64
Commands uint64
StallAnswers uint64
CapAnswers uint64
WaitNanos uint64
LastWaitNanos int64
LastReason string
FlusherPhase string
}
type walHoldEvent struct {
Reason string
WaitNanos int64
}
var nextWALHoldScope atomic.Uint64
type walHoldInstrumentation struct {
scope atomic.Uint64
active atomic.Int64
commands, stalls, caps, waitNanos atomic.Uint64
degraded atomic.Pointer[ReclaimProgress]
last atomic.Pointer[walHoldEvent]
}
func (s *WALStore) WALHoldStatus() WALHoldStatus {
scope := s.walHold.scope.Load()
if scope == 0 {
s.walHold.scope.CompareAndSwap(0, nextWALHoldScope.Add(1))
scope = s.walHold.scope.Load()
}
p := s.ReclaimProgress()
d := s.walHold.degraded.Load()
if d != nil && (p.ReclaimedBytes > d.ReclaimedBytes || p.ExtentBytes > d.ExtentBytes) {
s.walHold.degraded.CompareAndSwap(d, nil)
d = s.walHold.degraded.Load()
}
st := WALHoldStatus{OpenSequence: scope, ReclaimedBytes: p.ReclaimedBytes, ExtentBytes: p.ExtentBytes, Degraded: d != nil, ActiveWaiters: s.walHold.active.Load(), Commands: s.walHold.commands.Load(), StallAnswers: s.walHold.stalls.Load(), CapAnswers: s.walHold.caps.Load(), WaitNanos: s.walHold.waitNanos.Load(), FlusherPhase: p.Phase}
if st.Degraded {
st.Reason = string(walReclaimStalled)
}
if e := s.walHold.last.Load(); e != nil {
st.LastReason = e.Reason
st.LastWaitNanos = e.WaitNanos
}
return st
}
@@ -0,0 +1,59 @@
package storage
import "time"
const walReclaimWindow = 5 * time.Second
type walHoldReason string
const (
walReclaimStalled walHoldReason = "wal_reclaim_stalled"
walHoldCap walHoldReason = "wal_hold_cap"
)
// walHoldWindow belongs to one command. Global reclaim observations may renew
// its inactivity deadline, but can never shorten its initial window or move
// its absolute command cap. The admission waiter owns it; it needs no lock.
type walHoldWindow struct {
capAt time.Time
progressAt time.Time
stallAfter time.Duration
}
func newWALHoldWindow(arrival, holdStarted time.Time, maxHold time.Duration) walHoldWindow {
return walHoldWindow{capAt: arrival.Add(maxHold), progressAt: holdStarted, stallAfter: walReclaimWindow}
}
// newWALNoRetryHoldWindow is for protocols whose error completion is final.
// A zero device cap means no device timeout; it does not inherit a network
// frontend's cap. Diagnostic degradation still starts at five seconds.
func newWALNoRetryHoldWindow(arrival, holdStarted time.Time, deviceCap time.Duration) walHoldWindow {
w := walHoldWindow{progressAt: holdStarted, stallAfter: 30 * time.Second}
if deviceCap > 0 {
w.capAt = arrival.Add(deviceCap)
}
return w
}
func (w *walHoldWindow) degraded(now time.Time) bool {
return !now.Before(w.progressAt.Add(walReclaimWindow))
}
// observeProgress is called only when a same-scope checkpoint advanced or
// the current flusher cycle successfully wrote new extent bytes. An unchanged
// sample, failed write, phase heartbeat or empty cycle must not call it.
func (w *walHoldWindow) observeProgress(at time.Time) {
if at.After(w.progressAt) {
w.progressAt = at
}
}
func (w *walHoldWindow) expired(now time.Time) walHoldReason {
if !w.capAt.IsZero() && !now.Before(w.capAt) {
return walHoldCap
}
if !now.Before(w.progressAt.Add(w.stallAfter)) {
return walReclaimStalled
}
return ""
}
@@ -0,0 +1,108 @@
package storage
import (
"testing"
"time"
)
func TestWALHoldWindowRetryGetsOwnStallWindow(t *testing.T) {
now := time.Now()
oldProgress := now.Add(-20 * time.Second)
w := newWALHoldWindow(now, now, 25*time.Second)
w.observeProgress(oldProgress)
if got := w.expired(now); got != "" {
t.Fatalf("retry immediately stalled from global sample: %s", got)
}
if got := w.expired(now.Add(5*time.Second - time.Nanosecond)); got != "" {
t.Fatalf("premature stall: %s", got)
}
if got := w.expired(now.Add(5 * time.Second)); got != walReclaimStalled {
t.Fatalf("stall boundary: %s", got)
}
// A later command cannot inherit an earlier command's elapsed window.
later := newWALHoldWindow(now.Add(3*time.Second), now.Add(3*time.Second), 25*time.Second)
later.observeProgress(now)
if got := later.expired(now.Add(5 * time.Second)); got != "" {
t.Fatalf("shared window stalled newer command: %s", got)
}
}
func TestWALHoldWindowProgressDoesNotRenewCap(t *testing.T) {
now := time.Now()
w := newWALHoldWindow(now, now, 25*time.Second)
for sec := 4; sec <= 24; sec += 4 {
at := now.Add(time.Duration(sec) * time.Second)
if got := w.expired(at); got != "" {
t.Fatalf("live reclaim stalled at %ds: %s", sec, got)
}
w.observeProgress(at)
}
if got := w.expired(now.Add(25*time.Second - time.Nanosecond)); got != "" {
t.Fatalf("early cap: %s", got)
}
if got := w.expired(now.Add(25 * time.Second)); got != walHoldCap {
t.Fatalf("progress extended cap: %s", got)
}
}
func TestWALHoldWindowStartsCapAtCommandArrival(t *testing.T) {
now := time.Now()
w := newWALHoldWindow(now, now.Add(23*time.Second), 25*time.Second)
if got := w.expired(now.Add(25 * time.Second)); got != walHoldCap {
t.Fatalf("queue time escaped cap: %s", got)
}
}
func TestWALHoldWindowOlderObservationCannotMoveWindowBack(t *testing.T) {
now := time.Now()
w := newWALHoldWindow(now, now, 25*time.Second)
w.observeProgress(now.Add(4 * time.Second))
w.observeProgress(now.Add(time.Second))
if got := w.expired(now.Add(8 * time.Second)); got != "" {
t.Fatalf("older observation shortened window: %s", got)
}
if got := w.expired(now.Add(9 * time.Second)); got != walReclaimStalled {
t.Fatalf("no-progress window: %s", got)
}
}
func TestWALHoldWindowNoRetrySeparatesDegradedFromError(t *testing.T) {
now := time.Now()
w := newWALNoRetryHoldWindow(now, now, 0)
if w.degraded(now.Add(5*time.Second - time.Nanosecond)) {
t.Fatal("premature degraded")
}
if !w.degraded(now.Add(5 * time.Second)) {
t.Fatal("stall not visible at5s")
}
if got := w.expired(now.Add(30*time.Second - time.Nanosecond)); got != "" {
t.Fatalf("final answer before30s: %s", got)
}
if got := w.expired(now.Add(30 * time.Second)); got != walReclaimStalled {
t.Fatalf("stall answer at30s: %s", got)
}
}
func TestWALHoldWindowNoDeviceTimeoutHasNoCapWhileProgressMoves(t *testing.T) {
now := time.Now()
w := newWALNoRetryHoldWindow(now, now, 0)
for sec := 4; sec <= 120; sec += 4 {
at := now.Add(time.Duration(sec) * time.Second)
if got := w.expired(at); got != "" {
t.Fatalf("progressing uncapped hold expired at%ds: %s", sec, got)
}
w.observeProgress(at)
if w.degraded(at) {
t.Fatal("successful progress left degraded window")
}
}
}
func TestWALHoldWindowDeviceCapStillBoundsProgress(t *testing.T) {
now := time.Now()
w := newWALNoRetryHoldWindow(now, now, 10*time.Second)
w.observeProgress(now.Add(9 * time.Second))
if got := w.expired(now.Add(10 * time.Second)); got != walHoldCap {
t.Fatalf("device cap renewed: %s", got)
}
}
@@ -0,0 +1,219 @@
package storage
import (
"context"
"errors"
"fmt"
"log"
"time"
)
var (
ErrWALReclaimStalled = fmt.Errorf("storage: wal_reclaim_stalled: %w", ErrWALPressureTimeout)
ErrWALHoldCap = fmt.Errorf("storage: wal_hold_cap: %w", ErrWALPressureTimeout)
)
type walWriteArrivalKey struct{}
type walWriteArrival struct {
store *WALStore
arrival time.Time
order uint64
}
func newWALWriteArrival(s *WALStore, arrival time.Time) walWriteArrival {
if arrival.IsZero() {
arrival = time.Now()
}
var order uint64
if s.admission != nil {
order = s.admission.newCommandOrder()
}
return walWriteArrival{store: s, arrival: arrival, order: order}
}
func writeArrivalFor(ctx context.Context, s *WALStore) *walWriteArrival {
if v, _ := ctx.Value(walWriteArrivalKey{}).(*walWriteArrival); v != nil && v.store == s {
return v
}
if h := holdFor(ctx, s); h != nil {
return &h.walWriteArrival
}
return nil
}
// WithWALWriteArrival preserves command ordering across sequential store calls,
// independently of the transport's pressure timeout policy. It takes no ticket.
func WithWALWriteArrival(ctx context.Context, s *WALStore, arrival time.Time) context.Context {
if writeArrivalFor(ctx, s) != nil {
return ctx
}
v := newWALWriteArrival(s, arrival)
return context.WithValue(ctx, walWriteArrivalKey{}, &v)
}
func admissionArrival(ctx context.Context, a *walAdmission) *walWriteArrival {
if v, _ := ctx.Value(walWriteArrivalKey{}).(*walWriteArrival); v != nil && v.store.admission == a {
return v
}
if h := admissionHold(ctx, a); h != nil {
return &h.walWriteArrival
}
return nil
}
type walWriteHoldKey struct{}
// A command owns this state across its sequential store batches. Only the
// command's write goroutine observes progress or finishes the observations.
type walWriteHold struct {
walWriteArrival
waiting bool
waitStarted time.Time
waitNanos int64
reason walHoldReason
maxHold time.Duration
final bool
window walHoldWindow
progress ReclaimProgress
started bool
finished bool
}
// WithWALWriteHold preserves caller cancellation/deadlines and one command
// identity across adapter batches. The caller must FinishWALWriteHold after
// the byte command, including an error return. Each store append owns and
// releases its own ticket synchronously; cancellation cannot release it early.
func WithWALWriteHold(ctx context.Context, s *WALStore, arrival time.Time, maxHold time.Duration, final bool) (context.Context, context.CancelFunc) {
if h, _ := ctx.Value(walWriteHoldKey{}).(*walWriteHold); h != nil {
return ctx, func() {}
}
var command walWriteArrival
if existing := writeArrivalFor(ctx, s); existing != nil {
command = *existing
} else {
command = newWALWriteArrival(s, arrival)
}
arrival = command.arrival
h := &walWriteHold{walWriteArrival: command, maxHold: maxHold, final: final}
h.window = newWALHoldWindow(arrival, time.Now(), maxHold)
if final {
h.window = newWALNoRetryHoldWindow(arrival, time.Now(), maxHold)
}
ctx = context.WithValue(ctx, walWriteHoldKey{}, h)
if maxHold > 0 {
return context.WithDeadline(ctx, arrival.Add(maxHold))
}
return context.WithCancel(ctx)
}
func holdFor(ctx context.Context, s *WALStore) *walWriteHold {
h, _ := ctx.Value(walWriteHoldKey{}).(*walWriteHold)
if h != nil && h.store == s {
return h
}
return nil
}
func admissionHold(ctx context.Context, a *walAdmission) *walWriteHold {
h, _ := ctx.Value(walWriteHoldKey{}).(*walWriteHold)
if h != nil && h.store.admission == a {
return h
}
return nil
}
// FinishWALWriteHold records a complete byte command's pressure observations.
// Each store call has already released its admission ticket before returning.
func FinishWALWriteHold(ctx context.Context, outcome error) {
h, _ := ctx.Value(walWriteHoldKey{}).(*walWriteHold)
if h == nil || h.finished {
return
}
h.finished = true
if h.started || h.reason != "" {
reason := string(h.reason)
if reason == "" {
if outcome == nil {
reason = "completed"
} else if errors.Is(outcome, context.Canceled) {
reason = "cancelled"
} else {
reason = "write_failed"
}
}
if !h.started {
h.store.walHold.commands.Add(1)
}
h.store.walHold.waitNanos.Add(uint64(h.waitNanos))
h.store.walHold.last.Store(&walHoldEvent{Reason: reason, WaitNanos: h.waitNanos})
if h.reason == walHoldCap {
h.store.walHold.caps.Add(1)
}
if h.reason == walReclaimStalled {
h.store.walHold.stalls.Add(1)
}
detail := ""
if outcome != nil {
detail = outcome.Error()
}
p := h.store.ReclaimProgress()
log.Printf("storage: WAL write hold reason=%q held_ns=%d reclaimed_bytes=%d extent_bytes=%d phase=%s error=%q", reason, h.waitNanos, p.ReclaimedBytes, p.ExtentBytes, p.Phase, detail)
}
}
func (h *walWriteHold) start() {
if h.waiting {
return
}
h.waiting = true
h.waitStarted = time.Now()
h.window.progressAt = h.waitStarted
h.progress = h.store.ReclaimProgress()
h.store.walHold.active.Add(1)
if !h.started {
h.started = true
h.store.walHold.commands.Add(1)
}
}
func (h *walWriteHold) endWait() {
if !h.waiting {
return
}
h.waiting = false
h.store.walHold.active.Add(-1)
}
func (h *walWriteHold) check() error {
if fault := h.store.stickyIOFault(); fault != nil {
return fault
}
if h.finished {
return context.Canceled
}
now := time.Now()
if h.started {
p := h.store.ReclaimProgress()
if p.ReclaimedBytes < h.progress.ReclaimedBytes || p.ExtentBytes < h.progress.ExtentBytes {
return errors.New("storage: WAL reclaim observation scope changed")
}
if p.ReclaimedBytes > h.progress.ReclaimedBytes || p.ExtentBytes > h.progress.ExtentBytes {
h.window.observeProgress(now)
}
h.progress = p
}
if h.waiting && h.window.degraded(now) {
p := h.progress
h.store.walHold.degraded.CompareAndSwap(nil, &p)
}
switch reason := h.window.expired(now); reason {
case walHoldCap:
h.reason = walHoldCap
return ErrWALHoldCap
case walReclaimStalled:
if h.waiting {
h.reason = walReclaimStalled
return ErrWALReclaimStalled
}
}
return nil
}
@@ -0,0 +1,157 @@
package storage
import (
"bytes"
"context"
"errors"
"testing"
"testing/synctest"
"time"
)
func TestWALWriteHoldMovingReclaimOutlastsOldAdmissionBudget(t *testing.T) {
s := admissionPressureV3(t, 15)
synctest.Test(t, func(t *testing.T) {
ctx, cancel := WithWALWriteHold(context.Background(), s, time.Now(), 25*time.Second, false)
defer cancel()
go func() {
for i := 0; i < 4; i++ {
time.Sleep(4 * time.Second)
s.flusher.instr.extentWriteBytes.Add(4096)
}
time.Sleep(4 * time.Second)
if err := s.flusher.flushOnce(); err != nil {
panic(err)
}
}()
start := time.Now()
_, err := s.WriteContext(ctx, 16, blk(16))
FinishWALWriteHold(ctx, err)
if err != nil {
t.Fatal(err)
}
if got, err := s.Read(16); err != nil || !bytes.Equal(got, blk(16)) {
t.Fatalf("post-hold bytes: %v", err)
}
if time.Since(start) < 20*time.Second {
t.Fatalf("did not hold for reclaim: %s", time.Since(start))
}
})
}
func TestWALWriteHoldStallIsTypedAndFreshPerCommand(t *testing.T) {
s := admissionPressureV3(t, 15)
synctest.Test(t, func(t *testing.T) {
for i := 0; i < 2; i++ {
ctx, cancel := WithWALWriteHold(context.Background(), s, time.Now(), 25*time.Second, false)
start := time.Now()
_, err := s.WriteContext(ctx, 16, blk(16))
FinishWALWriteHold(ctx, err)
cancel()
if !errors.Is(err, ErrWALReclaimStalled) {
t.Fatalf("try%d: %v", i, err)
}
if got := time.Since(start); got < 5*time.Second || got > 5*time.Second+20*time.Millisecond {
t.Fatalf("try%d window=%s", i, got)
}
}
})
}
func TestWALWriteHoldCapWhileProgressMoves(t *testing.T) {
s := admissionPressureV3(t, 15)
synctest.Test(t, func(t *testing.T) {
ctx, cancel := WithWALWriteHold(context.Background(), s, time.Now(), 25*time.Second, false)
defer cancel()
stop, joined := make(chan struct{}), make(chan struct{})
go func() {
defer close(joined)
for i := 0; i < 30; i++ {
select {
case <-stop:
return
case <-time.After(time.Second):
s.flusher.instr.extentWriteBytes.Add(4096)
}
}
}()
before := s.NextLSN()
start := time.Now()
_, err := s.WriteContext(ctx, 16, blk(16))
close(stop)
<-joined
FinishWALWriteHold(ctx, err)
if !errors.Is(err, ErrWALHoldCap) {
t.Fatalf("cap was not typed: %v", err)
}
if got := time.Since(start); got != 25*time.Second {
t.Fatalf("cap at%s", got)
}
if s.NextLSN() != before {
t.Fatal("cap appended")
}
if st := s.WALHoldStatus(); st.CapAnswers != 1 || st.LastReason != "wal_hold_cap" {
t.Fatalf("cap status: %+v", st)
}
})
}
func TestWALWriteHoldDegradedBeforeFinalStallAndCancellationJoins(t *testing.T) {
s := admissionPressureV3(t, 15)
synctest.Test(t, func(t *testing.T) {
ctx, cancel := WithWALWriteHold(context.Background(), s, time.Now(), 0, true)
done := make(chan error, 1)
go func() { _, err := s.WriteContext(ctx, 16, blk(16)); FinishWALWriteHold(ctx, err); done <- err }()
time.Sleep(5*time.Second + 10*time.Millisecond)
st := s.WALHoldStatus()
if !st.Degraded || st.ActiveWaiters != 1 || st.StallAnswers != 0 {
t.Fatalf("not degraded before final answer: %+v", st)
}
select {
case err := <-done:
t.Fatalf("final error before30s: %v", err)
default:
}
s.flusher.instr.extentWriteBytes.Add(4096)
if s.WALHoldStatus().Degraded {
t.Fatal("successful extent progress did not clear diagnostic degradation")
}
cancel()
synctest.Wait()
if err := <-done; !errors.Is(err, context.Canceled) {
t.Fatalf("cancelled hold: %v", err)
}
if s.WALHoldStatus().ActiveWaiters != 0 {
t.Fatal("cancelled hold left active waiter")
}
})
}
func TestWALWriteHoldLatchedFaultWinsAtStallBoundary(t *testing.T) {
s := admissionPressureV3(t, 15)
synctest.Test(t, func(t *testing.T) {
ctx, cancel := WithWALWriteHold(context.Background(), s, time.Now(), 25*time.Second, false)
defer cancel()
fault := errors.New("injected physical persistence fault")
go func() { time.Sleep(5*time.Second - time.Millisecond); s.latchV3(fault) }()
_, err := s.WriteContext(ctx, 16, blk(16))
FinishWALWriteHold(ctx, err)
if !errors.Is(err, fault) || errors.Is(err, ErrWALReclaimStalled) {
t.Fatalf("stall masked physical fault: %v", err)
}
})
}
func TestWALWriteHoldFinalWithoutDeviceTimerWaitsThirtySeconds(t *testing.T) {
s := admissionPressureV3(t, 15)
synctest.Test(t, func(t *testing.T) {
ctx, cancel := WithWALWriteHold(context.Background(), s, time.Now(), 0, true)
defer cancel()
start := time.Now()
_, err := s.WriteContext(ctx, 16, blk(16))
FinishWALWriteHold(ctx, err)
if !errors.Is(err, ErrWALReclaimStalled) || time.Since(start) != 30*time.Second {
t.Fatalf("final window %s: %v", time.Since(start), err)
}
})
}
+29 -10
View File
@@ -47,6 +47,7 @@ import (
// - Online resize
// - Compaction (the WAL is bounded but periodic checkpoints free space)
type WALStore struct {
walHold walHoldInstrumentation
dataSyncStatus DataSyncStatus // selected before publication; never changes in this open
// recoveryWarnings and holesSuspected: the last Recover's typed
@@ -161,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.
@@ -530,8 +532,15 @@ 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
}
if !deadline.IsZero() {
wait = time.Until(deadline)
}
@@ -544,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")
@@ -565,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) })
@@ -631,8 +641,15 @@ 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
}
if !deadline.IsZero() {
wait = time.Until(deadline)
}
@@ -645,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")
@@ -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) })
@@ -11,6 +11,12 @@ import (
func (s *WALStore) writeAdmissionDeadline(ctx context.Context) time.Time {
now := time.Now()
deadline, hasDeadline := ctx.Deadline()
if holdFor(ctx, s) != nil {
if hasDeadline {
return deadline
}
return time.Time{}
}
if s.v3 != nil {
local := now.Add(s.admissionTimeout)
if !hasDeadline || local.Before(deadline) {
@@ -32,6 +38,12 @@ func (s *WALStore) writeBudgetError(ctx context.Context, deadline time.Time) err
if ctx.Err() == context.Canceled {
return context.Canceled
}
if h := holdFor(ctx, s); h != nil {
if err := h.check(); err != nil {
return err
}
}
if !deadline.IsZero() && !time.Now().Before(deadline) {
return ErrWALPressureTimeout
}
+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 --> [*]
```
+29 -11
View File
@@ -476,15 +476,27 @@ 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.
- 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.
Already-started physical I/O, COW/observer callbacks and higher-layer waits
are not preempted. An unresolved pin or local stall returns
`ErrWALPressureTimeout`, preserved as `frontend.ErrBackendBusy`; NVMe returns
Generic/Namespace Not Ready (SC0x82), DNR=0. Sticky faults retain their original
non-retryable mapping. This is a local pressure outcome, not a whole-I/O
deadline; the broader budget gap is tracked separately in issue221.
- 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
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. 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 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
stay effective. Successful reclaim/extent counter increases renew the
per-command inactivity window, never its absolute cap. Other backends keep
the four-second cooperative WriteCommandBudget. Already-started physical
I/O and short locks are not preempted; no detached worker appends after an
expiry answer. Permanent storage faults win over pressure/refusal timing.
- Every frontend I/O error completion uses one shared retry class
(`INV-FE-ERROR-RETRY-CLASS-001`, the shared backend-error classification rule): (a) a known permanent
cause anywhere in the wrapped/joined tree wins: EIO, ENOSPC, EROFS, counter
@@ -677,8 +689,14 @@ 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` | 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` | `TestWALAdmissionFastReservationExcludesCompetingAppend`, `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`, `TestWALHoldSamplerFixedNonzeroProgressExpires` | 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 |
| `INV-WAL-HOLD-OBSERVE-001` | The hold status and metrics routes read atomic progress without requiring general frontier locks and preserve the status listener's access policy. | M1 Serving (diagnostics) | `core/host/volume/wal_hold_metrics.go`; `DurableProvider.WALHoldStatuses` | `TestWALHoldMetricsAtomicSourceAndAccess`, `TestWALHoldAtomicStatusDoesNotReadFrontiers` | NONE (read-only observation) | ACTIVE |
| `INV-WAL-HOLD-TRANSPORT-SCOPE-001` | ublk, NBD and serial iSCSI explicitly retain the legacy write budget and cannot install a retryable WAL hold; ublk/NBD apply it to Write only, while FUA Sync and flush retain the caller context; final-error extended holds remain deferred. | M1 Serving (write admission) | `core/frontend/write_budget.go` `WithLegacyWriteBudget`; `core/frontend/durable/storage_adapter.go` `WriteCommandContext`; ublk, NBD and serial iSCSI write dispatch | `TestDeviceWriteKeepsLegacyBudget` (`core/frontend/ublk/device_write_budget_test.go`, `core/frontend/nbd/device_write_budget_test.go`); `TestDeviceLegacyBudgetDoesNotInstallARetryableWALHold` (`core/frontend/durable/device_write_scope_test.go`); `TestSerialISCSIWriteKeepsLegacyBudget` | WALHold r2 rows 325-333; final-error activation deferred | 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-DEADLINE-001` | A command keeps any earlier caller deadline across adapter batches. Retryable WAL commands use their arrival-based cap; explicit legacy device transports and other backends keep WriteCommandBudget. An expired command starts no new append. | 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`; `core/storage/wal_write_hold.go` | `TestStorageBackendWriteKeepsOneDeadlineAcrossBatches`, `TestWALStoreV3WriteContextDeadlineIncludesCaptureWait`, `TestWALStoreV3WriteBudgetIncludesPostAdmissionWait`, `TestSessionWriteBudgetIncludesDispatchQueue`, `TestWALHoldBudgetSurvivesNestedNVMeDispatch`, `TestWALHoldReleasesAdmissionBeforeObserverAck`, `TestWALHoldDoesNotOwnAdmissionWhileWaitingForRMW` | — | 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 |
| `INV-WAL-V3-ADMISSION-NOPAYLOAD-001` | A v3 write whose command deadline has passed starts no new payload WAL write: 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. | M1 Serving (write admission) | `core/storage/walstore_v3.go` `WALStore.appendWriteV3`, `WALStore.writeBatchV3Locked`, `WALStore.v3BudgetAfterRollover`; `core/storage/wal_io_v3.go` `walWriterV3.append` | `TestWALStoreV3WriteBudgetRefusesNewPayloadAfterRollover`, `TestWALStoreV3WriteBudgetRechecksAfterRollover` | — | ACTIVE |
| `INV-WAL-V3-ADMISSION-EXPIRY-STATE-001` | A v3 write refused for an expired deadline before its append leaves the WAL bytes, nextLSN and the dirty map unchanged. | M1 Serving (write admission) | `core/storage/walstore.go` `WALStore.WriteContext`, `WALStore.WriteBatchContext` | `TestStorageBackendExpiredWriteDoesNotAppend` | — | ACTIVE |
@@ -1394,7 +1412,7 @@ The two STUB rows of the start path are measured by the 1 TiB row's kill-and-res
| Offline seal | M5 PlainStop -> Quiesce; `INV-CUT-PLAIN-DETACH-001` | Caller context; positive HTTP timeoutMs. Completed uploads resume only within one blockvolume process and matching owner/HEAD/chunk versions; after restart the seal must fit seal_timeout_ms. | Provider owns drain, detached cut and settlement. Cancellation preserves unknown/fenced outcome safety; a closed frontend stays closed. | No admission lock held during store or remote I/O. |
| Plain seal remote proof | M5 RemoteProof; `INV-WS-SEAL-REPLAY-001` | Earlier caller context or existing 2 s HEAD-operation bound for the filer read; attachment serialization retains its owner's cooperative caller bound | Provider registers with Close; closeBoundRemote cancels the read, and Close joins it. Failure keeps frontend admission closed. | Attachment mutex serializes against recover/detach; no backend/store/map lock spans the filer read. |
| Frontend pre-copy admission | M5 tentative admission -> resume; `INV-CUT-PRECOPY-001` (not reachable in this release) | Earlier of caller deadline and this command arrival + 5 s; one bound across retries, no inherited pause clock | Owner `finishPrecopyLocked`: resume or terminal Close clears the pause and grants all waiters in FIFO arrival order under one `b.mu` hold; each rechecks the ordinary gate. Expiry removes only its waiter and refuses with typed `ErrBackendBusy` + deadline cause (guest-visible: yes). Only a typed pause refusal requeues a granted waiter under the original command deadline; already-observed stale-primary and other gate errors are returned unchanged. Grant versus queue expiry is decided under the same lock; timely grants survive later queue-timer expiry but never caller expiry or a terminal gate. No dependency on another command's completion. | No `ioMu`, store lock, or remote call while queued. Admitted I/O retains normal per-LBA serialization and lifecycle accounting. |
| v3 write WAL-pressure admission: `core/storage/wal_admission.go` `walAdmission.acquireContext`, called by `WALStore.WriteContext` and `WALStore.WriteBatchContext` | M1 Serving (write admission); `INV-WAL-V3-ADMISSION-001`, `INV-WAL-V3-ADMISSION-DEADLINE-001`, `INV-WAL-V3-ADMISSION-FAULT-001` | The write's store admission deadline, fixed once when the write enters the store: the earlier of the caller's deadline and entry + 4 s (`admissionTimeout`), less a reserve of min(1 s, a quarter of the time then left), so at most entry + 3 s, on the local clock. In the soft band (pressure at least 0.70 and below 0.90) the pressure wait is one sleep of at most 5 ms. | Owner: the flusher. The wait wakes it (`NotifyUrgent`) on entry and at every 2 ms recheck while pressure is at or above the 0.90 hard watermark, and ends once the flusher's progress brings pressure below 0.90; a wait for one of the 64 admission slots ends when another write releases its slot. On expiry the write is refused before its append, with no WAL byte, nextLSN or dirty entry changed: `ErrWALPressureTimeout` (retryable; `frontend.ErrBackendBusy` at the durable backend), or the original fault when a terminal fault has latched, or `context.Canceled` when the caller cancelled. The wait grants no reuse and acknowledges nothing. | Held while waiting: the `captureMu` and `lifecycleMu` read locks, so a capture barrier, a BASE begin or complete, and `Close` wait behind it for at most this bound. Not held while it sleeps: the store, descriptor and WAL writer locks (each pressure sample takes and releases them). Local wait: no remote call. |
| v3 write WAL-pressure admission: `core/storage/wal_admission.go` `walAdmission.acquireContext`, called by `WALStore.WriteContext` and `WALStore.WriteBatchContext` | M1 Serving (write admission); `INV-WAL-V3-ADMISSION-001`, `INV-WAL-V3-ADMISSION-DEADLINE-001`, `INV-WAL-V3-ADMISSION-FAULT-001` | NVMe WAL hold commands share their arrival-based cap (default 25 s) and a per-command five-second inactivity window, renewed only by reclaimed/extent bytes. Explicit legacy transports keep the earlier of caller deadline and store entry + 4 s, less a reserve of min(1 s, a quarter of the time left). In the soft band (pressure at least 0.70 and below 0.90) the pressure wait is one sleep of at most 5 ms. | Owner: the flusher. The wait wakes it (`NotifyUrgent`) on entry and at every 2 ms recheck while pressure is at or above the 0.90 hard watermark, and ends once pressure falls below 0.90; FIFO admission then retains its ticket through that store append, releasing before adapter RMW/replica waits. On expiry the write is refused before its append, with no WAL byte, nextLSN or dirty entry changed: `ErrWALPressureTimeout` (retryable; `frontend.ErrBackendBusy` at the durable backend), or the original fault when a terminal fault has latched, or `context.Canceled` when the caller cancelled. The wait grants no reuse and acknowledges nothing. | Held while waiting: the `captureMu` and `lifecycleMu` read locks, so a capture barrier, a BASE begin or complete, and `Close` join the command's bounded admission wait (default cap 25 s for NVMe holds; legacy admission at most about 3 s). Started I/O and short locks remain cooperative. Not held while it sleeps: the store, descriptor and WAL writer locks (each pressure sample takes and releases them). Local wait: no remote call. |
The WAL-pressure admission wait is the one wait here held under store locks (the `captureMu` and `lifecycleMu` read locks). It is a local wait: pressure samples, a timer and the flusher's local progress. No remote call is made while those locks are held, so the rule that no remote call runs under a lock still holds.
+12
View File
@@ -674,3 +674,15 @@ Every command on the pages above, and the test that runs it.
| Scheduled snapshots (`--chunk-snapshot-schedule`) on a running volume with a real clock | not run in 1.0 as written: the schedule is tested with a fake clock (`core/frontend/durable/chunk_snapshot_schedule_test.go`) | not run |
| Periodic capture (`--chunk-capture-interval`) on a running volume | a lab run on the release candidate: automatic cuts while the guest wrote, every acknowledged write read back | lab |
| SeaweedFS vacuum (`/vol/vacuum`, `volume.vacuum`) | not run in 1.0: a SeaweedFS command; the tests check that the cleaning deletes the chunks, not that SeaweedFS compacts its files | not run |
## Host I/O timeout configuration
The holder cannot discover an initiator's I/O timeout. Set `blockvolume --host-io-timeout` (`host_io_timeout`) to match the hosts using the volume; the default is `30s`. If you raise or lower the hosts' `io_timeout`, change this setting to match. For hosts with different timeouts, use the shortest timeout.
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, 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=<name>` for atomic hold counters, reclaimed/extent bytes and flusher phase, or `GET /metrics?volume=<name>` 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.
The extended WAL-pressure hold policy is currently limited to NVMe/TCP. The serial iSCSI session keeps its existing short write/admission budget (four seconds for a command, about three seconds for WAL admission), returning BUSY under transient pressure; it does not hold its reader for the extended window. Long iSCSI holds require concurrent session command handling and initiator qualification. ublk and NBD retain an explicit four-second backend Write budget and can return a final EIO under pressure. That budget applies only to Write: FUA then performs Sync with the original caller context, exactly as a separate write plus flush; standalone flush keeps that context too. Their final-error 30-second stall policy and device-timeout-derived cap are deferred until actual device timeout configuration and native controls are wired; the network host timeout declaration does not configure those devices. Do not assume the extended slow-reclaim guarantee for ublk/NBD.
+40
View File
@@ -14,6 +14,8 @@ The volume's authority and health projection. Go type `volume.StatusProjection`.
| Field | Type | Meaning |
|---|---|---|
| `Degraded` | bool | WAL reclaim stalled for at least five seconds; diagnostic, not an authority or readiness change |
| `DegradedReason` | string | — (omitted when empty) |
| `VolumeID` | string | the volume this host serves |
| `ReplicaID` | string | this host's replica of it |
| `Epoch` | uint64 | the authority epoch of the current assignment |
@@ -78,6 +80,21 @@ Durable store state of the served volume. Go type `volume.durableStatusBody`.
| `ReplicaID` | string | this host's replica |
| `VolumeCount` | int | number of entries in Volumes |
| `Volumes[]` | object | the durable store state of the served volume |
| `Volumes[].WALHold` | object | WAL-pressure hold health and cumulative metrics (omitted when empty) |
| `Volumes[].WALHold.OpenSequence` | uint64 | process-local store-open observation scope; compare with the status process identity |
| `Volumes[].WALHold.ReclaimedBytes` | uint64 | — |
| `Volumes[].WALHold.ExtentBytes` | uint64 | — |
| `Volumes[].WALHold.Degraded` | bool | — |
| `Volumes[].WALHold.Reason` | string | — |
| `Volumes[].WALHold.ActiveWaiters` | int64 | — |
| `Volumes[].WALHold.Commands` | uint64 | — |
| `Volumes[].WALHold.StallAnswers` | uint64 | — |
| `Volumes[].WALHold.CapAnswers` | uint64 | — |
| `Volumes[].WALHold.WaitNanos` | uint64 | — |
| `Volumes[].WALHold.LastWaitNanos` | int64 | — |
| `Volumes[].WALHold.LastReason` | string | — |
| `Volumes[].WALHold.FlusherPhase` | string | — |
| `Volumes[].Degraded` | bool | diagnostic WAL reclaim stall; does not alter authority or readiness |
| `Volumes[].UnknownOutcome{}` | uint64 | unknown HEAD-write answers by cause since catalog start; never implies persistence |
| `Volumes[].HeadWrites{}` | uint64 | acknowledged HEAD writes by cause since holder catalog start; unknown replies excluded |
| `Volumes[].VolumeID` | string | the volume |
@@ -374,6 +391,29 @@ Durable store state of the served volume. Go type `volume.durableStatusBody`.
| `Volumes[].Warnings[]` | string | Warnings are the store's typed recovery warnings (e.g. wal_hole_suspected, issue #51); they do not change readiness. HolesSuspected counts the recoveries that found a WAL hole. (omitted when empty) |
| `Volumes[].HolesSuspected` | uint64 | (group of `Warnings`) Warnings are the store's typed recovery warnings (e.g. wal_hole_suspected, issue #51); they do not change readiness. HolesSuspected counts the recoveries that found a WAL hole. (omitted when empty) |
### `GET /status/wal-hold`
Atomic WAL hold observations scoped to this process and store open. Go type `volume.walHoldStatusBody`.
| Field | Type | Meaning |
|---|---|---|
| `ProcessID` | string | holder process incarnation |
| `VolumeID` | string | the served volume |
| `WALHold` | object | atomic store-open observations |
| `WALHold.OpenSequence` | uint64 | process-local store-open observation scope; compare with the status process identity |
| `WALHold.ReclaimedBytes` | uint64 | — |
| `WALHold.ExtentBytes` | uint64 | — |
| `WALHold.Degraded` | bool | — |
| `WALHold.Reason` | string | — |
| `WALHold.ActiveWaiters` | int64 | — |
| `WALHold.Commands` | uint64 | — |
| `WALHold.StallAnswers` | uint64 | — |
| `WALHold.CapAnswers` | uint64 | — |
| `WALHold.WaitNanos` | uint64 | — |
| `WALHold.LastWaitNanos` | int64 | — |
| `WALHold.LastReason` | string | — |
| `WALHold.FlusherPhase` | string | — |
### `GET /status/recovery`
The engine's replica projection (only with recovery enabled). Go type `engine.ReplicaProjection`.