Merge branch 'main' into fix/chunk-refuses-replication

This commit is contained in:
Ping Qiu authored and GitHub committed 2026-11-19 03:05:05 -08:00
commit fe3fe97489
69 files changed
+2949 -140

No files matched your search

@@ -0,0 +1,130 @@
package main
import (
"bytes"
"context"
"errors"
"os"
"path/filepath"
"strconv"
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/frontend/durable"
"github.com/seaweedfs/seaweed-block/core/storage"
)
func TestExistingDurableVolumeIgnoresCreateGeometry(t *testing.T) {
root := t.TempDir()
s, err := storage.CreateWALStore(filepath.Join(root, "v1.bin"), 16, 4096)
if err != nil {
t.Fatal(err)
}
want := bytes.Repeat([]byte{0x73}, 4096)
if _, err = s.Write(0, want); err != nil {
s.Close()
t.Fatal(err)
}
if _, err = s.Sync(); err != nil {
s.Close()
t.Fatal(err)
}
if err = s.Close(); err != nil {
t.Fatal(err)
}
args := append(phase150RequiredBlockvolumeArgs(), "--volume-id=v1", "--durable-root="+root, "--durable-impl=walstore", "--durable-blocks=4294967295", "--durable-blocksize=8192")
f, err := parseFlags(args)
if err != nil {
t.Fatalf("existing storage must ignore create-only geometry: %v", err)
}
blocks, blockSize, err := durableCreateGeometry(f)
if err != nil {
t.Fatal(err)
}
if blocks != 0 {
t.Fatal("existing file must select open-only mode")
}
p, err := durable.NewDurableProvider(durable.ProviderConfig{Impl: durable.ImplName(f.durableImpl), StorageRoot: f.durableRoot, NumBlocks: blocks, BlockSize: blockSize}, healthyView{})
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { p.Close() })
result, _, err := openAndRecoverDurable(p, &spyHost{}, "v1", 5*time.Second)
if err != nil || result != durableStartupReady {
t.Fatalf("existing recovery: %v %v", result, err)
}
st, err := p.EnsureStorage("v1")
if err != nil {
t.Fatal(err)
}
if st.NumBlocks() != 16 || st.BlockSize() != 4096 {
t.Fatalf("existing geometry changed: %d x %d", st.NumBlocks(), st.BlockSize())
}
got := make([]byte, 4096)
b, err := p.Open(context.Background(), "v1")
if err != nil {
t.Fatal(err)
}
if _, err = b.Read(context.Background(), 0, got); err != nil {
t.Fatal(err)
}
if !bytes.Equal(got, want) {
t.Fatal("existing bytes changed")
}
}
func TestExistingDurableVolumeDisappearsDoesNotCreateFromIgnoredFlags(t *testing.T) {
if strconv.IntSize < 64 {
t.Skip("64-bit CLI uint overflow case")
}
for _, impl := range []durable.ImplName{durable.ImplWALStore, durable.ImplWALStoreChunk} {
t.Run(string(impl), func(t *testing.T) {
root := t.TempDir()
path := filepath.Join(root, "v1.bin")
s, err := storage.CreateWALStore(path, 16, 4096)
if err != nil {
t.Fatal(err)
}
if err = s.Close(); err != nil {
t.Fatal(err)
}
args := append(phase150RequiredBlockvolumeArgs(), "--volume-id=v1", "--durable-root="+root, "--durable-impl="+string(impl), "--durable-blocks=4294967297")
if impl == durable.ImplWALStoreChunk {
args = append(args, "--chunk-filer=127.0.0.1:18888")
}
f, err := parseFlags(args)
if err != nil {
t.Fatal(err)
}
blocks, bs, err := durableCreateGeometry(f)
if err != nil {
t.Fatal(err)
}
if blocks != 0 {
t.Fatal("not open-only")
}
if err = os.Remove(path); err != nil {
t.Fatal(err)
}
if _, _, err = durableCreateGeometry(f); err == nil {
t.Fatal("fresh recheck accepted original overflowing count")
}
p, err := durable.NewDurableProvider(durable.ProviderConfig{Impl: impl, StorageRoot: root, NumBlocks: blocks, BlockSize: bs, ChunkRemoteFor: func(string) (storage.ChunkRemote, error) {
return nil, errors.New("unexpected remote access for missing open-only volume")
}}, healthyView{})
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { p.Close() })
if _, err = p.EnsureStorage("v1"); err == nil {
t.Fatal("created replacement from ignored flags")
}
if _, err = os.Stat(path); !os.IsNotExist(err) {
t.Fatalf("replacement file exists: %v", err)
}
if _, err = os.Stat(path + ".chunkfresh"); !os.IsNotExist(err) {
t.Fatalf("open-only refusal left a fresh marker: %v", err)
}
})
}
}
+30 -3
View File
@@ -27,6 +27,7 @@ import (
"github.com/seaweedfs/seaweed-block/core/frontend/nvme"
"github.com/seaweedfs/seaweed-block/core/frontend/nvmerdma"
"github.com/seaweedfs/seaweed-block/core/frontend/ublk"
"github.com/seaweedfs/seaweed-block/core/geometry"
"github.com/seaweedfs/seaweed-block/core/host/volume"
"github.com/seaweedfs/seaweed-block/core/recovery"
"github.com/seaweedfs/seaweed-block/core/replication"
@@ -270,6 +271,11 @@ func parseFlags(args []string) (flags, error) {
return flags{}, fmt.Errorf("--durable-wal-recovery-test-disable-flusher requires --durable-impl=walstore")
}
}
if f.durableRoot != "" {
if _, _, err := durableCreateGeometry(f); err != nil {
return flags{}, err
}
}
if f.iscsiCHAPUser == "" {
f.iscsiCHAPUser = os.Getenv("SW_BLOCK_ISCSI_CHAP_USERNAME")
}
@@ -523,6 +529,22 @@ type nvmeReadyLine struct {
SubsysNQN string `json:"subsys_nqn"`
}
// durableCreateGeometry leaves existing volumes in open-only mode. If the
// observed file disappears before Open, NumBlocks=0 prevents a replacement
// from being created using narrowed or otherwise ignored CLI values.
func durableCreateGeometry(f flags) (uint32, int, error) {
path := filepath.Join(f.durableRoot, f.volumeID+".bin")
if _, err := os.Stat(path); err == nil {
return 0, 0, nil
} else if !os.IsNotExist(err) {
return 0, 0, fmt.Errorf("durable volume geometry: %w", err)
}
if err := geometry.ValidateBlockGeometry(uint64(f.durableBlocks), uint64(f.durableBlockSize)); err != nil {
return 0, 0, fmt.Errorf("--durable-blocks/--durable-blocksize: %w", err)
}
return uint32(f.durableBlocks), int(f.durableBlockSize), nil
}
func run(f flags) int {
readyCh := make(chan adapter.AssignmentInfo, 16)
@@ -579,11 +601,12 @@ func run(f flags) int {
var durableProv *durable.DurableProvider
var workspaceRemoteFor func(string) (storage.ChunkRemote, error)
if f.durableRoot != "" {
blocks, blockSize, geometryErr := durableCreateGeometry(f)
cfg := durable.ProviderConfig{
Impl: durable.ImplName(f.durableImpl),
StorageRoot: f.durableRoot,
BlockSize: int(f.durableBlockSize),
NumBlocks: uint32(f.durableBlocks),
BlockSize: blockSize,
NumBlocks: blocks,
WALRetentionLSNs: f.walRetentionLSNs,
WALMultiBlockRecords: f.durableWALMultiBlockRecords,
WALRecoveryTestDisableFlusher: f.durableWALRecoveryTestDisableFlusher,
@@ -603,7 +626,11 @@ func run(f flags) int {
defer chunk.close()
}
}
dp, err := durable.NewDurableProvider(cfg, h.ProjectionView())
var dp *durable.DurableProvider
err := geometryErr
if err == nil {
dp, err = durable.NewDurableProvider(cfg, h.ProjectionView())
}
if chunkErr != nil {
err = chunkErr
}
@@ -0,0 +1,27 @@
package main
import (
"strconv"
"strings"
"testing"
)
func TestDurableCreateFlagsValidateOriginalGeometry(t *testing.T) {
if strconv.IntSize < 64 {
t.Skip("64-bit CLI uint overflow case")
}
for _, blocks := range []string{"4294967297", "18446744073709551615"} {
args := append(phase150RequiredBlockvolumeArgs(), "--durable-root="+t.TempDir(), "--durable-blocks="+blocks)
if _, err := parseFlags(args); err == nil || !strings.Contains(err.Error(), "durable-blocks") {
t.Fatalf("blocks %s: %v", blocks, err)
}
}
args := append(phase150RequiredBlockvolumeArgs(), "--durable-root="+t.TempDir(), "--durable-blocks=4294967295", "--durable-blocksize=4096")
if _, err := parseFlags(args); err != nil {
t.Fatal(err)
}
args = append(args, "--durable-blocksize=8192")
if _, err := parseFlags(args); err == nil || !strings.Contains(err.Error(), "16 TiB - 4 KiB") {
t.Fatalf("oversize geometry: %v", err)
}
}
@@ -83,15 +83,12 @@ func bindAndGrant(t *testing.T, p *Publisher, volume, replica string) WorkspaceL
// waitExtenders joins every admitted extender (tests only; no concurrent
// admission while waiting).
// waitExtenders joins every admitted extender. No wall-clock bound (#227):
// extenders are finite (each makes at most one store write), so the join is
// the progress condition; a hang is reported by the go test timeout.
func waitExtenders(t *testing.T, p *Publisher) {
t.Helper()
done := make(chan struct{})
go func() { p.extWG.Wait(); close(done) }()
select {
case <-done:
case <-time.After(10 * time.Second):
t.Fatal("extenders did not finish")
}
p.extWG.Wait()
}
// assertLeaseViewMatches checks INV-LEASE-VIEW-001: with p.mu held, every
@@ -622,6 +619,7 @@ func TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose(t *testing.T) {
var holdOnce, releaseOnce sync.Once
releaseHold := func() { releaseOnce.Do(func() { close(heldRelease) }) }
var classifying atomic.Bool
var holding atomic.Bool // set when the extension write is held, before it blocks
hs.setBefore(func(r DurableRecord) error {
time.Sleep(5 * time.Millisecond) // a slow store
if !classifying.Load() || r.Workspace == nil || r.Workspace.Lease == nil {
@@ -640,6 +638,7 @@ func TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose(t *testing.T) {
first := false
holdOnce.Do(func() { first = true })
if first {
holding.Store(true) // before the hold: a renewal started after this saw it
close(heldEntered)
<-heldRelease
}
@@ -668,6 +667,7 @@ func TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose(t *testing.T) {
classifying.Store(true)
var grants [n]atomic.Int64
var underHold [n]atomic.Int64 // grants of calls that started while the extension write was held
var maxGrant [n]atomic.Int64
var slowest atomic.Int64
stop := make(chan struct{})
@@ -714,6 +714,7 @@ func TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose(t *testing.T) {
return
default:
}
fresh := holding.Load() // the call starts while the extension write is held
start := time.Now()
l, err := p.RenewWorkspaceLease(ctx, vol(i), "r", 1)
if d := int64(time.Since(start)); d > slowest.Load() {
@@ -721,6 +722,9 @@ func TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose(t *testing.T) {
}
if err == nil && !l.Revoking {
grants[i].Add(1)
if fresh {
underHold[i].Add(1)
}
if l.ExpiresAtNS > maxGrant[i].Load() {
maxGrant[i].Store(l.ExpiresAtNS)
}
@@ -731,29 +735,22 @@ func TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose(t *testing.T) {
}
// Handshake 1: the first extension write is held inside the store.
select {
case <-heldEntered:
case <-time.After(5 * time.Second):
t.Fatal("no horizon-extension write reached the store within 5 s")
}
<-heldEntered // progress, no timer (#227): renewers keep triggering extensions
// Handshake 2: renewals keep succeeding while it is held.
var atHold [n]int64
for _, i := range eligible {
atHold[i] = grants[i].Load()
}
for wait := time.Now().Add(2 * time.Second); ; time.Sleep(5 * time.Millisecond) {
// Progress, no timer (#227): every eligible volume gains a grant from a call
// that STARTED while the extension write was held (a reply computed before
// the hold does not count). Renewals that waited for it would never return.
for {
all := true
for _, i := range eligible {
if grants[i].Load() <= atHold[i] {
if underHold[i].Load() == 0 {
all = false
}
}
if all {
break
}
if time.Now().After(wait) {
t.Fatal("renewals did not succeed while an extension write was held")
}
time.Sleep(5 * time.Millisecond)
}
// Writers and Close start while the extension write is held.
writersStarted = true
@@ -0,0 +1,61 @@
package authority
import (
"context"
"strings"
"sync"
"testing"
"time"
)
// #242: a renewal refused for lack of host validity formats its error from
// the lease view; that read must happen under leaseMu, because the extender
// (refreshLeaseViewLocked) rewrites the view under leaseMu at any time.
// Run with -race: renewals that take the refusal run while another goroutine
// rewrites the view, as the extender does.
func TestWorkspaceLeaseRefusalReadsTheViewUnderTheLock(t *testing.T) {
disk, _ := newTempStore(t)
c := newTestClock()
p := newLeasePublisher(t, disk, 3*time.Second, c)
bindAndGrant(t, p, "v", "r")
// Force the no-host-validity refusal: the horizon just ahead, a skew
// bound far larger than what is left of it; the granted deadline later.
p.leaseMu.Lock()
lv := p.leaseViews["v"]
lv.d.horizon = c.now().Add(time.Millisecond).UnixNano()
lv.d.maxSkewNS = int64(time.Hour)
lv.deadline = c.now().Add(time.Hour)
p.leaseMu.Unlock()
const rounds = 200
var wg sync.WaitGroup
wg.Add(2)
go func() { // the extender's republish: a write of the view under leaseMu
defer wg.Done()
for i := 0; i < rounds; i++ {
p.leaseMu.Lock()
d := lv.d
lv.d = d
p.leaseMu.Unlock()
}
}()
errs := make(chan error, 1)
go func() {
defer wg.Done()
for i := 0; i < rounds; i++ {
if _, err := p.RenewWorkspaceLease(context.Background(), "v", "r", 1); err == nil || !strings.Contains(err.Error(), "leaves no host validity") {
select {
case errs <- err:
default:
}
return
}
}
}()
wg.Wait()
select {
case err := <-errs:
t.Fatalf("renewal with no host validity: %v; want the refusal", err)
default:
}
}
@@ -170,8 +170,9 @@ func (p *Publisher) RenewWorkspaceLease(ctx context.Context, volume, holder stri
// bound, leaseFact) would make the host fence on an invalid reply and lose
// its remaining validity; refuse with an error instead.
if grant-lv.d.maxSkewNS/2 <= now.UnixNano() {
horizon := lv.d.horizon // the view is leaseMu's: read it before the unlock (#242)
p.leaseMu.Unlock()
return WorkspaceLease{}, fmt.Errorf("workspace lease: durable horizon %s leaves no host validity", time.Unix(0, lv.d.horizon).UTC().Format(time.RFC3339Nano))
return WorkspaceLease{}, fmt.Errorf("workspace lease: durable horizon %s leaves no host validity", time.Unix(0, horizon).UTC().Format(time.RFC3339Nano))
}
if g := time.Unix(0, grant); g.After(lv.deadline) {
lv.deadline = g
+4
View File
@@ -8,6 +8,7 @@ import (
"time"
csipb "github.com/container-storage-interface/spec/lib/go/csi"
"github.com/seaweedfs/seaweed-block/core/geometry"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
@@ -248,6 +249,9 @@ func volumeSpecFromCreateRequest(req *csipb.CreateVolumeRequest) (VolumeSpec, er
if size <= 0 {
return VolumeSpec{}, status.Error(codes.InvalidArgument, "capacity is required")
}
if err := geometry.ValidateVolumeSize(uint64(size)); err != nil {
return VolumeSpec{}, status.Error(codes.InvalidArgument, err.Error())
}
if len(req.GetVolumeCapabilities()) == 0 {
return VolumeSpec{}, status.Error(codes.InvalidArgument, "volume capabilities are required")
}
@@ -0,0 +1,29 @@
package csi
import (
"context"
csipb "github.com/container-storage-interface/spec/lib/go/csi"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"strings"
"testing"
)
func TestCSICreateVolumeCapacityCapBeforeProvision(t *testing.T) {
const capBytes = int64(17592186040320)
p := &stubProvisioner{}
s := NewControllerServerWithProvisioner(&stubLookup{}, p)
req := &csipb.CreateVolumeRequest{Name: "v", CapacityRange: &csipb.CapacityRange{RequiredBytes: capBytes}, VolumeCapabilities: []*csipb.VolumeCapability{testVolumeCapability()}}
if _, err := s.CreateVolume(context.Background(), req); err != nil {
t.Fatal(err)
}
p.calls = nil
req.CapacityRange.RequiredBytes = capBytes + 4096
_, err := s.CreateVolume(context.Background(), req)
if status.Code(err) != codes.InvalidArgument || !strings.Contains(err.Error(), "16 TiB - 4 KiB") {
t.Fatalf("want clear InvalidArgument, got %v", err)
}
if len(p.calls) != 0 {
t.Fatal("oversized request reached provisioner")
}
}
@@ -35,6 +35,7 @@ import (
"strings"
"time"
"github.com/seaweedfs/seaweed-block/core/geometry"
"google.golang.org/protobuf/proto"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb"
@@ -487,6 +488,9 @@ func (c *Catalog) EnsureVolume(ctx context.Context, vol string, g Geometry) (Vol
return VolumeInfo{}, err
}
if !ok {
if g.BlockSize != 0 && g.NumBlocks > geometry.MaxVolumeBytes/uint64(g.BlockSize) {
return VolumeInfo{}, catErr(CodeGeometryMismatch, false, nil, "volume size exceeds maximum %d bytes (16 TiB - 4 KiB; uint32 LBA)", geometry.MaxVolumeBytes)
}
v = VolumeInfo{Format: volumeFormat, VolumeID: vol, Geometry: g, Origin: OriginCreate, CreatedNs: c.now().UnixNano()}
e, err := volumeEntry(v, "")
if err != nil {
@@ -1352,6 +1356,9 @@ func (c *Catalog) claimForkParent(ctx context.Context, req ForkRequest) (Snapsho
if ref.info.State == SnapDeleting {
return SnapshotInfo{}, catErr(CodeSnapshotDeleting, false, nil, "snapshot %s/%s is being deleted", req.Source, req.Snapshot)
}
if ref.info.geo.BlockSize != 0 && ref.info.geo.NumBlocks > geometry.MaxVolumeBytes/uint64(ref.info.geo.BlockSize) {
return SnapshotInfo{}, catErr(CodeGeometryMismatch, false, nil, "fork size exceeds maximum %d bytes (16 TiB - 4 KiB; uint32 LBA)", geometry.MaxVolumeBytes)
}
claims := decodeClaims(ref.entry)
for _, cl := range claims {
if cl == token {
@@ -0,0 +1,61 @@
package chunkstore
import (
"context"
"path"
"strings"
"testing"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb"
)
// A legacy catalog may already contain oversized geometry. A new fork is
// still a new volume: it must not bypass the creation cap by inheritance.
func TestForkRejectsLegacyOversizedGeometry(t *testing.T) {
for _, blocks := range []uint64{4294967295, 4294967296} {
f, b, c, _, _ := gcFixture(t)
ctx := context.Background()
v, ok, err := c.ReadVolume(ctx, "v1")
if err != nil || !ok {
t.Fatal(err)
}
v.NumBlocks = blocks
e, err := volumeEntry(v, "")
if err != nil {
t.Fatal(err)
}
if err = f.UpdateEntry(ctx, path.Join(catBase, "v1"), e, nil); err != nil {
t.Fatal(err)
}
h := publishSource(t, f, b.fakeBlobs, "v1", map[uint64][]byte{0: chunkBytes(0x41)})
_, err = c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "s"}, h)
if err != nil {
t.Fatal(err)
}
if err = f.CreateEntry(ctx, catBase, &filerpb.Entry{Name: "fork", IsDirectory: true}, true); err != nil {
t.Fatal(err)
}
_, err = c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "fork", RequestID: "f"})
if blocks == 4294967295 {
if err != nil {
t.Fatalf("at-cap fork: %v", err)
}
got, ok, e := c.ReadVolume(ctx, "fork")
if e != nil || !ok || got.NumBlocks != blocks {
t.Fatalf("at-cap geometry not inherited: %+v %v", got, e)
}
continue
}
if err == nil || !strings.Contains(err.Error(), "16 TiB - 4 KiB") {
t.Fatalf("oversized fork must refuse: %v", err)
}
if _, ok, e := c.ReadVolume(ctx, "fork"); e != nil || ok {
t.Fatalf("oversized fork persisted target: %v %v", ok, e)
}
// Observe claim cleanup through the public retention operation: an
// uncompleted fork claim would make this snapshot undeletable.
if _, deleteErr := c.DeleteSnapshot(ctx, "v1", "s1"); deleteErr != nil {
t.Fatalf("capacity refusal blocked snapshot deletion: %v", deleteErr)
}
}
}
@@ -90,14 +90,19 @@ func (r *ChunkRemote) PrepareManifest(ctx context.Context, base, next storage.Ch
data []byte
}
var uploads []upload
for group, chunks := range groups {
old := map[uint64]storage.ChunkRef{}
for idx, ref := range base.Chunks {
if idx/per == group {
ref.Key = qualifyManifestKey(owner, ref.Key)
old[idx] = ref
}
// Partition the base once, rather than scanning every base chunk for each
// segment group. Keep the same qualified-key comparison for segment reuse.
baseGroups := map[uint64]map[uint64]storage.ChunkRef{}
for idx, ref := range base.Chunks {
group := idx / per
if baseGroups[group] == nil {
baseGroups[group] = map[uint64]storage.ChunkRef{}
}
ref.Key = qualifyManifestKey(owner, ref.Key)
baseGroups[group][idx] = ref
}
for group, chunks := range groups {
old := baseGroups[group]
if previous, ok := base.Segments[group]; ok && base.ChunkBytes == chunkBytes && reflect.DeepEqual(chunks, old) {
next.Segments[group] = previous
continue
@@ -0,0 +1,36 @@
package chunkstore
import (
"context"
"fmt"
"testing"
"github.com/seaweedfs/seaweed-block/core/storage"
)
// Metadata-only scaling probe: one chunk per 1-GiB segment, all unchanged.
// No volume data allocation or remote I/O is included. Report ns/op and allocs;
// the old per-group scan visits groups*groups base references.
func BenchmarkPrepareManifestUnchangedGroups(b *testing.B) {
for _, n := range []int{256, 1024, 4096} {
b.Run(fmt.Sprint(n), func(b *testing.B) {
r, err := NewChunkRemote(newFakeFiler(), newFakeBlobs(), "/chunks/v1")
if err != nil {
b.Fatal(err)
}
base := storage.ChunkHead{Chunks: map[uint64]storage.ChunkRef{}, Segments: map[uint64]storage.ChunkSegment{}, ChunkBytes: 1 << 30, ManifestChunkCount: n}
for i := 0; i < n; i++ {
base.Chunks[uint64(i)] = storage.ChunkRef{Key: fmt.Sprintf("@v1/chunk/%d", i)}
base.Segments[uint64(i)] = storage.ChunkSegment{Key: fmt.Sprintf("@v1/seg/%d", i), Owner: "v1", Count: 1}
}
b.ReportAllocs()
b.ResetTimer()
for i := 0; i < b.N; i++ {
next, ids, err := r.PrepareManifest(context.Background(), base, base, 1<<30)
if err != nil || len(ids) != 0 || len(next.Segments) != n {
b.Fatalf("unchanged segment reuse: %v, intents=%v", err, ids)
}
}
})
}
}
@@ -0,0 +1,28 @@
package chunkstore
import (
"context"
"strings"
"testing"
)
func TestEnsureVolumeRejectsBeyondUint32LBACap(t *testing.T) {
f, b, _, _, _ := gcFixture(t)
c, err := NewCatalog(manifestFilerBlobs{f, b}, catBase)
if err != nil {
t.Fatal(err)
}
ctx := context.Background()
if _, err = c.EnsureVolume(ctx, "at-cap", Geometry{NumBlocks: 4294967295, BlockSize: 4096, ChunkBlocks: 1024}); err != nil {
t.Fatal(err)
}
for _, blocks := range []uint64{4294967296, ^uint64(0)} {
_, err = c.EnsureVolume(ctx, "too-large", Geometry{NumBlocks: blocks, BlockSize: 4096, ChunkBlocks: 1024})
if err == nil || !strings.Contains(err.Error(), "16 TiB - 4 KiB") {
t.Fatalf("blocks %d: want capacity refusal, got %v", blocks, err)
}
if _, ok, e := c.ReadVolume(ctx, "too-large"); e != nil || ok {
t.Fatalf("refusal changed catalog: exists=%v err=%v", ok, e)
}
}
}
@@ -1,5 +1,26 @@
package durable
import (
"context"
"time"
"github.com/seaweedfs/seaweed-block/core/frontend"
)
// SetTestAfterChunkResolve installs the test-only hook CutVolume runs right
// after it resolves the volume's handle and layer.
func SetTestAfterChunkResolve(p *DurableProvider, f func()) { p.testAfterChunkResolve = f }
// SetTestDetachStopIO replaces DetachVolume's StopIO call (test-only).
func SetTestDetachStopIO(p *DurableProvider, f func(ctx context.Context) error) {
p.testDetachStopIO = f
}
// SetTestDetachTrace observes DetachVolume's stages and deadlines (test-only).
func SetTestDetachTrace(p *DurableProvider, f func(stage string, deadline time.Time)) {
p.testDetachTrace = f
}
// SetTestBeforeIOLock runs f in the backend's admission, right before the I/O
// lock (test-only).
func SetTestBeforeIOLock(b frontend.Backend, f func()) { b.(*StorageBackend).testBeforeIOLock = f }
@@ -38,6 +38,7 @@ import (
"time"
"github.com/seaweedfs/seaweed-block/core/frontend"
"github.com/seaweedfs/seaweed-block/core/geometry"
"github.com/seaweedfs/seaweed-block/core/storage"
"github.com/seaweedfs/seaweed-block/core/storage/parallelwal"
"github.com/seaweedfs/seaweed-block/core/storage/smartwal"
@@ -81,6 +82,14 @@ var ErrImplKindMismatch = errors.New("durable: impl kind mismatch between select
// volumeID has not been Open'd.
var ErrVolumeNotOpen = errors.New("durable: volume not opened")
// ErrDetachAborted: the detach did not happen (its final cut provably did not
// publish), so the volume resumed serving on this host (MIGRATION E4).
var ErrDetachAborted = errors.New("durable: detach aborted; the volume keeps serving on this host")
// ErrDetachOutcomeUnknown: whether the detach landed cannot be decided yet;
// I/O stays stopped (never resumed on a possibly detached HEAD).
var ErrDetachOutcomeUnknown = errors.New("durable: detach outcome unknown; I/O stays stopped")
// ProviderConfig configures a DurableProvider.
type ProviderConfig struct {
// Impl selects which LogicalStorage implementation to open or
@@ -157,6 +166,13 @@ type ProviderConfig struct {
// passed since the volume's last successful cut (of any kind). Zero
// disables the timer.
ChunkCaptureInterval time.Duration
// DetachFreezeTimeout bounds how long a failing DetachVolume keeps guest
// I/O stopped before it resumes or settles: the drain and final cut get
// three quarters of it, the settlement of a failed cut the rest (the
// caller's context can only shorten the cut part). Zero: 20 s, below the
// host's 30 s I/O timeout; a freeze past the 5 s target is logged as an
// alarm. Cooperative: a syscall that never returns is not bounded.
DetachFreezeTimeout time.Duration
// ChunkDirtyThreshold is the bound on one cut's barrier copy, in
// chunks. It never triggers a cut: the remote holds snapshots, and
// cuts are published only by CaptureVolume, MakeVolumeRemoteDurable
@@ -179,6 +195,11 @@ type DurableProvider struct {
// testAfterChunkResolve, test-only, runs in CutVolume right after the
// volume's handle and layer are resolved.
testAfterChunkResolve func()
// testDetachStopIO, test-only, replaces DetachVolume's StopIO call (so a
// test can force the failed-drain branch); testDetachTrace, test-only,
// observes the detach's stages and their deadlines ("cut", "settle").
testDetachStopIO func(ctx context.Context) error
testDetachTrace func(stage string, deadline time.Time)
// testBeforeChunkFreshRetire holds the real post-presence/pre-marker boundary.
testBeforeChunkFreshRetire func() error
@@ -596,6 +617,13 @@ func (p *DurableProvider) openOrCreate(volumeID string) (*volHandle, error) {
}
return h, nil
}
// Existing storage ignores create geometry; admission precedes all fresh sidecars.
if p.cfg.NumBlocks == 0 {
return nil, fmt.Errorf("durable: NumBlocks=0; cannot create storage for %s (use open-existing mode)", volumeID)
}
if err := geometry.ValidateBlockGeometry(uint64(p.cfg.NumBlocks), uint64(p.cfg.BlockSize)); err != nil {
return nil, err
}
if p.cfg.Impl == ImplWALStoreChunk {
// Durable before the volume file exists: a crash anywhere between
// here and the first successful attach leaves a fresh volume.
@@ -262,15 +262,22 @@ func (p *DurableProvider) attachChunk(ctx context.Context, volumeID string, h *v
h.backend.mu.Lock()
h.backend.chunkFenced = layer.Fenced
h.backend.mu.Unlock()
if p.cfg.ChunkCaptureInterval > 0 {
loopCtx, cancel := context.WithCancel(context.Background())
h.chunkStop, h.chunkDone = cancel, make(chan struct{})
go p.chunkLoop(loopCtx, volumeID, layer, h.chunkDone)
}
p.startChunkLoop(volumeID, h, layer)
}
return nil
}
// startChunkLoop starts the periodic cuts of an attached layer, if configured
// and not already running. The caller holds h.attachMu and p.mu.
func (p *DurableProvider) startChunkLoop(volumeID string, h *volHandle, layer storage.ChunkLayer) {
if p.cfg.ChunkCaptureInterval <= 0 || h.chunkStop != nil {
return
}
loopCtx, cancel := context.WithCancel(context.Background())
h.chunkStop, h.chunkDone = cancel, make(chan struct{})
go p.chunkLoop(loopCtx, volumeID, layer, h.chunkDone)
}
func (p *DurableProvider) newChunkLayer(ctx context.Context, volumeID string, h *volHandle) (storage.ChunkLayer, error) {
ws, ok := h.storage.(*storage.WALStore)
if !ok {
@@ -743,12 +750,19 @@ func (p *DurableProvider) CutVolume(ctx context.Context, volumeID string, minLSN
}
// DetachVolume is a clean stop's final cut (B9 W2 §3.6): it stops the
// volume's frontend I/O and waits (bounded by ctx) for the I/O already
// admitted to finish, stops the periodic cuts, then publishes one cut with
// HEAD state detached. It also returns the last LSN written. From its
// start, the volume stays stopped for this process, through any later
// RecoverVolume, even when the detach fails; a retry settles it and a
// repeated call returns the first result.
// volume's frontend I/O and waits for the I/O already admitted to finish,
// stops the periodic cuts, then publishes one cut with HEAD state detached.
// It also returns the last LSN written. The freeze (drain + final cut) is
// bounded by DetachFreezeTimeout and ctx. After a successful detach the
// volume stays stopped for this process, through any later RecoverVolume,
// and a repeated call returns the first result. A failed detach never leaves
// the guest frozen by a detach that did not happen (MIGRATION E4):
// - nothing published (the drain or the cut failed before its CAS, or the
// CAS was refused, or an unresolved detach CAS was cancelled): serving
// resumes and ErrDetachAborted is returned;
// - the detach CAS applied (its reply was lost): the detached result;
// - HEAD belongs to another holder: stays stopped (fenced);
// - undecidable (HEAD unreadable): stays stopped, ErrDetachOutcomeUnknown.
func (p *DurableProvider) DetachVolume(ctx context.Context, volumeID string) (storage.ChunkCutResult, uint64, error) {
p.mu.Lock()
h, ok := p.volumes[volumeID]
@@ -762,16 +776,83 @@ func (p *DurableProvider) DetachVolume(ctx context.Context, volumeID string) (st
if err != nil {
return storage.ChunkCutResult{}, 0, err
}
freeze := p.cfg.DetachFreezeTimeout
if freeze <= 0 {
freeze = defaultDetachFreezeTimeout
}
// One freeze budget covers the drain, the final cut AND the settlement:
// the cut gets three quarters, the settlement what is left. The bound is
// cooperative (contexts): a syscall that never returns is not bounded here.
start := time.Now()
cutCtx, cancel := context.WithDeadline(ctx, start.Add(freeze*3/4))
defer cancel()
defer func() {
if d := time.Since(start); d > detachFreezeTarget {
log.Printf("durable: ALARM detach of volume=%s held guest I/O for %s (target %s, bound %s)", volumeID, d.Round(time.Millisecond), detachFreezeTarget, freeze)
}
}()
if trace := p.testDetachTrace; trace != nil {
dl, _ := cutCtx.Deadline()
trace("cut", dl)
}
h.chunkDetach = true
if err := h.backend.StopIO(ctx, "chunk detach: I/O stopped until a new attach"); err != nil {
return storage.ChunkCutResult{}, 0, err
if stop := p.testDetachStopIO; stop != nil {
err = stop(cutCtx)
} else {
err = h.backend.StopIO(cutCtx, "chunk detach: I/O stopped until a new attach")
}
p.stopChunkLoop(h)
r, err := layer.Detach(ctx)
if err != nil {
return storage.ChunkCutResult{}, 0, err
if err == nil {
p.stopChunkLoop(h)
var r storage.ChunkCutResult
if r, err = layer.Detach(cutCtx); err == nil {
return r, h.storage.NextLSN() - 1, nil
}
}
return r, h.storage.NextLSN() - 1, nil
// Every failure, a failed drain included, is settled before anything
// resumes: an earlier detach that applied, an unresolved detach CAS or a
// fenced layer must never resume serving. The settlement keeps the rest
// of the freeze budget even when the caller's context is gone.
sctx, scancel := context.WithDeadline(context.WithoutCancel(ctx), start.Add(freeze))
defer scancel()
if trace := p.testDetachTrace; trace != nil {
dl, _ := sctx.Deadline()
trace("settle", dl)
}
how, dr, serr := layer.SettleDetach(sctx)
switch {
case serr != nil:
return storage.ChunkCutResult{}, 0, fmt.Errorf("%w: %w (settle: %w)", ErrDetachOutcomeUnknown, err, serr)
case how == storage.DetachApplied:
return dr, h.storage.NextLSN() - 1, nil
case how == storage.DetachFenced:
return storage.ChunkCutResult{}, 0, fmt.Errorf("durable: detach of %s: HEAD belongs to a newer epoch or another holder; I/O stays stopped: %w: %w", volumeID, storage.ErrChunkLayerFenced, err)
default:
return storage.ChunkCutResult{}, 0, p.resumeAfterDetach(volumeID, h, layer, err)
}
}
const (
defaultDetachFreezeTimeout = 20 * time.Second
detachFreezeTarget = 5 * time.Second
)
// resumeAfterDetach undoes a detach that provably did not happen: the
// periodic cuts restart, the stop is lifted, and the volume serves again.
// The caller holds h.attachMu.
func (p *DurableProvider) resumeAfterDetach(volumeID string, h *volHandle, layer storage.ChunkLayer, cause error) error {
p.mu.Lock()
closed := p.closed || h.chunk != layer
if !closed {
p.startChunkLoop(volumeID, h, layer)
}
p.mu.Unlock()
if closed { // a concurrent Close or detach of the layer owns the volume now
return fmt.Errorf("durable: detach of %s aborted while the provider closed: %w", volumeID, cause)
}
h.chunkDetach = false
h.backend.SetOperational(true, "chunk detach aborted: serving resumed")
log.Printf("durable: detach of volume=%s aborted, nothing published; serving resumed: %v", volumeID, cause)
return fmt.Errorf("%w: %w", ErrDetachAborted, cause)
}
// Preserve the optional manifest capability only when the inner remote has it;
@@ -0,0 +1,423 @@
package durable_test
// A failed detach (design MIGRATION E4, review S6): the guest is never left
// frozen by a detach that did not happen. When the final cut provably did not
// publish (a failed upload, a refused CAS, an unresolved detach CAS that a
// cancel at the same base settles), serving resumes on this host. When the
// detach landed, the volume stays stopped with the detached result. When the
// outcome cannot be decided (HEAD unreadable), it stays stopped: never resume
// on top of a possibly detached HEAD.
import (
"context"
"errors"
"sync"
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/frontend"
"github.com/seaweedfs/seaweed-block/core/frontend/durable"
"github.com/seaweedfs/seaweed-block/core/storage"
)
// faultRemote injects one fault into the next detach's remote calls.
type faultRemote struct {
*storage.MemChunkRemote
mu sync.Mutex
putErr error // returned by every Put while set
casMode string // "", "precondition", "lost" (not applied, error), "applied-lost" (applied, error), "hold"
getHeadErr error // returned by every GetHead while set
getHeadFail int // the next N GetHead calls fail
getHeadHold bool // every GetHead blocks until its caller gives up
// "delayed": the CAS's reply is lost now, the CAS itself reaches the
// remote only when release closes; its own result goes to delayedErr.
release chan struct{}
delayedErr chan error
}
var errInjected = errors.New("injected remote fault")
func (r *faultRemote) set(f func(r *faultRemote)) { r.mu.Lock(); f(r); r.mu.Unlock() }
func (r *faultRemote) Put(ctx context.Context, key string, data []byte) error {
r.mu.Lock()
err := r.putErr
r.mu.Unlock()
if err != nil {
return err
}
return r.MemChunkRemote.Put(ctx, key, data)
}
func (r *faultRemote) GetHead(ctx context.Context) (storage.ChunkHead, error) {
r.mu.Lock()
hold := r.getHeadHold
err := r.getHeadErr
if err == nil && r.getHeadFail > 0 {
r.getHeadFail--
err = errInjected
}
r.mu.Unlock()
if hold {
<-ctx.Done()
return storage.ChunkHead{}, ctx.Err()
}
if err != nil {
return storage.ChunkHead{}, err
}
return r.MemChunkRemote.GetHead(ctx)
}
func (r *faultRemote) CASHead(ctx context.Context, expected storage.ChunkHeadVersion, next storage.ChunkHead) (uint64, error) {
r.mu.Lock()
mode := r.casMode
r.casMode = "" // one fault, on the next CAS only
r.mu.Unlock()
switch mode {
case "precondition":
return 0, storage.ErrChunkHeadPrecondition
case "lost":
return 0, errInjected
case "hold": // held until the caller gives up: not applied
<-ctx.Done()
return 0, ctx.Err()
case "delayed":
r.mu.Lock()
release, out := r.release, r.delayedErr
r.mu.Unlock()
go func() {
<-release
_, err := r.MemChunkRemote.CASHead(context.Background(), expected, next)
out <- err
}()
return 0, errInjected
case "applied-lost":
if _, err := r.MemChunkRemote.CASHead(ctx, expected, next); err != nil {
return 0, err
}
return 0, errInjected
}
return r.MemChunkRemote.CASHead(ctx, expected, next)
}
// detachFixture: a chunk volume with one cut published and one more write
// (dirty), so the detach's final cut has something to upload.
func detachFixture(t *testing.T) (*faultRemote, *durable.DurableProvider, frontend.Backend) {
t.Helper()
remote := &faultRemote{MemChunkRemote: storage.NewMemChunkRemote()}
p := chunkProvider(t, t.TempDir(), remote, v1View(), 0)
openRecovered(t, p)
b, err := p.Open(context.Background(), "v1")
if err != nil {
t.Fatal(err)
}
if _, err := b.Write(context.Background(), 4096, block(1)); err != nil {
t.Fatal(err)
}
if _, err := p.CutVolume(context.Background(), "v1", 0); err != nil {
t.Fatal(err)
}
if _, err := b.Write(context.Background(), 8192, block(2)); err != nil {
t.Fatal(err)
}
return remote, p, b
}
// assertServing: the volume accepts writes and a cut publishes them, with a
// HEAD that is not detached.
func assertServing(t *testing.T, p *durable.DurableProvider, b frontend.Backend, remote *faultRemote) {
t.Helper()
ctx := context.Background()
if _, err := b.Write(ctx, 12288, block(3)); err != nil {
t.Fatalf("write after an aborted detach: %v; want the volume serving again", err)
}
r, err := p.CutVolume(ctx, "v1", 0)
if err != nil {
t.Fatalf("cut after an aborted detach: %v", err)
}
if r.Head.State == storage.ChunkHeadDetached {
t.Fatal("HEAD is detached after a detach that was reported aborted")
}
if !bytesEqual(headBlock(t, remote.MemChunkRemote, 2), block(2)) || !bytesEqual(headBlock(t, remote.MemChunkRemote, 3), block(3)) {
t.Fatal("the cut after an aborted detach lost the dirty blocks")
}
}
func TestWALStoreChunk_FailedDetachUploadResumes(t *testing.T) {
remote, p, b := detachFixture(t)
remote.set(func(r *faultRemote) { r.putErr = errInjected })
if _, _, err := p.DetachVolume(context.Background(), "v1"); !errors.Is(err, durable.ErrDetachAborted) {
t.Fatalf("detach with failing uploads: %v; want ErrDetachAborted", err)
}
remote.set(func(r *faultRemote) { r.putErr = nil })
assertServing(t, p, b, remote)
}
func TestWALStoreChunk_RefusedDetachCASResumes(t *testing.T) {
remote, p, b := detachFixture(t)
remote.set(func(r *faultRemote) { r.casMode = "precondition" })
if _, _, err := p.DetachVolume(context.Background(), "v1"); !errors.Is(err, durable.ErrDetachAborted) {
t.Fatalf("detach with a refused CAS: %v; want ErrDetachAborted", err)
}
assertServing(t, p, b, remote)
}
// The detach CAS's reply is lost and it did not apply: the settle cancels it
// with a CAS at the same base, so it can never land, and serving resumes.
func TestWALStoreChunk_LostDetachCASNotAppliedIsCancelledAndResumes(t *testing.T) {
remote, p, b := detachFixture(t)
base, _ := remote.MemChunkRemote.GetHead(context.Background())
remote.set(func(r *faultRemote) { r.casMode = "lost" })
if _, _, err := p.DetachVolume(context.Background(), "v1"); !errors.Is(err, durable.ErrDetachAborted) {
t.Fatalf("detach with a lost, unapplied CAS: %v; want ErrDetachAborted after the cancel", err)
}
// The cancel is a real CAS at the detach's base: HEAD moved one generation
// and is not detached, so the lost detach CAS can never land afterwards.
if head, _ := remote.MemChunkRemote.GetHead(context.Background()); head.State == storage.ChunkHeadDetached || head.Gen != base.Gen+1 {
t.Fatalf("HEAD after the cancel: gen %d state %q; want gen %d, not detached", head.Gen, head.State, base.Gen+1)
}
assertServing(t, p, b, remote)
}
// The detach CAS's reply is lost but it applied: the detach succeeded, the
// volume stays stopped and DetachVolume returns the detached result.
func TestWALStoreChunk_LostDetachCASAppliedStaysDetached(t *testing.T) {
remote, p, b := detachFixture(t)
remote.set(func(r *faultRemote) { r.casMode = "applied-lost" })
r, _, err := p.DetachVolume(context.Background(), "v1")
if err != nil || r.Head.State != storage.ChunkHeadDetached {
t.Fatalf("detach whose CAS applied but lost its reply: %+v %v; want the detached result", r, err)
}
if _, err := b.Write(context.Background(), 12288, block(3)); !errors.Is(err, frontend.ErrNotReady) {
t.Fatalf("write after an applied detach: %v; want ErrNotReady", err)
}
}
// The detach CAS applied but its reply was lost AND the cut's own HEAD re-read
// failed: only the settle can tell. It reads HEAD, finds the detach, and the
// detach succeeds (stays stopped) instead of resuming on a detached HEAD.
func TestWALStoreChunk_LostDetachCASAppliedFoundBySettle(t *testing.T) {
remote, p, b := detachFixture(t)
remote.set(func(r *faultRemote) { r.casMode = "applied-lost"; r.getHeadFail = 1 })
r, _, err := p.DetachVolume(context.Background(), "v1")
if err != nil || r.Head.State != storage.ChunkHeadDetached {
t.Fatalf("detach whose applied CAS only the settle can see: %+v %v; want the detached result", r, err)
}
if _, err := b.Write(context.Background(), 12288, block(3)); !errors.Is(err, frontend.ErrNotReady) {
t.Fatalf("write after a settled, applied detach: %v; want ErrNotReady", err)
}
}
// The detach CAS's reply is lost and HEAD cannot be read: the outcome is
// unknown, so the volume stays stopped (also through a recovery).
func TestWALStoreChunk_UndecidableDetachStaysStopped(t *testing.T) {
remote, p, b := detachFixture(t)
remote.set(func(r *faultRemote) { r.casMode = "lost"; r.getHeadErr = errInjected })
if _, _, err := p.DetachVolume(context.Background(), "v1"); !errors.Is(err, durable.ErrDetachOutcomeUnknown) {
t.Fatalf("detach with an undecidable outcome: %v; want ErrDetachOutcomeUnknown", err)
}
if _, err := b.Write(context.Background(), 12288, block(3)); !errors.Is(err, frontend.ErrNotReady) {
t.Fatalf("write after an undecidable detach: %v; want ErrNotReady", err)
}
if _, err := p.RecoverVolume(context.Background(), "v1"); !errors.Is(err, storage.ErrChunkLayerDetached) {
t.Fatalf("recovery after an undecidable detach: %v; want the volume to stay stopped", err)
}
}
// The freeze is bounded by DetachFreezeTimeout: a CAS that hangs ends there,
// the outcome is settled (HEAD still at base: cancelled) and serving resumes,
// all well inside bound + settle.
func TestWALStoreChunk_DetachFreezeIsBoundedThenResumes(t *testing.T) {
remote := &faultRemote{MemChunkRemote: storage.NewMemChunkRemote()}
p, err := durable.NewDurableProvider(durable.ProviderConfig{
Impl: durable.ImplWALStoreChunk,
StorageRoot: t.TempDir(),
BlockSize: 4096,
NumBlocks: pcBlocks,
ChunkBlocks: pcChunkBlocks,
DetachFreezeTimeout: 300 * time.Millisecond,
ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil },
}, v1View())
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = p.Close() })
openRecovered(t, p)
b, err := p.Open(context.Background(), "v1")
if err != nil {
t.Fatal(err)
}
if _, err := b.Write(context.Background(), 4096, block(1)); err != nil {
t.Fatal(err)
}
if _, err := p.CutVolume(context.Background(), "v1", 0); err != nil {
t.Fatal(err)
}
if _, err := b.Write(context.Background(), 8192, block(2)); err != nil {
t.Fatal(err)
}
remote.set(func(r *faultRemote) { r.casMode = "hold" })
start := time.Now()
_, _, err = p.DetachVolume(context.Background(), "v1")
took := time.Since(start)
if !errors.Is(err, durable.ErrDetachAborted) || !errors.Is(err, context.DeadlineExceeded) {
t.Fatalf("detach with a hung CAS: %v; want an aborted detach at the freeze bound", err)
}
// The cut gets three quarters of the bound, the settlement the rest.
if took < 225*time.Millisecond || took > 300*time.Millisecond+200*time.Millisecond {
t.Fatalf("detach with a hung CAS took %v; want the cut ended at 3/4 of the 300 ms freeze bound and the total within it", took)
}
assertServing(t, p, b, remote)
}
// HEAD belongs to a newer epoch: the detach's CAS is refused and the volume
// is fenced; it stays stopped (never resumes against another holder).
func TestWALStoreChunk_DetachAgainstNewerEpochStaysStopped(t *testing.T) {
remote, p, b := detachFixture(t)
ctx := context.Background()
cur, err := remote.MemChunkRemote.GetHead(ctx)
if err != nil {
t.Fatal(err)
}
newer := cur
newer.Epoch, newer.Holder = cur.Epoch+1, "another-holder"
if _, err := remote.MemChunkRemote.CASHead(ctx, storage.ChunkHeadVersion{Gen: cur.Gen, Epoch: cur.Epoch}, newer); err != nil {
t.Fatal(err)
}
if _, _, err := p.DetachVolume(ctx, "v1"); !errors.Is(err, storage.ErrChunkLayerFenced) || errors.Is(err, durable.ErrDetachAborted) {
t.Fatalf("detach against a newer epoch: %v; want fenced, not aborted", err)
}
if _, err := b.Write(ctx, 12288, block(3)); !errors.Is(err, frontend.ErrNotReady) && !errors.Is(err, frontend.ErrStalePrimary) {
t.Fatalf("write after a fenced detach: %v; want it refused (not ready / stale primary)", err)
}
}
// P1 (review): a repeated detach after a successful one, with a cancelled
// context (its StopIO fails at once), returns the first result and never
// resumes serving.
func TestWALStoreChunk_RepeatDetachWithCancelledContextNeverResumes(t *testing.T) {
_, p, b := detachFixture(t)
r1, _, err := p.DetachVolume(context.Background(), "v1")
if err != nil {
t.Fatal(err)
}
forced := false
durable.SetTestDetachStopIO(p, func(context.Context) error { forced = true; return context.Canceled }) // the drain fails
r2, _, err := p.DetachVolume(context.Background(), "v1")
if !forced {
t.Fatal("the failed-drain branch was not taken")
}
if err != nil || r2.Head.Gen != r1.Head.Gen || r2.Head.State != storage.ChunkHeadDetached {
t.Fatalf("repeated detach with a cancelled context: %+v %v; want the first result %+v", r2, err, r1)
}
if _, err := b.Write(context.Background(), 12288, block(3)); !errors.Is(err, frontend.ErrNotReady) {
t.Fatalf("write after a repeated detach: %v; want ErrNotReady (never resumed)", err)
}
}
// P1 (review): after an undecidable detach, a retry whose StopIO fails (a
// cancelled context) settles first and stays stopped while the outcome is
// still unknown.
func TestWALStoreChunk_RetryAfterUndecidableDetachNeverResumes(t *testing.T) {
remote, p, b := detachFixture(t)
remote.set(func(r *faultRemote) { r.casMode = "lost"; r.getHeadErr = errInjected })
if _, _, err := p.DetachVolume(context.Background(), "v1"); !errors.Is(err, durable.ErrDetachOutcomeUnknown) {
t.Fatalf("first detach: %v; want ErrDetachOutcomeUnknown", err)
}
forced := false
durable.SetTestDetachStopIO(p, func(context.Context) error { forced = true; return context.Canceled }) // the drain fails
_, _, err := p.DetachVolume(context.Background(), "v1")
if !forced {
t.Fatal("the failed-drain branch was not taken")
}
if !errors.Is(err, durable.ErrDetachOutcomeUnknown) || errors.Is(err, durable.ErrDetachAborted) {
t.Fatalf("retry over an unresolved detach CAS: %v; want still unknown, never aborted", err)
}
if _, err := b.Write(context.Background(), 12288, block(3)); !errors.Is(err, frontend.ErrNotReady) {
t.Fatalf("write after a retry over an unknown detach: %v; want ErrNotReady", err)
}
}
// P1 (review): one freeze budget covers the cut AND the settlement: with the
// CAS and every HEAD read hung, DetachVolume returns within the bound (here
// undecided, so the volume stays stopped).
func TestWALStoreChunk_DetachFreezeBoundCoversTheSettle(t *testing.T) {
const freeze = 400 * time.Millisecond
remote := &faultRemote{MemChunkRemote: storage.NewMemChunkRemote()}
p, err := durable.NewDurableProvider(durable.ProviderConfig{
Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), BlockSize: 4096, NumBlocks: pcBlocks, ChunkBlocks: pcChunkBlocks,
DetachFreezeTimeout: freeze,
ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil },
}, v1View())
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = p.Close() })
openRecovered(t, p)
b, err := p.Open(context.Background(), "v1")
if err != nil {
t.Fatal(err)
}
if _, err := b.Write(context.Background(), 4096, block(1)); err != nil {
t.Fatal(err)
}
remote.set(func(r *faultRemote) { r.casMode = "hold"; r.getHeadHold = true })
deadlines := map[string]time.Time{}
durable.SetTestDetachTrace(p, func(stage string, d time.Time) { deadlines[stage] = d })
start := time.Now()
_, _, err = p.DetachVolume(context.Background(), "v1")
took := time.Since(start)
cutAt, settleAt := deadlines["cut"].Sub(start), deadlines["settle"].Sub(start)
if cutAt < freeze*3/4-50*time.Millisecond || cutAt > freeze*3/4+50*time.Millisecond || settleAt < freeze-50*time.Millisecond || settleAt > freeze+50*time.Millisecond {
t.Fatalf("deadlines: cut %v, settle %v after the start; want three quarters of the %v freeze, then the bound", cutAt, settleAt, freeze)
}
if !errors.Is(err, durable.ErrDetachOutcomeUnknown) {
t.Fatalf("detach with a hung CAS and hung HEAD reads: %v; want the outcome unknown", err)
}
if took > freeze+200*time.Millisecond {
t.Fatalf("detach took %v; the %v freeze bound must cover the settlement too", took, freeze)
}
if _, err := b.Write(context.Background(), 8192, block(2)); !errors.Is(err, frontend.ErrNotReady) {
t.Fatalf("write after an undecided detach: %v; want ErrNotReady", err)
}
}
// P2 (review): the lost detach CAS really is in flight. It reaches the remote
// only after the cancel landed, and then fails its precondition: HEAD stays
// active.
func TestWALStoreChunk_DelayedDetachCASCannotLandAfterTheCancel(t *testing.T) {
remote, p, b := detachFixture(t)
release, delayed := make(chan struct{}), make(chan error, 1)
var once sync.Once
unblock := func() { once.Do(func() { close(release) }) }
joined := false
t.Cleanup(func() { // join the delayed CAS worker, bounded
unblock()
if !joined {
select {
case <-delayed:
case <-time.After(5 * time.Second):
t.Error("delayed CAS worker not joined")
}
}
})
remote.set(func(r *faultRemote) { r.casMode = "delayed"; r.release, r.delayedErr = release, delayed })
if _, _, err := p.DetachVolume(context.Background(), "v1"); !errors.Is(err, durable.ErrDetachAborted) {
t.Fatalf("detach with a delayed CAS: %v; want ErrDetachAborted after the cancel", err)
}
unblock()
var derr error
select {
case derr = <-delayed:
joined = true
case <-time.After(5 * time.Second):
t.Fatal("the delayed detach CAS did not complete after its release")
}
if !errors.Is(derr, storage.ErrChunkHeadPrecondition) {
t.Fatalf("the delayed detach CAS after the cancel: %v; want a precondition failure", derr)
}
if head, _ := remote.MemChunkRemote.GetHead(context.Background()); head.State == storage.ChunkHeadDetached {
t.Fatal("the delayed detach CAS landed after the cancel")
}
assertServing(t, p, b, remote)
}
@@ -118,10 +118,11 @@ func TestWALStoreChunk_DetachDrainsAdmittedWrite(t *testing.T) {
}
}
// The drain is bounded by the caller's context: a detach that cannot drain
// fails, publishes nothing and keeps I/O stopped, also through a recovery;
// once the admitted write finishes, a retry settles the detach with it.
func TestWALStoreChunk_DetachDrainIsBoundedAndStaysStopped(t *testing.T) {
// The drain is bounded (the caller's context or the freeze bound): a detach
// that cannot drain publishes nothing, so it aborts and the volume serves
// again (MIGRATION E4; it used to stay stopped, review S6); once the admitted
// write finishes, a retry detaches with every acknowledged write.
func TestWALStoreChunk_DetachDrainTimeoutAbortsAndResumes(t *testing.T) {
ctx := context.Background()
remote := storage.NewMemChunkRemote()
p, view := parkedProvider(t, remote)
@@ -139,21 +140,54 @@ func TestWALStoreChunk_DetachDrainIsBoundedAndStaysStopped(t *testing.T) {
dctx, cancel := context.WithTimeout(ctx, 100*time.Millisecond)
_, _, err = p.DetachVolume(dctx, "v1")
cancel()
if !errors.Is(err, context.DeadlineExceeded) {
t.Fatalf("detach that cannot drain: %v; want the context's deadline", err)
if !errors.Is(err, context.DeadlineExceeded) || !errors.Is(err, durable.ErrDetachAborted) {
t.Fatalf("detach that cannot drain: %v; want an aborted detach on the context's deadline", err)
}
if head, _ := remote.GetHead(ctx); head.State == storage.ChunkHeadDetached {
t.Fatalf("a detach that did not drain published a detached HEAD: %+v", head)
}
if _, err := p.RecoverVolume(ctx, "v1"); !errors.Is(err, storage.ErrChunkLayerDetached) {
t.Fatalf("recovery after a failed detach: %v; want the volume to stay stopped", err)
// Serving resumes: a new write is accepted. The drain still pending from
// the aborted stop orders new I/O after the I/O admitted before it, so
// this write completes once that admitted write does (never on the
// detach itself).
arrived := make(chan struct{})
var arriveOnce sync.Once
durable.SetTestBeforeIOLock(b, func() { arriveOnce.Do(func() { close(arrived) }) })
nerr := make(chan error, 1)
go func() { _, err := b.Write(ctx, 8192, block(6)); nerr <- err }()
bounded := func(what string, ch <-chan struct{}) {
t.Helper()
select {
case <-ch:
case <-time.After(5 * time.Second):
t.Fatalf("%s did not happen within 5s", what)
}
}
if _, err := b.Write(ctx, 8192, block(6)); !errors.Is(err, frontend.ErrNotReady) {
t.Fatalf("new write after a failed detach and a recovery: %v; want ErrNotReady", err)
bounded("the new write passing the operational gate (serving resumed)", arrived)
select {
case err := <-nerr:
t.Fatalf("new write completed (%v) ahead of the write admitted before the stop", err)
default: // queued behind the admitted write at the I/O lock, as the drain orders it
}
view.unpark()
acked := <-werr == nil
recv := func(what string, ch <-chan error) error {
t.Helper()
select {
case err := <-ch:
return err
case <-time.After(5 * time.Second):
t.Fatalf("%s did not complete within 5s", what)
return nil
}
}
acked := recv("the admitted write", werr) == nil
if err := recv("the new write", nerr); err != nil {
t.Fatalf("new write after an aborted detach: %v; want it accepted", err)
}
if _, err := p.RecoverVolume(ctx, "v1"); err != nil {
t.Fatalf("recovery after an aborted detach: %v; want it to succeed", err)
}
o := detachOutcome{}
o.r, o.last, o.err = p.DetachVolume(ctx, "v1")
if o.err != nil || o.r.Head.State != storage.ChunkHeadDetached {
@@ -162,6 +196,9 @@ func TestWALStoreChunk_DetachDrainIsBoundedAndStaysStopped(t *testing.T) {
if acked && !bytesEqual(headBlock(t, remote, 1), block(5)) {
t.Fatal("the write admitted before the stop was acknowledged but is not in the detached HEAD")
}
if !bytesEqual(headBlock(t, remote, 2), block(6)) {
t.Fatal("the write accepted after the aborted detach is not in the detached HEAD")
}
}
// After a successful detach, RecoverVolume keeps I/O stopped and a repeated
@@ -0,0 +1,190 @@
package durable_test
import (
"bytes"
"context"
"encoding/binary"
"fmt"
"github.com/seaweedfs/seaweed-block/core/frontend/durable"
"github.com/seaweedfs/seaweed-block/core/frontend/nvme"
"github.com/seaweedfs/seaweed-block/core/recovery"
"github.com/seaweedfs/seaweed-block/core/storage"
"runtime"
"sort"
"testing"
"time"
)
// Public provider + actual NVMe handler, file-backed v3 with the default
// 64 MiB WAL. No injected I/O failures, private selector, or flusher control.
func TestWALStoreChunkV3_NoClientFlushBurst(t *testing.T) {
for _, mode := range []storage.WMode{storage.WModeLagged, storage.WModeStrict} {
t.Run(fmt.Sprintf("mode-%d", mode), func(t *testing.T) {
runNoClientFlushBurst(t, mode)
})
}
}
func runNoClientFlushBurst(t *testing.T, mode storage.WMode) {
const total = 400 * 1024 * 1024
const transfer = 128 * 1024
ctx := context.Background()
remote := storage.NewMemChunkRemote()
p, err := durable.NewDurableProvider(durable.ProviderConfig{
Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), BlockSize: 4096,
NumBlocks: (1 << 30) / 4096, ChunkBlocks: 1024, ChunkCaptureInterval: 0,
ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil },
}, v1View())
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() {
if err := p.Close(); err != nil {
t.Logf("close: %v", err)
}
})
s, err := p.EnsureStorage("v1")
if err != nil {
t.Fatal(err)
}
if _, err = p.RecoverVolume(ctx, "v1"); err != nil {
t.Fatal(err)
}
be, err := p.Open(ctx, "v1")
if err != nil {
t.Fatal(err)
}
before, err := remote.GetHead(ctx)
if err != nil {
t.Fatal(err)
}
ws := s.(*storage.WALStore)
if err := ws.SetWMode(mode); err != nil {
t.Fatal(err)
}
syncsBefore := ws.WALSyncCount()
var durations []time.Duration
t.Logf("before HEAD gen=%d remoteLSN=%d cp=%d next=%d retention=%d", before.Gen, before.RemoteLSN, ws.CheckpointLSN(), ws.NextLSN(), ws.RecoveryRetentionLSNs())
h := nvme.NewIOHandler(nvme.HandlerConfig{Backend: be, BlockSize: 4096, VolumeSize: 1 << 30})
data := make([]byte, transfer)
start := time.Now()
for off := 0; off < total; off += transfer {
for i := range data {
if i%8 == 0 {
binary.LittleEndian.PutUint64(data[i:i+8], uint64(off+i))
}
}
writeStart := time.Now()
r := h.Handle(ctx, nvme.IOCommand{Opcode: 0x01, NSID: 1, SLBA: uint64(off / 4096), NLB: transfer / 4096, Data: data})
durations = append(durations, time.Since(writeStart))
if r.AsError() != nil {
dump := make([]byte, 2<<20)
n := runtime.Stack(dump, true)
t.Logf("TIMEOUT STACKS\n%s", dump[:n])
t.Fatalf("NO FLUSH write bytes=%d elapsed=%v result=%+v cp=%d next=%d", off, time.Since(start), r, ws.CheckpointLSN(), ws.NextLSN())
}
if (off+transfer)%(16*1024*1024) == 0 {
t.Logf("NO FLUSH progress bytes=%d elapsed=%v cp=%d next=%d", off+transfer, time.Since(start), ws.CheckpointLSN(), ws.NextLSN())
}
}
// The expected bytes come from the submitted pattern, not another reader.
for off := 0; off < total; off += transfer {
got := make([]byte, transfer)
n, err := be.Read(ctx, int64(off), got)
if err != nil {
t.Fatalf("readback at%d: %v", off, err)
}
if n != transfer {
t.Fatalf("short readback at%d: %d", off, n)
}
for i := 0; i < len(got); i += 8 {
if value := binary.LittleEndian.Uint64(got[i : i+8]); value != uint64(off+i) {
t.Fatalf("readback offset%d got%d", off+i, value)
}
}
}
sort.Slice(durations, func(i, j int) bool { return durations[i] < durations[j] })
batches := ws.WALSyncCount() - syncsBefore
fsyncs := batches
if mode == storage.WModeStrict {
fsyncs *= 2
}
t.Logf("COST mode=%d bytes=%d pressureBatches=%d internalFsyncsPerGiB=%.2f writeP99=%v max=%v", mode, total, batches, float64(fsyncs)/(float64(total)/(1<<30)), durations[(len(durations)-1)*99/100], durations[len(durations)-1])
after, err := remote.GetHead(ctx)
if err != nil {
t.Fatal(err)
}
st := p.DurableStatuses()
if after.Gen != before.Gen || after.RemoteLSN != before.RemoteLSN {
t.Fatalf("remote moved without explicit cut: before=%+v after=%+v", before, after)
}
if len(st) != 1 || st[0].Chunk == nil || st[0].Chunk.Stats.CutsOK != 0 {
t.Fatalf("unexpected cuts: %+v", st)
}
if ws.CheckpointLSN() == 0 || st[0].WriteProfile.WALAppendWrapCount == 0 {
t.Fatal("no checkpoint or physical wrap observed")
}
t.Logf("after HEAD gen=%d remoteLSN=%d cp=%d next=%d wraps=%d cuts=%d", after.Gen, after.RemoteLSN, ws.CheckpointLSN(), ws.NextLSN(), st[0].WriteProfile.WALAppendWrapCount, st[0].Chunk.Stats.CutsOK)
}
// Actual RF2 coordinator pins retained history even after an internal fsync.
// Expiry is retryable; ending the session restores local no-Flush progress.
func TestWALStoreChunkV3NoFlushWithActiveRF2CatchupPin(t *testing.T) {
ctx := context.Background()
remote := storage.NewMemChunkRemote()
p, err := durable.NewDurableProvider(durable.ProviderConfig{Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), BlockSize: 4096, NumBlocks: 1 << 18, ChunkBlocks: 1024, ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil }}, v1View())
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = p.Close() })
s, err := p.EnsureStorage("v1")
if err != nil {
t.Fatal(err)
}
if _, err = p.RecoverVolume(ctx, "v1"); err != nil {
t.Fatal(err)
}
be, err := p.Open(ctx, "v1")
if err != nil {
t.Fatal(err)
}
ws := s.(*storage.WALStore)
c := recovery.NewPeerShipCoordinator()
if err := c.StartSession("r2", 1, 0, 0); err != nil {
t.Fatal(err)
}
ws.SetRecycleFloorSource(c)
h := nvme.NewIOHandler(nvme.HandlerConfig{Backend: be, BlockSize: 4096, VolumeSize: 1 << 30})
data := bytes.Repeat([]byte{0x5a}, 128*1024)
var stalled bool
for off := 0; off < 80*1024*1024; off += len(data) {
start := time.Now()
r := h.Handle(ctx, nvme.IOCommand{Opcode: 1, NSID: 1, SLBA: uint64(off / 4096), NLB: 32, Data: data})
if r.AsError() != nil {
if r.SCT != nvme.SCTGeneric || r.SC != nvme.SCNamespaceNotReady || time.Since(start) >= 5*time.Second {
t.Fatalf("pin wait status=%+v elapsed=%v", r, time.Since(start))
}
stalled = true
break
}
}
if !stalled || ws.CheckpointLSN() != 0 {
t.Fatalf("pin did not constrain checkpoint: stalled=%v cp=%d", stalled, ws.CheckpointLSN())
}
count := 0
if err := ws.ScanLBAs(1, func(e storage.RecoveryEntry) error {
count++
if !bytes.Equal(e.Data, bytes.Repeat([]byte{0x5a}, 4096)) {
return fmt.Errorf("pinned catch-up bytes changed")
}
return nil
}); err != nil || count == 0 {
t.Fatalf("retained catch-up records=%d err=%v", count, err)
}
c.EndSession("r2")
r := h.Handle(ctx, nvme.IOCommand{Opcode: 1, NSID: 1, SLBA: 20000, NLB: 32, Data: data})
if err := r.AsError(); err != nil {
t.Fatalf("no-Flush progress after catch-up release: %v", err)
}
}
@@ -146,6 +146,10 @@ const maxFullBlockBatchBlocks = 64
// StorageBackend adapts a LogicalStorage into frontend.Backend.
type StorageBackend struct {
// 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()
storage storage.LogicalStorage
view frontend.ProjectionView
id frontend.Identity
@@ -557,6 +561,9 @@ func (b *StorageBackend) Write(ctx context.Context, offset int64, p []byte) (int
b.profile.recordBackendWriteRequest(len(p))
start := time.Now()
n, err := b.writeBytes(ctx, offset, p)
if errors.Is(err, storage.ErrWALPressureTimeout) {
err = fmt.Errorf("%w: %w", frontend.ErrBackendBusy, err)
}
if n > 0 {
b.profile.recordBackendWrite(n, time.Since(start))
}
@@ -582,6 +589,9 @@ func (b *StorageBackend) admit() (func(), error) {
if err := b.readyCheck(); err != nil {
return nil, err
}
if hook := b.testBeforeIOLock; hook != nil {
hook()
}
b.ioMu.RLock()
if err := b.gate(); err != nil {
b.ioMu.RUnlock()
@@ -0,0 +1,39 @@
package durable_test
import (
"context"
"os"
"path/filepath"
"strings"
"testing"
"github.com/seaweedfs/seaweed-block/core/frontend"
"github.com/seaweedfs/seaweed-block/core/frontend/durable"
"github.com/seaweedfs/seaweed-block/core/storage"
)
func TestProviderCreateCapacityPrecedesFreshMarker(t *testing.T) {
root := t.TempDir()
id := frontend.Identity{VolumeID: "v1", ReplicaID: "r1", Epoch: 1, EndpointVersion: 1}
p, err := durable.NewDurableProvider(durable.ProviderConfig{Impl: durable.ImplWALStoreChunk, StorageRoot: root, NumBlocks: ^uint32(0), BlockSize: 8192, ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return storage.NewMemChunkRemote(), nil }}, newStubView(healthyProj(id)))
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { p.Close() })
// A blocked marker path prevents a giant allocation even without admission.
parent := filepath.Join(root, "v1.bin.chunkfresh")
if err := os.Mkdir(parent, 0700); err != nil {
t.Fatal(err)
}
_, err = p.Open(context.Background(), "v1")
if err == nil || !strings.Contains(err.Error(), "16 TiB - 4 KiB") {
t.Fatalf("want capacity before marker, got %v", err)
}
entries, err := os.ReadDir(root)
if err != nil {
t.Fatal(err)
}
if len(entries) != 1 || entries[0].Name() != "v1.bin.chunkfresh" {
t.Fatalf("refused create wrote files: %v", entries)
}
}
+4
View File
@@ -15,3 +15,7 @@ var ErrNotReady = errors.New("frontend: volume not ready")
// ErrBackendClosed is returned by Backend.Read / Backend.Write
// after Backend.Close has been invoked.
var ErrBackendClosed = errors.New("frontend: backend closed")
// ErrBackendBusy is a transient local admission timeout. Retry may succeed;
// it must not be used for a sticky persistence or integrity fault.
var ErrBackendBusy = errors.New("frontend: backend temporarily busy")
+10 -4
View File
@@ -72,12 +72,15 @@ type IOCommand struct {
// idiomatic error use AsError() — nil return means Status
// was Success.
type IOResult struct {
SCT uint8
SC uint8
Data []byte // read payload (nil for writes / errors)
Reason string
SCT uint8
SC uint8
Data []byte // read payload (nil for writes / errors)
Reason string
retryable bool // only transient backend pressure clears wire DNR
}
func (r IOResult) completionStatus() uint16 { return MakeStatusField(r.SCT, r.SC, !r.retryable) }
// AsError returns a non-nil *StatusError iff Status != Success.
func (r IOResult) AsError() *StatusError {
if r.SCT == SCTGeneric && r.SC == SCSuccess {
@@ -297,6 +300,9 @@ func (h *IOHandler) write(ctx context.Context, cmd IOCommand) IOResult {
// Error (fail-closed; real-backend-specific mapping lands with
// T3).
func mapBackendError(err error, op string) IOResult {
if errors.Is(err, frontend.ErrBackendBusy) {
return IOResult{SCT: SCTGeneric, SC: SCNamespaceNotReady, Reason: "local admission pressure on " + op + ": " + err.Error(), retryable: true}
}
if errors.Is(err, frontend.ErrStalePrimary) {
return IOResult{
SCT: SCTPathRelated,
@@ -0,0 +1,37 @@
package nvme
import (
"context"
"errors"
"github.com/seaweedfs/seaweed-block/core/frontend"
"github.com/seaweedfs/seaweed-block/core/frontend/testback"
"testing"
)
type pressureWriteBackend struct {
frontend.Backend
err error
}
func (b *pressureWriteBackend) Write(context.Context, int64, []byte) (int, error) { return 0, b.err }
func TestSessionPressureTimeoutIsRetryableNamespaceNotReady(t *testing.T) {
b := &pressureWriteBackend{Backend: testback.NewRecordingBackend(frontend.Identity{VolumeID: "v1"}), err: frontend.ErrBackendBusy}
s := &Session{handler: NewIOHandler(HandlerConfig{Backend: b}), respCh: make(chan *response, 1), done: make(chan struct{})}
for _, busy := range []bool{true, false} {
if !busy {
b.err = errors.New("sticky physical I/O fault")
}
req := &Request{payload: make([]byte, 512)}
req.capsule.OpCode = ioWrite
req.capsule.NSID = 1
s.handleWrite(context.Background(), req)
resp := <-s.respCh
want := MakeStatusField(SCTGeneric, SCInternalError, true)
if busy {
want = MakeStatusField(SCTGeneric, SCNamespaceNotReady, false)
}
if resp.resp.Status != want {
t.Fatalf("busy=%v wire status=%#x want%#x", busy, resp.resp.Status, want)
}
}
}
+3 -3
View File
@@ -475,7 +475,7 @@ func (s *Session) dispatchIO(ctx context.Context, req *Request) {
if s.logger != nil {
s.logger.Printf("nvme: Flush failed qid=%d nsid=%d sct=%#x sc=%#x reason=%s", s.qid, req.capsule.NSID, res.SCT, res.SC, res.Reason)
}
req.resp.Status = MakeStatusField(res.SCT, res.SC, true)
req.resp.Status = res.completionStatus()
}
s.enqueueResponse(&response{resp: req.resp})
default:
@@ -580,7 +580,7 @@ func (s *Session) handleRead(ctx context.Context, req *Request) {
NLB: req.capsule.LbaLength(),
})
if res.AsError() != nil {
req.resp.Status = MakeStatusField(res.SCT, res.SC, true)
req.resp.Status = res.completionStatus()
s.enqueueResponse(&response{resp: req.resp})
return
}
@@ -601,7 +601,7 @@ func (s *Session) handleWrite(ctx context.Context, req *Request) {
})
s.recordWriteHandler(time.Since(handlerStart))
if res.AsError() != nil {
req.resp.Status = MakeStatusField(res.SCT, res.SC, true)
req.resp.Status = res.completionStatus()
}
s.enqueueResponse(&response{resp: req.resp, writeCompletion: true, queuedAt: time.Now()})
}
@@ -0,0 +1,33 @@
// Package geometry defines shared volume capacity limits at creation boundaries.
package geometry
import "fmt"
// MaxVolumeBytes is the uint32-LBA limit with the supported 4-KiB IO unit.
// This byte cap assumes that IO unit: support for another block size must
// enforce min(MaxVolumeBytes, (2^32-1)*blockSize) at creation as well.
const MaxVolumeBytes uint64 = (16 << 40) - 4096
// ValidateVolumeSize rejects an unsupported capacity before any allocation or
// durable create. Division also makes block geometry checks overflow-safe.
func ValidateVolumeSize(size uint64) error {
if size > MaxVolumeBytes {
return fmt.Errorf("volume size %d exceeds maximum %d bytes (16 TiB - 4 KiB; uint32 LBA)", size, MaxVolumeBytes)
}
return nil
}
// ValidateBlockGeometry checks the original values before narrowing or I/O.
func ValidateBlockGeometry(blocks, blockSize uint64) error {
if blocks > uint64(^uint32(0)) {
return fmt.Errorf("block count %d exceeds uint32", blocks)
}
if blockSize == 0 || blockSize > uint64(^uint32(0)) {
return fmt.Errorf("invalid block size %d", blockSize)
}
// Division prevents an oversized product from wrapping before admission.
if blocks > MaxVolumeBytes/blockSize {
return fmt.Errorf("volume geometry %d x %d exceeds maximum %d bytes (16 TiB - 4 KiB; uint32 LBA)", blocks, blockSize, MaxVolumeBytes)
}
return nil
}
@@ -0,0 +1,217 @@
package master
import (
"bytes"
"context"
"strings"
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/authority"
"github.com/seaweedfs/seaweed-block/core/frontend"
"github.com/seaweedfs/seaweed-block/core/frontend/durable"
"github.com/seaweedfs/seaweed-block/core/lifecycle"
control "github.com/seaweedfs/seaweed-block/core/rpc/control"
"github.com/seaweedfs/seaweed-block/core/storage"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
"google.golang.org/protobuf/types/known/timestamppb"
)
// A holder that exited never detaches or ACKs, so its live authority blocks
// a volume delete. The existing path recovers the volume: after the lease
// horizon plus skew a forced move grants epoch+1 on another host, that
// host claims HEAD and serves the last cut, then detaches with a clean ACK,
// and the delete is admitted. Real master runtime, real providers, the
// in-memory ChunkRemote (read by the master through a HEAD reader).
func TestWorkspaceExitedHolderForcedMoveThenCleanDelete(t *testing.T) {
// The real lease horizon (1.5 x the 30 s TTL) plus skew takes ~45 s of
// this budget; the rest must cover the work after it under load and -race.
ctx, cancel := context.WithTimeout(context.Background(), 180*time.Second)
defer cancel()
remote := storage.NewMemChunkRemote()
reader := func(ctx context.Context, _ string) (authority.WorkspaceHead, error) {
h, err := remote.GetHead(ctx)
if err != nil {
return authority.WorkspaceHead{}, err
}
return authority.WorkspaceHead{Gen: h.Gen, Epoch: h.Epoch, Holder: h.Holder, RemoteLSN: h.RemoteLSN, Detached: h.State == storage.ChunkHeadDetached}, nil
}
const skew = 100 * time.Millisecond
m, err := New(Config{WorkspaceMaxClockSkew: skew, Listen: "127.0.0.1:0", AuthorityStoreDir: t.TempDir(), LifecycleStoreDir: t.TempDir(), WorkspaceRPC: true, WorkspaceHeadReader: reader})
if err != nil {
t.Fatal(err)
}
m.Start()
defer closeTestMaster(t, m)
conn, err := grpc.NewClient(m.Addr(), grpc.WithTransportCredentials(insecure.NewCredentials()))
if err != nil {
t.Fatal(err)
}
defer conn.Close()
ws, lc := control.NewWorkspaceServiceClient(conn), control.NewLifecycleServiceClient(conn)
// vol-a placed on node-a as r1; node-b is a prepared target.
for _, server := range []string{"node-a", "node-b"} {
if _, err = m.Lifecycle().Nodes.RegisterNode(lifecycle.NodeRegistration{ServerID: server, DataAddr: "127.0.0.1:9200", CtrlAddr: "127.0.0.1:9100"}); err != nil {
t.Fatal(err)
}
}
if _, err = lc.CreateVolume(ctx, &control.CreateVolumeRequest{VolumeId: "vol-a", SizeBytes: 1 << 20, ReplicationFactor: 1}); err != nil {
t.Fatal(err)
}
src := &control.WorkspaceBinding{VolumeId: "vol-a", ServerId: "node-a", DataAddr: "127.0.0.1:19200", CtrlAddr: "127.0.0.1:19100"}
dst := &control.WorkspaceBinding{VolumeId: "vol-a", ServerId: "node-b", DataAddr: "127.0.0.1:29200", CtrlAddr: "127.0.0.1:29100"}
for _, b := range []*control.WorkspaceBinding{src, dst} {
if _, err = ws.RegisterWorkspaceBinding(ctx, b); err != nil {
t.Fatal(err)
}
}
if _, err = ws.PlaceWorkspace(ctx, &control.WorkspacePlacement{VolumeId: "vol-a", ServerId: "node-a", ReplicaId: "r1"}); err != nil {
t.Fatal(err)
}
if _, err = control.NewObservationServiceClient(conn).ReportHeartbeat(ctx, &control.HeartbeatReport{ServerId: "node-a", SentAt: timestamppb.Now(), Reachable: true, Eligible: true,
Slots: []*control.HeartbeatSlot{{VolumeId: "vol-a", ReplicaId: "r1", DataAddr: src.DataAddr, CtrlAddr: src.CtrlAddr}}}); err != nil {
t.Fatal(err)
}
if _, err = m.RunLifecycleProductTick(); err != nil {
t.Fatal(err)
}
oldLine := waitAuthorityLine(t, m.Publisher(), "vol-a")
oldID := &control.WorkspaceIdentity{VolumeId: "vol-a", ReplicaId: oldLine.ReplicaID, Epoch: oldLine.Epoch}
if _, err = ws.RenewWorkspaceLease(ctx, oldID); err != nil {
t.Fatal(err)
}
open := func(host string, line authority.AuthorityBasis) (*durable.DurableProvider, frontend.Backend) {
t.Helper()
p, err := durable.NewDurableProvider(durable.ProviderConfig{
Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 4,
ChunkHolder: host + "/" + line.ReplicaID,
ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil },
}, restoreProjection{frontend.Projection{VolumeID: "vol-a", ReplicaID: line.ReplicaID, Epoch: line.Epoch, EndpointVersion: line.EndpointVersion, Healthy: true}})
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = p.Close() })
if _, err := p.EnsureStorage("vol-a"); err != nil {
t.Fatal(err)
}
if _, err := p.RecoverVolume(ctx, "vol-a"); err != nil {
t.Fatalf("%s recovery: %v", host, err)
}
b, err := p.Open(ctx, "vol-a")
if err != nil {
t.Fatal(err)
}
return p, b
}
// The holder writes, cuts, then exits without detaching or ACKing.
oldProvider, oldBackend := open("node-a", oldLine)
want := bytes.Repeat([]byte{0xE1}, 4096)
if n, err := oldBackend.Write(ctx, 8*4096, want); err != nil || n != len(want) {
t.Fatal(n, err)
}
if err := oldBackend.Sync(ctx); err != nil {
t.Fatal(err)
}
cut, err := oldProvider.CaptureVolume(ctx, "vol-a")
if err != nil {
t.Fatal(err)
}
if err := oldProvider.Close(); err != nil {
t.Fatal(err)
}
head, err := remote.GetHead(ctx)
if err != nil || head.RemoteLSN != cut || head.State == storage.ChunkHeadDetached {
t.Fatalf("HEAD after the holder exited: %+v %v", head, err)
}
// The exited holder's live authority blocks the delete and a clean move.
if _, err := lc.MarkVolumeDeleting(ctx, &control.MarkVolumeDeletingRequest{VolumeId: "vol-a", Token: "del-early"}); err == nil || !strings.Contains(err.Error(), "live authority requires clean revocation ACK") {
t.Fatalf("delete under the exited holder's live authority: %v; want the clean revocation ACK refusal", err)
}
move := &control.WorkspaceMove{RequestId: "clean-1", VolumeId: "vol-a", ExpectedReplicaId: "r1", ExpectedEpoch: oldLine.Epoch, TargetReplicaId: "r1",
TargetServerId: "node-b", TargetDataAddr: dst.DataAddr, TargetCtrlAddr: dst.CtrlAddr, Kind: "clean"}
if _, err := ws.MoveWorkspace(ctx, move); err == nil {
t.Fatal("clean move granted without the holder's detach and ACK")
}
move.RequestId, move.Kind, move.Force = "forced-1", "forced", true
if _, err := ws.MoveWorkspace(ctx, move); err == nil {
t.Fatal("forced move granted before the lease horizon plus skew")
}
// After the durable lease horizon plus skew, the forced move is granted.
horizon := int64(0)
if st := m.Publisher().WorkspaceState("vol-a"); st != nil && st.Lease != nil {
horizon = st.Lease.ExpiresAtNS
}
if horizon == 0 {
t.Fatal("no lease horizon recorded")
}
select {
case <-time.After(time.Until(time.Unix(0, horizon)) + skew + 20*time.Millisecond):
case <-ctx.Done():
t.Fatal(ctx.Err())
}
grant, err := ws.MoveWorkspace(ctx, move)
if err != nil {
t.Fatal("forced move after the horizon:", err)
}
newLine, ok := m.Publisher().VolumeAuthorityLine("vol-a")
if !grant.Issued || grant.NewEpoch != oldLine.Epoch+1 || !ok || newLine.Epoch != grant.NewEpoch || grant.HeadGen != head.Gen || grant.RemoteLsn != cut {
t.Fatalf("forced grant %+v line %+v; want epoch %d bound to HEAD gen %d lsn %d", grant, newLine, oldLine.Epoch+1, head.Gen, cut)
}
if _, err := ws.RenewWorkspaceLease(ctx, oldID); err == nil {
t.Fatal("the exited holder's authority renewed after the forced move")
}
// The new host claims HEAD, serves the last cut and continues past it.
newProvider, newBackend := open("node-b", newLine)
claimed, err := remote.GetHead(ctx)
if err != nil || claimed.Epoch != newLine.Epoch || claimed.Holder != "node-b/r1" || claimed.RemoteLSN != cut || claimed.State == storage.ChunkHeadDetached {
t.Fatalf("HEAD after the new host's recovery: %+v %v", claimed, err)
}
got := make([]byte, len(want))
if n, err := newBackend.Read(ctx, 8*4096, got); err != nil || n != len(got) || !bytes.Equal(got, want) {
t.Fatalf("new host read of the last cut: n=%d err=%v", n, err)
}
if n, err := newBackend.Write(ctx, 0, bytes.Repeat([]byte{0xE2}, 4096)); err != nil || n != 4096 {
t.Fatal(n, err)
}
if err := newBackend.Sync(ctx); err != nil {
t.Fatal(err)
}
if newCut, err := newProvider.CaptureVolume(ctx, "vol-a"); err != nil || newCut <= cut {
t.Fatalf("new host cut %d err %v; want past %d", newCut, err, cut)
}
// The new holder detaches cleanly and ACKs; the delete is then admitted.
newID := &control.WorkspaceIdentity{VolumeId: "vol-a", ReplicaId: newLine.ReplicaID, Epoch: newLine.Epoch}
if _, err := ws.RenewWorkspaceLease(ctx, newID); err != nil {
t.Fatal(err)
}
if _, err := ws.RevokeWorkspace(ctx, newID); err != nil {
t.Fatal(err)
}
detached, _, err := newProvider.DetachVolume(ctx, "vol-a")
if err != nil || detached.Head.State != storage.ChunkHeadDetached {
t.Fatalf("detach: %+v %v", detached.Head, err)
}
if _, err := ws.AckWorkspaceRevoked(ctx, &control.WorkspaceRevocationAck{Identity: newID, HeadGen: detached.Head.Gen}); err != nil {
t.Fatal(err)
}
res, err := lc.MarkVolumeDeleting(ctx, &control.MarkVolumeDeletingRequest{VolumeId: "vol-a", Token: "del-1"})
if err != nil || !res.GetKnown() || res.GetState() != lifecycle.ReservationAdmitted {
t.Fatalf("delete after the clean ACK: %+v %v", res, err)
}
if _, err := ws.RenewWorkspaceLease(ctx, newID); err == nil {
t.Fatal("authority renewed after the delete was admitted")
}
move.RequestId, move.ExpectedEpoch = "forced-2", newLine.Epoch
// The RPC refuses first; publication admission refuses it again behind it.
if _, err := ws.MoveWorkspace(ctx, move); err == nil || !strings.Contains(err.Error(), "workspace: volume is being deleted") {
t.Fatalf("move after the delete was admitted: %v; want the RPC's deletion refusal", err)
}
}
@@ -69,7 +69,9 @@ func TestWorkspaceHeldRenewalBoundary(t *testing.T) {
if err != nil {
t.Fatal(err)
}
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
// No wall-clock bound on the test context (#227): the held client
// is released by the test; only the guard's own RPC timeout remains.
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
if err := g.Refresh(ctx); err != nil {
t.Fatal(err)
@@ -14,17 +14,60 @@ import (
"google.golang.org/grpc"
)
// slowGuardStore delays every workspace-lease Put once armed (issue #205).
// slowGuardStore holds every workspace-lease Put, once armed, until a lease
// renewal that STARTED after the Put entered has succeeded (issue #205): a slow
// store write, with the slowness defined by progress instead of a fixed sleep.
// Each held Put takes a generation; a renewal is credited with the generation
// it observed before its call, so a reply computed before the hold never
// releases it.
type slowGuardStore struct {
authority.AuthorityStore
delayNS atomic.Int64
puts atomic.Int64 // delayed (armed) lease writes: proves the stall was exercised
armed atomic.Bool
gen atomic.Int64 // generation of the latest held Put
credited atomic.Int64 // highest generation a fresh renewal was started under
renewals atomic.Int64 // successful renewals seen by the client
kick chan struct{} // a renewal succeeded (buffered 1)
stop chan struct{} // closed by release(): frees any held Put
stopOnce sync.Once
held atomic.Int64 // lease writes that were held and then completed
}
func newSlowGuardStore(s authority.AuthorityStore) *slowGuardStore {
return &slowGuardStore{AuthorityStore: s, kick: make(chan struct{}, 1), stop: make(chan struct{})}
}
// release disarms and frees every held Put; idempotent.
func (s *slowGuardStore) release() {
s.armed.Store(false)
s.stopOnce.Do(func() { close(s.stop) })
}
// renewed credits a successful renewal that started under generation g.
func (s *slowGuardStore) renewed(g int64) {
s.renewals.Add(1)
for {
c := s.credited.Load()
if g <= c || s.credited.CompareAndSwap(c, g) {
break
}
}
select {
case s.kick <- struct{}{}:
default:
}
}
func (s *slowGuardStore) Put(r authority.DurableRecord) error {
if d := time.Duration(s.delayNS.Load()); d > 0 && r.Workspace != nil && r.Workspace.Lease != nil {
s.puts.Add(1)
time.Sleep(d)
if s.armed.Load() && r.Workspace != nil && r.Workspace.Lease != nil {
g := s.gen.Add(1)
for s.credited.Load() < g {
select {
case <-s.kick:
case <-s.stop:
return s.AuthorityStore.Put(r)
}
}
defer s.held.Add(1)
}
return s.AuthorityStore.Put(r)
}
@@ -35,6 +78,7 @@ func (s *slowGuardStore) Put(r authority.DurableRecord) error {
type deadlineLeaseClient struct {
p *authority.Publisher
inflight *sync.WaitGroup
slow *slowGuardStore // optional: told about each successful renewal
}
func (c deadlineLeaseClient) RenewWorkspaceLease(ctx context.Context, id *control.WorkspaceIdentity, _ ...grpc.CallOption) (*control.WorkspaceLeaseFact, error) {
@@ -42,6 +86,10 @@ func (c deadlineLeaseClient) RenewWorkspaceLease(ctx context.Context, id *contro
fact *control.WorkspaceLeaseFact
err error
}
var g int64
if c.slow != nil {
g = c.slow.gen.Load() // a reply can only release holds that entered before this call
}
done := make(chan result, 1)
c.inflight.Add(1)
go func() {
@@ -55,6 +103,9 @@ func (c deadlineLeaseClient) RenewWorkspaceLease(ctx context.Context, id *contro
}()
select {
case r := <-done:
if r.err == nil && c.slow != nil {
c.slow.renewed(g)
}
return r.fact, r.err
case <-ctx.Done():
return nil, ctx.Err()
@@ -74,10 +125,10 @@ func TestWorkspaceLeaseGuardSurvivesSlowAuthorityStore(t *testing.T) {
if err != nil {
t.Fatal(err)
}
slow := &slowGuardStore{AuthorityStore: disk}
slow := newSlowGuardStore(disk)
var inflight sync.WaitGroup
t.Cleanup(func() {
slow.delayNS.Store(0)
slow.release()
inflight.Wait()
if err := disk.Close(); err != nil {
t.Error(err)
@@ -86,10 +137,11 @@ func TestWorkspaceLeaseGuardSurvivesSlowAuthorityStore(t *testing.T) {
dir := &skewDirective{asks: make(chan authority.AssignmentAsk, 1)}
p := authority.NewPublisher(dir, authority.WithStore(slow), authority.WithWorkspaceLeaseConfig(6*time.Second, nil))
t.Cleanup(p.CloseWorkspaceExtenders) // join extenders before the store closes
t.Cleanup(slow.release) // runs before the join above: frees a held Put first
seedSkewPublisher(t, p, dir)
var stops atomic.Int32
g, err := volume.NewWorkspaceLeaseGuard(workspaceRPCView{frontend.Projection{VolumeID: "v", ReplicaID: "r", Epoch: 1, Healthy: true}},
deadlineLeaseClient{p: p, inflight: &inflight}, &control.WorkspaceIdentity{VolumeId: "v", ReplicaId: "r", Epoch: 1},
deadlineLeaseClient{p: p, inflight: &inflight, slow: slow}, &control.WorkspaceIdentity{VolumeId: "v", ReplicaId: "r", Epoch: 1},
func(context.Context) (uint64, error) { stops.Add(1); return 7, nil }, nil)
if err != nil {
t.Fatal(err)
@@ -99,29 +151,40 @@ func TestWorkspaceLeaseGuardSurvivesSlowAuthorityStore(t *testing.T) {
go func() { runDone <- g.Run(ctx) }()
t.Cleanup(func() {
cancel()
select {
case <-runDone:
case <-time.After(10 * time.Second):
t.Error("guard did not settle")
}
<-runDone // Run returns on cancel; the go test timeout bounds a hang
})
for wait := time.Now().Add(3 * time.Second); !g.Projection().Healthy; time.Sleep(20 * time.Millisecond) {
if time.Now().After(wait) {
t.Fatal("first grant did not arrive")
t.Cleanup(slow.release) // first of all cleanups: a held Put never blocks the joins
for !g.Projection().Healthy { // progress: the first grant
time.Sleep(20 * time.Millisecond)
}
// Every lease write is now held until a renewal succeeded during its hold,
// so a renewal that waited for the store would deadlock this test. The
// sampler records any fence while armed; three held writes must complete.
var fenced atomic.Bool
sampled := make(chan struct{})
slow.armed.Store(true)
go func() {
defer close(sampled)
for slow.armed.Load() {
if !g.Projection().Healthy || stops.Load() != 0 {
fenced.Store(true)
}
time.Sleep(20 * time.Millisecond)
}
}
slow.delayNS.Store(int64(2500 * time.Millisecond))
start := time.Now()
for time.Since(start) < 10*time.Second {
if !g.Projection().Healthy || stops.Load() != 0 {
t.Fatalf("guard fenced %s after the store slowed to 2.5 s per write (stop calls %d)", time.Since(start).Round(time.Millisecond), stops.Load())
}()
for slow.held.Load() < 3 {
if fenced.Load() {
break
}
time.Sleep(50 * time.Millisecond)
time.Sleep(20 * time.Millisecond)
}
if slow.puts.Load() == 0 {
t.Fatal("no lease write went through the 2.5 s stall: the test did not exercise it")
slow.armed.Store(false)
<-sampled
if fenced.Load() || !g.Projection().Healthy || stops.Load() != 0 {
t.Fatalf("guard fenced while lease writes were held behind renewals (held=%d renewals=%d stops=%d)", slow.held.Load(), slow.renewals.Load(), stops.Load())
}
t.Logf("guard stayed healthy for 10 s; %d lease writes took 2.5 s each", slow.puts.Load())
t.Logf("guard stayed healthy through %d held lease writes (%d renewals)", slow.held.Load(), slow.renewals.Load())
}
// A durable deletion-reservation write of an unrelated volume must not block
@@ -6,7 +6,6 @@ import (
"reflect"
"sync/atomic"
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/authority"
"github.com/seaweedfs/seaweed-block/core/frontend"
@@ -33,7 +32,9 @@ func (r *restoreRemote) Get(ctx context.Context, key string) ([]byte, error) {
// Keep the old projection stale to model delayed assignment delivery; a HEAD
// takeover must independently refuse its cut and then stop its frontend I/O.
func TestWorkspaceMoveRestoresLazilyAndFencesOldHost(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
// No wall-clock bound (#227): each step completes or the go test timeout
// reports the hang; a 10 s context failed the HEAD claim under load.
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
m := newTestMaster(t, t.TempDir())
defer closeTestMaster(t, m)
@@ -59,6 +59,7 @@ type ChunkCutStatsBody struct {
COWSaveNs int64 `json:"cowSaveNs"`
COWWaitNs int64 `json:"cowWaitNs"`
BarrierPauseNs int64 `json:"barrierPauseNs"`
LockWaitNs int64 `json:"lockWaitNs"`
SyncNs int64 `json:"syncNs"`
CopyNs int64 `json:"copyNs"`
CandidateChunks int `json:"candidateChunks"`
@@ -80,6 +81,7 @@ type ChunkCutStatsBody struct {
func cutStatsBody(s storage.ChunkCutStats) ChunkCutStatsBody {
return ChunkCutStatsBody{
BarrierPauseNs: s.BarrierPauseNs,
LockWaitNs: s.LockWaitNs,
SyncNs: s.SyncNs,
CopyNs: s.CopyNs,
COWSavedChunks: s.COWSavedChunks,
@@ -157,6 +159,7 @@ const (
codeFenced = "fenced"
codeHeadConflict = "head_conflict"
codeClosing = "closing"
codeDetachAborted = "detach_aborted" // the detach did not happen; the volume keeps serving here
codeLSNBehind = "lsn_behind"
codeInternal = "internal"
codeBadRequest = "bad_request"
@@ -227,6 +230,13 @@ func writeChunkFailure(w http.ResponseWriter, err error) {
func chunkErrorCode(err error) (int, string, bool) {
var ce *chunkstore.CatalogError
switch {
case errors.Is(err, durable.ErrDetachAborted):
// Before any cause (a catalog error included): nothing was
// published and serving resumed here.
return http.StatusConflict, codeDetachAborted, true
case errors.Is(err, durable.ErrDetachOutcomeUnknown):
// Before any cause: the detach may still have landed; I/O stays stopped.
return http.StatusServiceUnavailable, chunkstore.CodeOutcomeUnknown, true
case errors.As(err, &ce):
return catalogStatus(ce.Code), ce.Code, ce.Retryable
case errors.Is(err, storage.ErrChunkLayerFenced):
@@ -222,6 +222,11 @@ func TestStatusServer_ChunkErrorBodyIsTyped(t *testing.T) {
{fmt.Errorf("x: %w", storage.ErrChunkRemoteUnavailable), "remote_unavailable", 503, true},
{fmt.Errorf("x: %w", storage.ErrChunkLayerClosed), "closing", 503, false},
{fmt.Errorf("x: %w", storage.ErrChunkLayerDetached), "closing", 409, false},
{fmt.Errorf("%w: %w", durable.ErrDetachAborted, storage.ErrChunkRemoteUnavailable), "detach_aborted", 409, true},
// The detach sentinels decide even over a catalog-error cause (which
// alone maps to its own code), and without the storage CAS sentinel.
{fmt.Errorf("%w: %w", durable.ErrDetachAborted, &chunkstore.CatalogError{Code: chunkstore.CodeSnapshotExists, Message: "m"}), "detach_aborted", 409, true},
{fmt.Errorf("%w: %w", durable.ErrDetachOutcomeUnknown, &chunkstore.CatalogError{Code: chunkstore.CodeSnapshotExists, Message: "m"}), "outcome_unknown", 503, true},
{fmt.Errorf("%w: %w: cut LSN 1, HEAD remote_lsn 10", storage.ErrChunkCaptureRefused, storage.ErrChunkLSNBehind), "lsn_behind", 409, false},
{&chunkstore.CatalogError{Code: chunkstore.CodeInvalidLabel, Message: "m"}, "invalid_label", 400, false},
{fmt.Errorf("x: %w", durable.ErrNotChunkVolume), "not_chunk_volume", 409, false},
@@ -0,0 +1,35 @@
package lifecycle
import (
"encoding/json"
"os"
"path/filepath"
"testing"
)
func TestLegacyOversizeIdenticalCreateRetry(t *testing.T) {
dir := t.TempDir()
spec := VolumeSpec{VolumeID: "legacy", SizeBytes: 17592186044416, ReplicationFactor: 1}
data, err := json.Marshal(VolumeRecord{Spec: spec})
if err != nil {
t.Fatal(err)
}
if err = os.WriteFile(filepath.Join(dir, "legacy.json"), data, 0600); err != nil {
t.Fatal(err)
}
s, err := OpenFileStore(dir)
if err != nil {
t.Fatal(err)
}
got, err := s.CreateVolume(spec)
if err != nil {
t.Fatalf("existing identical intent must remain retryable: %v", err)
}
if got.Spec.SizeBytes != spec.SizeBytes {
t.Fatal("existing size changed")
}
spec.VolumeID = "new-oversize"
if _, err = s.CreateVolume(spec); err == nil {
t.Fatal("new oversize admitted")
}
}
+5
View File
@@ -16,6 +16,8 @@ import (
"sort"
"sync"
"sync/atomic"
"github.com/seaweedfs/seaweed-block/core/geometry"
)
var (
@@ -124,6 +126,9 @@ func (s *FileStore) CreateVolume(spec VolumeSpec) (VolumeRecord, error) {
}
return existing, nil
}
if err := geometry.ValidateVolumeSize(spec.SizeBytes); err != nil {
return VolumeRecord{}, fmt.Errorf("%w: %w", ErrInvalidVolumeSpec, err)
}
rec := VolumeRecord{Spec: spec}
if err := s.putLocked(rec); err != nil {
return VolumeRecord{}, err
@@ -0,0 +1,27 @@
package lifecycle
import (
"errors"
"strings"
"testing"
)
func TestCreateVolumeRejectsBeyondUint32LBACap(t *testing.T) {
s, err := OpenFileStore(t.TempDir())
if err != nil {
t.Fatal(err)
}
const capBytes = uint64(17592186040320) // 16 TiB - 4 KiB
if _, err = s.CreateVolume(VolumeSpec{VolumeID: "at-cap", SizeBytes: capBytes, ReplicationFactor: 1}); err != nil {
t.Fatal(err)
}
for _, size := range []uint64{capBytes + 1, capBytes + 4096, ^uint64(0)} {
_, err = s.CreateVolume(VolumeSpec{VolumeID: "too-large", SizeBytes: size, ReplicationFactor: 1})
if !errors.Is(err, ErrInvalidVolumeSpec) || !strings.Contains(err.Error(), "16 TiB - 4 KiB") {
t.Fatalf("size %d: want clear capacity refusal, got %v", size, err)
}
if _, ok := s.GetVolumeSnapshot("too-large"); ok {
t.Fatal("refusal persisted oversized volume")
}
}
}
+13 -1
View File
@@ -18,6 +18,9 @@ import (
)
const cutCOWMemoryLimit = 64 << 20
// defaultCOWSpillLimit caps a copy window's side-file bytes by default.
const defaultCOWSpillLimit = 1 << 30
const (
cowPending uint8 = iota
cowCopying
@@ -53,6 +56,8 @@ type cutCOWWindow struct {
entries map[uint64]*cutCOWEntry
head map[uint64]chunkRef // the cut's base HEAD: the source of missing blocks
memory int64
spillBytes int64 // bytes written to the side file; at most spillLimit
spillLimit int64
chunkBytes int64
side *os.File
sideErr error
@@ -129,7 +134,7 @@ func (l *chunkLayerImpl) installCOWWindow(candidates, staged map[uint64]bool, he
if size == 0 || size > math.MaxInt64 || uint64(len(candidates)) > math.MaxInt64/size {
return nil, fmt.Errorf("%w: side-store geometry", errCutCOWAborted)
}
w := &cutCOWWindow{layer: l, ended: make(chan struct{}), entries: make(map[uint64]*cutCOWEntry), head: head, chunkBytes: int64(size)}
w := &cutCOWWindow{layer: l, ended: make(chan struct{}), entries: make(map[uint64]*cutCOWEntry), head: head, spillLimit: l.cfg.COWSpillLimit, chunkBytes: int64(size)}
var slot int64
for _, idx := range sortedKeys(candidates) {
state := cowPending
@@ -293,6 +298,13 @@ func (w *cutCOWWindow) save(e *cutCOWEntry, data []byte, missing []uint64) error
inMemory := w.memory+w.chunkBytes <= cutCOWMemoryLimit
if inMemory {
w.memory += w.chunkBytes
} else if w.spillBytes+w.chunkBytes > w.spillLimit {
// The side file is sparse but its saved chunks are real bytes on the
// volume's filesystem: abort the cut (retried) instead of filling it.
w.mu.Unlock()
return fmt.Errorf("%w: COW spill would exceed its cap of %d bytes", errCutCOWAborted, w.spillLimit)
} else {
w.spillBytes += w.chunkBytes
}
w.mu.Unlock()
// e.missing (and e.data / the spilled bytes) are published to readers by
@@ -0,0 +1,87 @@
package storage
import (
"context"
"errors"
"strings"
"testing"
"time"
)
// P3: once the in-memory budget is used, a save that would take the side file
// past its byte cap aborts the cut (retried) instead of growing the file; the
// guest write still completes and no side file is left.
func TestCutCOWV3_SpillCapAbortsTheCut(t *testing.T) {
s, l, _, gate := cowFixture(t)
cutDone, cutErr := cowStartCut(t, l, gate)
w := l.cowActive.Load()
w.mu.Lock()
w.memory = cutCOWMemoryLimit // the in-memory budget is used
w.spillLimit = w.chunkBytes - 1 // the cap leaves no room for one chunk
w.mu.Unlock()
writeDone := make(chan error, 1)
go func() { _, err := s.Write(5, makeBlock(ctBlockSize, 0xd5)); writeDone <- err }()
select {
case err := <-writeDone:
if err != nil {
t.Fatal("guest write refused by the spill cap:", err)
}
case <-time.After(ctLocalBound):
t.Fatal("guest write did not complete when the spill cap aborted the cut")
}
w.mu.Lock()
side, spilled := w.side, w.spillBytes
w.mu.Unlock()
if side != nil || spilled != 0 {
t.Fatalf("side file %v / %d spilled bytes past the cap", side != nil, spilled)
}
gate.unblock()
cowWaitSignal(t, cutDone, "capped cut")
if err := <-cutErr; !errors.Is(err, errCutCOWAborted) || !strings.Contains(err.Error(), "spill would exceed its cap") {
t.Fatalf("cut past the spill cap: %v, want the cap abort", err)
}
if _, err := l.Cut(context.Background()); err != nil {
t.Fatal("retried cut:", err)
}
}
// The default cap applies at attach (0), and a negative cap is refused.
func TestChunkLayer_COWSpillLimitDefaultAndRefusal(t *testing.T) {
s, _ := newChunkTestStore(t)
cfg := ctConfig(1)
cfg.COWSpillLimit = -1
if _, err := attachChunkLayer(s, newFakeChunkRemote(), cfg); err == nil || !strings.Contains(err.Error(), "spill limit") {
t.Fatalf("negative COW spill limit: %v, want a refusal", err)
}
cfg.COWSpillLimit = 0
l := mustAttach(t, s, newFakeChunkRemote(), cfg).(*chunkLayerImpl)
if l.cfg.COWSpillLimit != defaultCOWSpillLimit {
t.Fatalf("COW spill limit %d, want the default %d", l.cfg.COWSpillLimit, defaultCOWSpillLimit)
}
}
// A spill within the cap is accounted: with room for exactly one chunk the
// save spills, the window counts that chunk, and the cut completes.
func TestCutCOWV3_SpillWithinCapIsAccounted(t *testing.T) {
s, l, _, gate := cowFixture(t)
cutDone, cutErr := cowStartCut(t, l, gate)
w := l.cowActive.Load()
w.mu.Lock()
w.memory = cutCOWMemoryLimit
w.spillLimit = w.chunkBytes
w.mu.Unlock()
if _, err := s.Write(5, makeBlock(ctBlockSize, 0xd5)); err != nil {
t.Fatal(err)
}
w.mu.Lock()
side, spilled := w.side, w.spillBytes
w.mu.Unlock()
if side == nil || spilled != w.chunkBytes {
t.Fatalf("spill within the cap: side file %v, %d bytes accounted, want one chunk (%d)", side != nil, spilled, w.chunkBytes)
}
gate.unblock()
cowWaitSignal(t, cutDone, "cut within the spill cap")
if err := <-cutErr; err != nil {
t.Fatal(err)
}
}
@@ -0,0 +1,79 @@
package storage
import (
"sync"
"testing"
"time"
)
// cutWithBarrierHeld runs one cut while a writer holds the capture barrier
// shared (as a writer parked in WAL admission does). The hold ends hold after
// the cut's barrier Lock REQUEST (a handshake, not a guess at the cut's
// progress), so the cut waited at least hold at its Lock. The shared hold is
// released on every path, and the cut is joined within a bound.
func cutWithBarrierHeld(t *testing.T, hold time.Duration) chunkCutStats {
t.Helper()
s, _ := newChunkTestStore(t)
f := newFakeChunkRemote()
layer := mustAttach(t, s, f, ctConfig(1))
l := layer.(*chunkLayerImpl)
w := newWriteLog()
w.write(t, s, 2, 0x22)
requested := make(chan struct{})
var reqOnce sync.Once
l.testBeforeBarrierLockHook = func() { reqOnce.Do(func() { close(requested) }) }
s.captureMu.RLock()
var unlockOnce sync.Once
release := func() { unlockOnce.Do(s.captureMu.RUnlock) }
type result struct {
r chunkCutResult
err error
}
done := make(chan result, 1)
t.Cleanup(func() {
release()
select {
case <-done:
case <-time.After(ctLocalBound):
t.Errorf("cut not joined within %v", ctLocalBound)
}
})
go func() {
r, err := layer.Cut(ctTimeout(t))
done <- result{r, err}
}()
cowWaitSignal(t, requested, "the cut's barrier Lock request")
time.Sleep(hold) // the cut is waiting at captureMu.Lock for the shared holder
release()
var got result
select {
case got = <-done:
case <-time.After(ctLocalBound):
t.Fatalf("cut did not finish within %v after the shared holder released the barrier", ctLocalBound)
}
done <- got // for the cleanup's join
if got.err != nil {
t.Fatal(got.err)
}
return got.r.Stats
}
// P2: the guest pause starts at the barrier's Lock request (a pending writer
// blocks new readers), so the wait for writers already holding the barrier is
// part of BarrierPauseNs.
func TestCutStats_BarrierPauseIncludesTheLockWait(t *testing.T) {
const hold = 300 * time.Millisecond
st := cutWithBarrierHeld(t, hold)
if st.BarrierPauseNs < hold.Nanoseconds() {
t.Fatalf("BarrierPauseNs %v does not include the >= %v wait for a writer holding the barrier", time.Duration(st.BarrierPauseNs), hold)
}
}
// P2: LockWaitNs reports that wait on its own, as the first part of the pause.
func TestCutStats_LockWaitNsReportsTheWait(t *testing.T) {
const hold = 300 * time.Millisecond
st := cutWithBarrierHeld(t, hold)
if st.LockWaitNs < hold.Nanoseconds() || st.BarrierPauseNs < st.LockWaitNs+st.SyncNs {
t.Fatalf("LockWaitNs %v (pause %v, sync %v): want >= %v and inside the pause before the sync", time.Duration(st.LockWaitNs), time.Duration(st.BarrierPauseNs), time.Duration(st.SyncNs), hold)
}
}
+88 -4
View File
@@ -132,6 +132,7 @@ type chunkLayerImpl struct {
testAfterStageHook func(round int) // after each pre-copy staging round
testAfterStageReadHook func(idx uint64) // after a staging read, before its result is kept
testAfterBarrierSyncHook func(h uint64) // under the capture barrier, right after Sync fixed H
testBeforeBarrierLockHook func() // right before the capture barrier's Lock request
syncDirFn func(dir string) error // directory fsync after a rename; syncDir in production
// Absence: chunks whose local bytes are not authoritative (fresh host,
@@ -180,6 +181,12 @@ func attachChunkLayerImpl(s *WALStore, remote chunkRemote, cfg chunkLayerConfig)
if cfg.ReadMissTimeout <= 0 {
cfg.ReadMissTimeout = defaultReadMissTimeout
}
if cfg.COWSpillLimit < 0 {
return nil, errors.New("storage: COW spill limit must not be negative (0 defaults to 1 GiB)")
}
if cfg.COWSpillLimit == 0 {
cfg.COWSpillLimit = defaultCOWSpillLimit
}
nb := uint64(s.NumBlocks())
l := &chunkLayerImpl{
s: s,
@@ -835,9 +842,17 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch
return chunkCutResult{}, err
}
// Quiesced cut.
// Quiesced cut. The guest pause starts at the Lock REQUEST: a pending
// writer blocks new readers of captureMu, so a write arriving while the cut
// waits for writers already holding it (e.g. parked in WAL admission) is
// paused too. LockWaitNs reports that wait on its own.
pauseStart := time.Now()
if hook := l.testBeforeBarrierLockHook; hook != nil {
hook()
}
l.s.captureMu.Lock()
barrier := time.Now()
st.LockWaitNs = barrier.Sub(pauseStart).Nanoseconds()
h, err := l.s.Sync()
st.SyncNs = time.Since(barrier).Nanoseconds()
if hook := l.testAfterBarrierSyncHook; hook != nil && err == nil {
@@ -845,7 +860,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch
}
if err != nil {
l.s.captureMu.Unlock()
st.BarrierPauseNs = time.Since(barrier).Nanoseconds()
st.BarrierPauseNs = time.Since(pauseStart).Nanoseconds()
l.dropIntents(ctx, intents) // a clean abort: staged keys are released
return chunkCutResult{}, fmt.Errorf("storage: capture sync: %w", err)
}
@@ -900,7 +915,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch
var w *cutCOWWindow
w, copyErr = l.installCOWWindow(candidates, useStaged, baseHead.Chunks)
l.s.captureMu.Unlock()
st.BarrierPauseNs = time.Since(barrier).Nanoseconds()
st.BarrierPauseNs = time.Since(pauseStart).Nanoseconds()
copyStart = time.Now()
if copyErr == nil {
var copied []capturedChunk
@@ -923,7 +938,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch
captured = append(captured, capturedChunk{idx: idx, data: buf, sum: sha256.Sum256(buf), zero: isAllZero(buf)})
}
l.s.captureMu.Unlock()
st.BarrierPauseNs = time.Since(barrier).Nanoseconds()
st.BarrierPauseNs = time.Since(pauseStart).Nanoseconds()
}
st.CopyNs = time.Since(copyStart).Nanoseconds()
if copyErr != nil {
@@ -1148,6 +1163,75 @@ func (l *chunkLayerImpl) Detach(ctx context.Context) (chunkCutResult, error) {
return r, err
}
// SettleDetach: see chunkLayer. Only an unresolved DETACH proposal needs a
// remote decision: if HEAD is still that CAS's base, it is cancelled by a CAS
// at the same base to the non-detached base image (this holder, this epoch),
// so whichever lands first decides and the detach can never land after a
// successful cancel. resolvePending would re-propose the detach instead.
func (l *chunkLayerImpl) SettleDetach(ctx context.Context) (detachSettlement, chunkCutResult, error) {
l.capMu.Lock()
defer l.capMu.Unlock()
if r, ok := l.storedDetach(); ok {
return detachApplied, r, nil
}
l.stMu.Lock()
fenced, pending, isDetach, base, intents := l.fenced, l.pending, l.pendingDetach, l.pendingBase, l.pendingIntents
baseHead := copyHead(l.head)
l.stMu.Unlock()
if fenced {
return detachFenced, chunkCutResult{}, nil
}
if pending == nil || !isDetach {
// Nothing of this detach can land: it failed before its CAS or was
// definitely refused (an unresolved ordinary cut settles as usual).
return detachNotPublished, chunkCutResult{}, nil
}
cur, err := l.remote.GetHead(ctx)
if err != nil {
return 0, chunkCutResult{}, fmt.Errorf("storage: detach outcome unresolved: %w: %w", errChunkCASOutcomeUnknown, err)
}
if !sameProposal(cur, *pending) && !l.supersededBy(cur) && cur.Gen == base.Gen && cur.Epoch == base.Epoch {
if err := l.admit(); err != nil {
return 0, chunkCutResult{}, fmt.Errorf("storage: detach outcome unresolved (%w); cancel refused: %w", errChunkCASOutcomeUnknown, err)
}
cancel := copyHead(baseHead)
cancel.Epoch, cancel.Holder = l.cfg.Epoch, l.cfg.Holder
cancel.State, cancel.DetachedBy = chunkHeadActive, nil
gen, casErr := l.remote.CASHead(ctx, base, cancel)
if casErr == nil {
cancel.Gen = gen
cur = cancel
} else if cur, err = l.remote.GetHead(ctx); err != nil {
return 0, chunkCutResult{}, fmt.Errorf("storage: detach outcome unresolved (cancel: %v): %w: %w", casErr, errChunkCASOutcomeUnknown, err)
} else if !sameProposal(cur, *pending) && !l.supersededBy(cur) && cur.Gen == base.Gen && cur.Epoch == base.Epoch {
return 0, chunkCutResult{}, fmt.Errorf("storage: detach outcome unresolved (cancel: %v): HEAD unchanged: %w", casErr, errChunkCASOutcomeUnknown)
}
}
// Settled: the detach landed, or it can never land.
l.dropIntents(ctx, intents)
l.stMu.Lock()
defer l.stMu.Unlock()
cut := l.pendingCut
l.pending, l.pendingIntents = nil, nil
l.pendingDetach, l.pendingCut, l.pendingBase = false, chunkCutResult{}, chunkHeadVersion{}
switch {
case sameProposal(cur, *pending):
l.head, l.remoteLSN = copyHead(cur), cur.RemoteLSN
cut.Head = copyHead(cur)
l.detached = &cut
r := cut
r.Head = copyHead(cur)
return detachApplied, r, nil
case l.supersededBy(cur):
l.fenced = true
l.head = copyHead(cur)
return detachFenced, chunkCutResult{}, nil
default:
l.head = copyHead(cur)
return detachNotPublished, chunkCutResult{}, nil
}
}
func (l *chunkLayerImpl) storedDetach() (chunkCutResult, bool) {
l.stMu.Lock()
defer l.stMu.Unlock()
@@ -20,6 +20,14 @@ type (
ChunkLayerStats = chunkLayerStats
ChunkIntent = chunkIntent
ChunkDetachedBy = chunkDetachedBy
DetachSettlement = detachSettlement
)
// How a failed Detach ended (ChunkLayer.SettleDetach).
const (
DetachNotPublished = detachNotPublished
DetachApplied = detachApplied
DetachFenced = detachFenced
)
// HEAD states.
+30 -3
View File
@@ -355,6 +355,12 @@ type chunkLayerConfig struct {
// UploadConcurrency bounds capture/pre-copy Put calls (0 defaults to 8).
UploadConcurrency int
// COWSpillLimit caps the bytes a cut's copy window may spill to its side
// file once the in-memory budget is used: a save beyond it aborts the cut
// (the caller retries) instead of growing the file under the WAL/extent.
// 0 defaults to defaultCOWSpillLimit; negative is refused.
COWSpillLimit int64
// testReconcileHold, set only by this package's tests, holds the
// reconciler before each slice until a token is received or the
// channel is closed.
@@ -369,10 +375,14 @@ type chunkLayerConfig struct {
// chunkCutStats describes one cut. The periodic-cut work fills it; a zero
// value means "not measured".
type chunkCutStats struct {
COWSavedChunks int
COWSaveNs int64
COWWaitNs int64
COWSavedChunks int
COWSaveNs int64
COWWaitNs int64
// BarrierPauseNs is the guest pause: from the capture barrier's Lock
// request until it is released. LockWaitNs is its first part, the wait for
// writers already holding the capture barrier shared.
BarrierPauseNs int64
LockWaitNs int64
SyncNs int64
CopyNs int64
CandidateChunks int
@@ -453,6 +463,15 @@ type chunkCutResult struct {
}
// chunkLayer is what the store owner drives.
// detachSettlement is how a failed Detach ended (SettleDetach).
type detachSettlement int
const (
detachNotPublished detachSettlement = iota
detachApplied
detachFenced
)
type chunkLayer interface {
chunkSink
// Cut takes a quiesced cut at H (the last written LSN), uploads the
@@ -471,6 +490,14 @@ type chunkLayer interface {
// Detach returns the first result. An unresolved detach CAS is settled
// like any other unresolved CAS, before the next capture or Detach.
Detach(ctx context.Context) (chunkCutResult, error)
// SettleDetach decides how a failed Detach ended, with the caller's I/O
// still stopped: detachNotPublished (HEAD does not and can never carry
// this layer's detach: serving may resume; the dirty set stays dirty),
// detachApplied (HEAD carries it: the detached result is returned) or
// detachFenced (HEAD belongs to a newer epoch or another holder). An
// error wrapping errChunkCASOutcomeUnknown leaves it undecided: stay
// stopped. It never resumes on top of a possibly detached HEAD.
SettleDetach(ctx context.Context) (detachSettlement, chunkCutResult, error)
// MakeRemoteDurable is the durability point for snapshot, detach and
// migrate: a Capture whose H >= t. Only a nil return makes t remote
// durable; it requires the local Sync to cover t first, and fails
+28 -1
View File
@@ -4,6 +4,7 @@ import (
"encoding/binary"
"fmt"
"log"
"sort"
"sync"
"sync/atomic"
"time"
@@ -162,6 +163,13 @@ func (f *flusher) flushOnceInternal(allowClosed bool) (err error) {
if err := store.stickyIOFault(); err != nil {
return err // no checkpoint advance after a failed fsync
}
// Do not acquire lifecycleMu here: Close holds it while joining Stop.
// The pressure leader is released before snapshot/materialization/checkpoint.
if store.v3 != nil {
if err := store.syncWALPressureV3(); err != nil {
return fmt.Errorf("flusher: pressure WAL sync: %w", err)
}
}
store.mu.RLock()
if store.closed && !allowClosed {
store.mu.RUnlock()
@@ -204,8 +212,27 @@ func (f *flusher) flushOnceInternal(allowClosed bool) (err error) {
f.instr.recordWrittenOpportunity(writtenEntries, store.sb.BlockSize)
}()
// Adjacent blocks of a native batch share one immutable, validated record.
// Keep only one record (at most WALSize bytes), scoped to this Recover lifetime.
var recordCache *flushRecordCacheV3
if store.v3 != nil {
sort.Slice(entries, func(i, j int) bool {
if entries[i].WALOffset == entries[j].WALOffset {
return entries[i].DataOffset < entries[j].DataOffset
}
return entries[i].WALOffset < entries[j].WALOffset
})
recordCache = &flushRecordCacheV3{recoveryGen: recoveryGen}
}
for _, e := range entries {
data, entrySize, err := f.readDirtyRecord(e)
var data []byte
var entrySize uint64
var err error
if recordCache != nil {
data, entrySize, err = f.readDirtyRecordV3Cached(e, recordCache)
} else {
data, entrySize, err = f.readDirtyRecord(e)
}
if err != nil {
return err
}
@@ -61,10 +61,14 @@ func TestFlusherInstrumentationCountsCompleteCycle(t *testing.T) {
t.Fatalf("snapshot/validated/superseded=%d/%d/%d want 4/4/0",
got.SnapshotEntries, got.ValidatedRecords, got.SupersededEntries)
}
if got.WALHeaderReadOps != 4 || got.WALRecordReadOps != 4 ||
got.WALRecordDecodeOps != 4 || got.WALRecordDecodeBytes == 0 ||
wantRecords := uint64(4)
if s.FormatV3() {
wantRecords = 1
} // one full native batch decode, four validated blocks
if got.WALHeaderReadOps != wantRecords || got.WALRecordReadOps != wantRecords ||
got.WALRecordDecodeOps != wantRecords || got.WALRecordDecodeBytes == 0 ||
got.WALRecordDecodeDurationNanos == 0 {
t.Fatalf("header/record reads and decode ops/bytes/ns=%d/%d %d/%d/%d want 4/4 4/nonzero/nonzero",
t.Fatalf("header/record reads and decode ops/bytes/ns=%d/%d %d/%d/%d want actual unique-record counts/nonzero bytes and duration",
got.WALHeaderReadOps, got.WALRecordReadOps,
got.WALRecordDecodeOps, got.WALRecordDecodeBytes,
got.WALRecordDecodeDurationNanos)
@@ -30,7 +30,7 @@ func TestFlusherV3ProfileCountsRealRecordStages(t *testing.T) {
if err != nil {
t.Fatal(err)
}
if got.ValidatedRecords != 2 || got.WALHeaderReadOps != 2 || got.WALRecordReadOps != 2 || got.WALRecordDecodeOps != 2 || got.ValidationFailures != 0 || got.CyclesSucceeded != 1 {
if got.ValidatedRecords != 2 || got.WALHeaderReadOps != 1 || got.WALRecordReadOps != 1 || got.WALRecordDecodeOps != 1 || got.ValidationFailures != 0 || got.CyclesSucceeded != 1 {
t.Fatalf("successful batch stages: %+v", got)
}
} else {
@@ -14,6 +14,7 @@ import (
"sync"
"time"
"github.com/seaweedfs/seaweed-block/core/geometry"
"github.com/seaweedfs/seaweed-block/core/storage"
)
@@ -134,6 +135,9 @@ func CreateStore(path string, numBlocks uint32, blockSize int) (*Store, error) {
func CreateStoreWithConfig(path string, cfg Config) (*Store, error) {
cfg = normalizeConfig(cfg)
if err := geometry.ValidateBlockGeometry(uint64(cfg.NumBlocks), uint64(cfg.BlockSize)); err != nil {
return nil, err
}
h, err := headerForConfig(cfg)
if err != nil {
return nil, err
@@ -0,0 +1,23 @@
package parallelwal
import (
"os"
"path/filepath"
"strings"
"testing"
)
func TestCreateCapacityBeforeFilesystem(t *testing.T) {
parent := filepath.Join(t.TempDir(), "file")
if err := os.WriteFile(parent, []byte("unchanged"), 0600); err != nil {
t.Fatal(err)
}
s, err := CreateStore(filepath.Join(parent, "volume"), ^uint32(0), 8192)
if s != nil {
s.Close()
t.Fatal("created oversized image")
}
if err == nil || !strings.Contains(err.Error(), "16 TiB - 4 KiB") {
t.Fatalf("capacity must precede filesystem: %v", err)
}
}
@@ -11,6 +11,7 @@ import (
"sync/atomic"
"time"
"github.com/seaweedfs/seaweed-block/core/geometry"
"github.com/seaweedfs/seaweed-block/core/storage"
)
@@ -90,6 +91,9 @@ func CreateStoreWithSlots(path string, numBlocks uint32, blockSize int, walSlots
if blockSize == 0 {
blockSize = storage.DefaultBlockSize
}
if err := geometry.ValidateBlockGeometry(uint64(numBlocks), uint64(blockSize)); err != nil {
return nil, err
}
if walSlots == 0 {
walSlots = defaultWALSlots
}
@@ -0,0 +1,23 @@
package smartwal
import (
"os"
"path/filepath"
"strings"
"testing"
)
func TestCreateCapacityBeforeFilesystem(t *testing.T) {
parent := filepath.Join(t.TempDir(), "file")
if err := os.WriteFile(parent, []byte("unchanged"), 0600); err != nil {
t.Fatal(err)
}
s, err := CreateStore(filepath.Join(parent, "volume"), ^uint32(0), 8192)
if s != nil {
s.Close()
t.Fatal("created oversized image")
}
if err == nil || !strings.Contains(err.Error(), "16 TiB - 4 KiB") {
t.Fatalf("capacity must precede filesystem: %v", err)
}
}
@@ -0,0 +1,29 @@
package storage
import (
"os"
"path/filepath"
"strings"
"testing"
)
func TestCreateWALStoreRefusesOversizeBeforeFilesystem(t *testing.T) {
// An invalid parent prevents even the old implementation from creating a
// huge sparse image; the capacity error must precede all filesystem work.
parent := filepath.Join(t.TempDir(), "file")
if err := os.WriteFile(parent, []byte("untouched"), 0600); err != nil {
t.Fatal(err)
}
s, err := CreateWALStore(filepath.Join(parent, "volume"), ^uint32(0), 8192)
if s != nil {
s.Close()
t.Fatal("oversized store created")
}
if err == nil || !strings.Contains(err.Error(), "16 TiB - 4 KiB") {
t.Fatalf("want capacity refusal before I/O, got %v", err)
}
got, e := os.ReadFile(parent)
if e != nil || string(got) != "untouched" {
t.Fatal("parent changed")
}
}
+7 -2
View File
@@ -2,12 +2,17 @@ package storage
import (
"errors"
"fmt"
"sync/atomic"
"time"
)
// errVolumeClosed is returned by walAdmission.Acquire if the store
// closes while the caller is waiting.
// ErrWALPressureTimeout is retryable local admission pressure, not a substrate
// fault. Unwrap preserves existing WAL-full classification for callers.
var ErrWALPressureTimeout = fmt.Errorf("storage: admission wait timed out: %w", errWALFull)
var errVolumeClosed = errors.New("storage: volume closed during admission wait")
// walAdmission controls write admission based on WAL pressure
@@ -117,7 +122,7 @@ func (a *walAdmission) Acquire(timeout time.Duration) error {
if err := a.terminalFault(); err != nil {
return err
}
return errWALFull
return ErrWALPressureTimeout
default:
}
a.sleepFn(2 * time.Millisecond)
@@ -156,7 +161,7 @@ func (a *walAdmission) Acquire(timeout time.Duration) error {
if err := a.terminalFault(); err != nil {
return err
}
return errWALFull
return ErrWALPressureTimeout
case <-closeTick.C:
if err := a.terminalFault(); err != nil {
return err
+9
View File
@@ -9,6 +9,7 @@ import (
"sync/atomic"
"time"
"github.com/seaweedfs/seaweed-block/core/geometry"
"github.com/seaweedfs/seaweed-block/core/iolatency"
)
@@ -191,6 +192,9 @@ func CreateWALStoreWithOptions(path string, numBlocks uint32, blockSize int, opt
if blockSize < 0 || uint64(blockSize) > uint64(^uint32(0)) {
return nil, errSuperblockBadVolume
}
if err := geometry.ValidateVolumeSize(uint64(numBlocks) * uint64(blockSize)); err != nil {
return nil, err
}
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
return nil, err
}
@@ -386,6 +390,11 @@ func openInitializedInternal(path string, f *os.File, sb *superblock, metadata B
// flusher via NotifyUrgent — same seam V2 wires for pressure-
// driven flushes.
s.admissionTimeout = 30 * time.Second
if s.v3 != nil {
// WAL pressure gets a budget below the host's I/O timeout. This bounds
// cooperative admission waits, not a blocking callback or physical I/O.
s.admissionTimeout = 4 * time.Second
}
s.admission = newWALAdmission(walAdmissionConfig{
MaxConcurrent: 64,
SoftWatermark: 0.70,
@@ -379,8 +379,18 @@ func TestWALStoreV3_MapFailureRefusesQueuedSync(t *testing.T) {
s.v3.ownedMap.syncFile = func() error { return injected }
// Preparation is outside syncMu, so this failure must surface while the
// later Sync remains queued behind the held leader role.
if err := s.flusher.flushOnce(); !errors.Is(err, injected) {
t.Fatalf("map failure=%v", err)
flushed := make(chan error, 1)
go func() { flushed <- s.flusher.flushOnce() }()
select {
case err := <-flushed:
if !errors.Is(err, injected) {
t.Fatalf("map failure=%v", err)
}
case <-time.After(5 * time.Second):
// Release and join before failing; never abandon the flusher worker.
release()
<-flushed
t.Fatal("idle pressure check blocked map preparation behind Sync")
}
if s.stickyIOFault() == nil {
t.Error("map failure not globally latched before releasing Sync")
@@ -0,0 +1,300 @@
package storage
import (
"bytes"
"errors"
"fmt"
"path/filepath"
"sync"
"testing"
"time"
)
// Write six native WAL rings with the real background flusher and no client
// Sync. Production plain/chunk stores both own a map. The earlier unmapped
// dark fixture deliberately cannot reclaim without map coverage (covered by
// TestWALStoreV3FlusherWritesTheExtentButHoldsTheCheckpointUntilTheMap).
func TestWALStoreV3NoClientSyncSixRings(t *testing.T) {
for _, mode := range []WMode{WModeLagged, WModeStrict} {
t.Run(fmt.Sprintf("mode-%d", mode), func(t *testing.T) {
const walSize = 64 * 1024
const count = 6 * walSize / 4096
path := filepath.Join(t.TempDir(), "volume")
s, err := createMappedWALStoreV3ForTest(path, count, 4096, walSize, mode, 4)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = s.Close() })
// Exercise the production cooperative pressure budget (four seconds).
if s.admissionTimeout >= 5*time.Second {
t.Fatalf("budget=%v", s.admissionTimeout)
}
for i := uint32(0); i < count; i++ {
if _, err := s.Write(i, blk(byte(i+1))); err != nil {
t.Fatalf("no-client-Sync write %d/%d: %v", i, count, err)
}
}
for i := uint32(0); i < count; i++ {
got, err := s.Read(i)
if err != nil || !bytes.Equal(got, blk(byte(i+1))) {
t.Fatalf("readback %d: %v", i, err)
}
}
})
}
}
func pressureStoreNoSync(t *testing.T, records uint32) *WALStore {
t.Helper()
s, err := createMappedWALStoreV3ForTest(filepath.Join(t.TempDir(), "volume"), 96, 4096, 64*1024, WModeLagged, 4)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = s.Close() })
s.DisableAutoFlushForRecoveryTest()
for i := uint32(0); i < records; i++ {
if _, err := s.Write(i, blk(byte(i+1))); err != nil {
t.Fatal(err)
}
}
return s
}
func TestWALStoreV3PressureSyncFaultDoesNotPublishFrontiers(t *testing.T) {
for _, mode := range []WMode{WModeLagged, WModeStrict} {
for _, stage := range []string{"fsync", "slot"} {
t.Run(fmt.Sprintf("mode-%d/%s", mode, stage), func(t *testing.T) {
s := pressureStoreNoSync(t, 12)
if err := s.SetWMode(mode); err != nil {
t.Fatal(err)
}
// SetWMode syncs; add fresh uncovered writes without changing pressure.
if _, err := s.Write(0, blk(99)); err != nil {
t.Fatal(err)
}
before := s.v3.pub.current()
ack := s.v3.wack.Load()
boom := errors.New("pressure persistence fault")
if stage == "slot" {
s.v3.testBeforeSlotWrite = func() error { return boom }
} else {
s.syncWALFile = func() error { return boom }
s.v3.pub.io.fsync = func() error { return boom }
}
err := s.syncWALPressureV3()
if !errors.Is(err, boom) || s.stickyIOFault() == nil {
t.Fatalf("lost pressure fault: %v", err)
}
if s.v3.wack.Load() != ack || s.CheckpointLSN() != before.CheckpointLSN {
t.Fatal("failed pressure persistence advanced frontier")
}
if _, err := s.Write(1, blk(98)); !errors.Is(err, boom) {
t.Fatalf("subsequent write lost cause: %v", err)
}
})
}
}
}
func TestWALStoreV3PressureSyncSkipsInstalling(t *testing.T) {
s, _ := newStoreV3(t, WModeLagged)
t.Cleanup(func() { crashRecoveryHardeningStore(t, s) })
h := beginV3(t, s, 0, idA)
for i := uint64(1); i <= 12; i++ {
if err := h.ApplyInstallEntry(uint32(i), blk(byte(i)), i); err != nil {
t.Fatal(err)
}
}
before := s.v3.pub.current()
ack := s.v3.wack.Load()
if err := s.syncWALPressureV3(); err != nil {
t.Fatal(err)
}
if s.v3.pub.current() != before || s.v3.wack.Load() != ack {
t.Fatal("ordinary pressure sync bypassed install-log gate")
}
}
func TestWALStoreV3PressureWaitBudgetAndPin(t *testing.T) {
s, err := createMappedWALStoreV3ForTest(filepath.Join(t.TempDir(), "volume"), 96, 4096, 64*1024, WModeLagged, 4)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = s.Close() })
if s.admissionTimeout <= 0 || s.admissionTimeout >= 5*time.Second {
t.Fatalf("pressure budget %v", s.admissionTimeout)
}
// Contract used by an active RF2 catch-up session: do not release its records.
s.SetRecycleFloorSource(&fakeRecycleFloorSource{floor: 0, anyActive: true})
start := time.Now()
var got error
for i := uint32(0); i < 96; i++ {
if _, got = s.Write(i, blk(byte(i+1))); got != nil {
break
}
}
if !errors.Is(got, ErrWALPressureTimeout) || time.Since(start) >= 5*time.Second {
t.Fatalf("pinned burst outcome %v after %v", got, time.Since(start))
}
if s.CheckpointLSN() != 0 {
t.Fatal("active catch-up pin was bypassed")
}
}
// TryRLock refuses only once the pending exclusive operation is queued: the
// parked Write still owns a read lock. No sleep guesses when the Lock queues.
func TestWALStoreV3PressureProgressWithPendingCutOrClose(t *testing.T) {
for _, kind := range []string{"cut", "close", "lifecycle"} {
closing := kind == "close"
t.Run(kind, func(t *testing.T) {
s := pressureStoreNoSync(t, 15)
parked, resume := make(chan struct{}), make(chan struct{})
release := sync.OnceFunc(func() { close(resume) })
cutRelease := make(chan struct{})
releaseCut := sync.OnceFunc(func() { close(cutRelease) })
var joins []chan struct{}
t.Cleanup(func() {
release()
releaseCut()
for _, done := range joins {
select {
case <-done:
case <-time.After(6 * time.Second):
t.Error("pressure worker did not join")
}
}
})
var once sync.Once
s.admission.sleepFn = func(d time.Duration) { once.Do(func() { close(parked); <-resume }); time.Sleep(d) }
writerDone := make(chan struct{})
joins = append(joins, writerDone)
var writeErr error
go func() { defer close(writerDone); _, writeErr = s.Write(16, blk(16)) }()
select {
case <-parked:
case <-time.After(2 * time.Second):
t.Fatal("writer not parked")
}
exclusiveDone := make(chan struct{})
joins = append(joins, exclusiveDone)
go func() {
defer close(exclusiveDone)
if closing {
_ = s.Close()
} else if kind == "lifecycle" {
s.lifecycleMu.Lock()
defer s.lifecycleMu.Unlock()
<-cutRelease
} else {
s.captureMu.Lock()
defer s.captureMu.Unlock()
<-cutRelease
}
}()
deadline := time.Now().Add(time.Second)
for {
var admitted bool
if kind == "lifecycle" {
admitted = s.lifecycleMu.TryRLock()
if admitted {
s.lifecycleMu.RUnlock()
}
} else {
admitted = s.captureMu.TryRLock()
if admitted {
s.captureMu.RUnlock()
}
}
if !admitted {
break
}
if time.Now().After(deadline) {
t.Fatal("exclusive operation did not queue")
}
time.Sleep(time.Millisecond)
}
// Observe reaching physical persistence while the exclusive lock is
// pending; disk latency is not an oracle for a Go lock inversion.
physicalBoundary := make(chan struct{})
var boundaryOnce sync.Once
s.testBeforeFileSync = func() { boundaryOnce.Do(func() { close(physicalBoundary) }) }
flushDone := make(chan struct{})
joins = append(joins, flushDone)
var flushErr error
go func() { defer close(flushDone); flushErr = s.flusher.flushOnce() }()
select {
case <-physicalBoundary:
case <-time.After(5 * time.Second):
t.Fatal("pressure flusher did not reach persistence with exclusive lock pending")
}
// Join physical I/O before releasing the parked writer, so Close
// cannot close its file under this manually invoked cycle. This
// join bound is not the admission budget or a whole-I/O promise.
select {
case <-flushDone:
case <-time.After(10 * time.Second):
t.Fatal("pressure flusher physical I/O did not finish")
}
if flushErr != nil {
t.Fatal(flushErr)
}
release()
select {
case <-writerDone:
case <-time.After(3 * time.Second):
t.Fatal("writer did not drain")
}
// The test holds admission at sleep while real fsync runs. A slow
// disk may consume the unchanged production four-second budget;
// that typed outcome is permitted, never an indefinite lock wait.
if writeErr != nil && !errors.Is(writeErr, ErrWALPressureTimeout) {
t.Fatal(writeErr)
}
releaseCut()
select {
case <-exclusiveDone:
case <-time.After(10 * time.Second):
t.Fatal("exclusive operation did not finish")
}
})
}
}
func TestWALStoreV3FlushBatchCacheIsBoundToRecoveryLifetime(t *testing.T) {
s, err := createMappedWALStoreV3ForTest(filepath.Join(t.TempDir(), "volume"), 32, 4096, 64*1024, WModeStrict, 4)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = s.Close() })
s.DisableAutoFlushForRecoveryTest()
if _, err := s.WriteBatch(0, [][]byte{blk(1), blk(2), blk(3), blk(4)}); err != nil {
t.Fatal(err)
}
if _, err := s.Sync(); err != nil {
t.Fatal(err)
}
e := s.dm.snapshot()[0]
cache := &flushRecordCacheV3{recoveryGen: s.v3.recoverGen.Load()}
if _, _, err := s.flusher.readDirtyRecordV3Cached(e, cache); err != nil {
t.Fatal(err)
}
before := s.FlusherInstrumentation()
if err := s.flusher.flushOnce(); err != nil {
t.Fatal(err)
}
after := s.FlusherInstrumentation()
if got := after.WALRecordDecodeOps - before.WALRecordDecodeOps; got != 1 {
t.Fatalf("four-block batch decoded %d times, want1", got)
}
for i := uint32(0); i < 4; i++ {
if got, err := s.Read(i); err != nil || !bytes.Equal(got, blk(byte(i+1))) {
t.Fatalf("batch read%d: %v", i, err)
}
}
if _, err := s.Recover(); err != nil {
t.Fatal(err)
}
if _, _, err := s.flusher.readDirtyRecordV3Cached(e, cache); !errors.Is(err, ErrMapCoverageStale) {
t.Fatalf("old recovery lifetime cache accepted: %v", err)
}
}
+22 -7
View File
@@ -5,6 +5,7 @@ import (
"errors"
"os"
"path/filepath"
"sync"
"testing"
)
@@ -417,7 +418,7 @@ func TestWALStore_WriteBatchCopiesCallerBuffersIntoWALRecords(t *testing.T) {
// 1. Write blocks 0,1,2 + Sync (acked, must survive)
// 2. Write blocks 3,4 (NOT followed by Sync — may or may not survive)
// 3. Bypass Close — drop the file handle without finalizing
// anything (no superblock update, no fsync, no group-committer drain)
// anything (no superblock update, no fsync, no new commit batch)
// 4. Reopen + Recover
// 5. Acked blocks 0,1,2 MUST be present and intact
// 6. Post-Sync blocks 3,4 may be present OR absent — never corrupt
@@ -432,6 +433,20 @@ func TestWALStore_AckedWritesSurviveSimulatedCrash(t *testing.T) {
if err != nil {
t.Fatal(err)
}
// A simulated process crash cannot leave an old flusher using the
// descriptor. Stop it BEFORE writes: stopping after them could flush
// the very WAL replay this test is intended to exercise.
crash := sync.OnceFunc(func() {
s.DisableAutoFlushForRecoveryTest()
crashRecoveryHardeningStore(t, s)
})
t.Cleanup(crash)
s.DisableAutoFlushForRecoveryTest()
select {
case <-s.flusher.doneCh:
default:
t.Fatal("crash fixture flusher is still running before writes")
}
for i := uint32(0); i < 3; i++ {
if _, err := s.Write(i, makeBlock(4096, byte(0xA0+i))); err != nil {
t.Fatal(err)
@@ -441,18 +456,18 @@ func TestWALStore_AckedWritesSurviveSimulatedCrash(t *testing.T) {
if _, err := s.Sync(); err != nil {
t.Fatal(err)
}
if cp := s.CheckpointLSN(); cp != 0 {
t.Fatalf("crash fixture checkpoint=%d, want uncheckpointed WAL", cp)
}
// Unacked: may or may not survive.
for i := uint32(3); i < 5; i++ {
if _, err := s.Write(i, makeBlock(4096, byte(0xA0+i))); err != nil {
t.Fatal(err)
}
}
// Simulate crash: stop the group committer (so it doesn't
// race the file close), then drop the *os.File handle without
// going through Close(). The on-disk state is whatever was
// fsync'd by the Sync call above; nothing else.
s.committer.Stop()
_ = s.fd.Close()
// Drop descriptors without store.Close(), a final checkpoint or
// another Sync. Cleanup also runs on an earlier assertion failure.
crash()
}()
// Reopen + Recover. The acked blocks must be present.
+68 -16
View File
@@ -778,22 +778,50 @@ func (s *WALStore) replayRecordV3(r walScannedRecordV3, walSize uint64, blockSiz
// syncWALBatchV3 is the committer leader's batch for a v3 store (DESIGN 6.2,
// 6.3). The cut H is every record pwritten before the leader starts.
func (s *WALStore) syncWALBatchV3() error {
return s.syncWALBatchV3Internal(false)
}
// Called only by the flusher, without capture/lifecycle/store locks. Pressure
// cannot depend on a guest Flush: persist locally before checkpointing, using
// the same physical sync and final fault gate as an ordinary sync batch.
func (s *WALStore) syncWALPressureV3() error {
return s.syncWALBatchV3Internal(true)
}
func (s *WALStore) syncWALBatchV3Internal(pressureOnly bool) error {
if err := s.stickyIOFault(); err != nil {
return err
}
v := s.v3
// An idle flusher must not queue behind an unrelated Sync leader before
// preparing its map. This is only a scheduling hint: pressure eligibility
// and the mutation/frontier cut are still rechecked together under syncMu.
// A concurrent append missed here is picked up by the next notified cycle.
if pressureOnly && s.walUsedFraction() < 0.70 {
return nil
}
// The leader role: SetWMode holds it while it changes the mode, so no
// batch acknowledges under a stale mode selection (the mode is read
// only after the role is taken).
if h := v.testLeaderWaiting; h != nil && !pressureOnly {
h()
}
v.syncMu.Lock()
defer v.syncMu.Unlock()
if pressureOnly {
// Recheck under the same leader interval as the mutation/frontier cut.
// Installing uses receiver-owned SyncInstallLog, never this normal path.
s.mu.RLock()
closed := s.closed
s.mu.RUnlock()
if closed || v.pub.current().BaseState == BaseInstalling || s.walUsedFraction() < 0.70 || v.appended.Load() <= v.wack.Load() {
return nil
}
}
cut := s.walMutation.Load()
if !s.bypassSyncDedup.Load() && s.chunk.Load() == nil && cut <= s.durableMutation.Load() {
return nil
}
v := s.v3
// The leader role: SetWMode holds it while it changes the mode, so no
// batch acknowledges under a stale mode selection (the mode is read
// only after the role is taken).
if h := v.testLeaderWaiting; h != nil {
h()
}
v.syncMu.Lock()
defer v.syncMu.Unlock()
H, prev := v.appended.Load(), v.wack.Load()
// One sample per covering WAL batch, as on v2. In mode C the slot
// publication is the physical sync; mode A also settles its W slot.
@@ -1043,7 +1071,18 @@ func blockOfRecordV3(e walEntryV3, lba uint64, dataOff uint32, lsn uint64, block
// readDirtyRecordV3 is the flusher's record read for a v3 store: it decodes
// and validates the whole record before its data may reach the extent.
func (f *flusher) readDirtyRecordV3(e snapshotEntry) (data []byte, entrySize uint64, err error) {
type flushRecordCacheV3 struct {
recoveryGen uint64
offset, size uint64
entry walEntryV3
valid bool
}
func (f *flusher) readDirtyRecordV3(e snapshotEntry) ([]byte, uint64, error) {
return f.readDirtyRecordV3Cached(e, nil)
}
func (f *flusher) readDirtyRecordV3Cached(e snapshotEntry, cache *flushRecordCacheV3) (data []byte, entrySize uint64, err error) {
readFailed := false
defer func() {
if err == nil {
@@ -1054,13 +1093,26 @@ func (f *flusher) readDirtyRecordV3(e snapshotEntry) (data []byte, entrySize uin
}()
store := f.store
d := store.v3.pub.current()
entry, size, ioErr, verr := readWholeRecordProfiledV3(store.fd, recordGeometryV3{store.sb.WALOffset, store.sb.WALSize, store.sb.BlockSize, store.sb.VolumeSize}, e.WALOffset, &f.instr)
if ioErr != nil {
readFailed = true
return nil, 0, fmt.Errorf("flusher: read v3 WAL record at %d: %w", e.WALOffset, ioErr)
if cache != nil && !store.v3.flushLifetimeValidV3(cache.recoveryGen) {
return nil, 0, ErrMapCoverageStale
}
if verr != nil {
return nil, 0, fmt.Errorf("flusher: invalid v3 WAL record LBA %d offset %d: %w", e.LBA, e.WALOffset, verr)
var entry walEntryV3
var size uint64
if cache != nil && cache.valid && cache.offset == e.WALOffset {
entry, size = cache.entry, cache.size
} else {
var ioErr, verr error
entry, size, ioErr, verr = readWholeRecordProfiledV3(store.fd, recordGeometryV3{store.sb.WALOffset, store.sb.WALSize, store.sb.BlockSize, store.sb.VolumeSize}, e.WALOffset, &f.instr)
if ioErr != nil {
readFailed = true
return nil, 0, fmt.Errorf("flusher: read v3 WAL record at %d: %w", e.WALOffset, ioErr)
}
if verr != nil {
return nil, 0, fmt.Errorf("flusher: invalid v3 WAL record LBA %d offset %d: %w", e.LBA, e.WALOffset, verr)
}
if cache != nil {
cache.entry, cache.size, cache.offset, cache.valid = entry, size, e.WALOffset, true
}
}
if entry.Nonce != d.Nonce || e.Length != store.sb.BlockSize {
return nil, 0, fmt.Errorf("flusher: v3 WAL slot mismatch LBA %d offset %d", e.LBA, e.WALOffset)
@@ -177,7 +177,7 @@ stateDiagram-v2
Cleanup --> Retry: ABORTED, merge all candidates back
```
**Statistics.** `barrierPauseNs` covers Sync and window installation; native `barrierCopyChunks` is zero. `copyNs` covers outside-barrier materialization/drain. `cowSavedChunks` counts successful saves; `cowSaveNs` and `cowWaitNs` sum per-owner/per-wait elapsed time and are not wall-clock pause. These fields mirror into the actual cut response. Upload sizes and remote GC roots are unchanged.
**Statistics.** `barrierPauseNs` runs from the capture barrier's Lock request to its release: `lockWaitNs` (the wait for writers already holding it shared), Sync and window installation; native `barrierCopyChunks` is zero. `copyNs` covers outside-barrier materialization/drain. `cowSavedChunks` counts successful saves; `cowSaveNs` and `cowWaitNs` sum per-owner/per-wait elapsed time and are not wall-clock pause. These fields mirror into the actual cut response. Upload sizes and remote GC roots are unchanged.
**Model and tests.** The existing S4c r2 `CutCOW2` verdict and limits are bound in the [spec correspondence](../spec/README.md#cut-window-implementation-correspondence). One-copier whole-chunk modelling does not certify actual writer ownership, batches or Close/attach. `TestCutCOWV3_*` exercises real native mutation, abort, spill, recovery and close callers; earlier ACTIVE staging/image/intent/CAS controls remain. See [the implementation lock graph and mount rehearsal](cut-cow-validation.md).
@@ -45,7 +45,9 @@ this volume's reserved `.cut-cow-` prefix; other prefixes, directories and
symlinks are left alone. Cleanup failure fails the cut diagnostically, without
changing any guest write outcome.
`barrierPauseNs` includes Sync/window setup, not chunk reads. `copyNs` is the
`barrierPauseNs` runs from the capture barrier's Lock request (a pending Lock
already blocks new writers) to its release: it includes `lockWaitNs`, the wait for
writers already holding the barrier shared, and Sync/window setup, not chunk reads. `copyNs` is the
outside-barrier copy and drain. Native `barrierCopyChunks`/`barrierOverBound`
are zero; the configured threshold still bounds staging, not a hard COW-copy
limit. `cowSavedChunks`, `cowSaveNs`, `cowWaitNs` are mirrored into the cut
+40
View File
@@ -262,6 +262,46 @@ HEAD states, snapshots, forks, intents, key bindings, GC and volume delete in th
---
### Local WAL-pressure durability progress
A serving v3 store at the soft WAL watermark may perform an internal local
sync from its existing flusher, before snapshotting dirty work. This transition
uses the ordinary A/C physical-sync and final fault gate under one `syncMu`
interval; it takes neither `captureMu` nor `lifecycleMu`. It is ineligible while
BASE is installing or the store is closed. The leader is released before extent,
map and checkpoint publication. Client Flush acknowledgements keep their own
covering durability and observer requirements. Recovery invalidates the existing
snapshot lifetime; local persistence does not bypass it.
- `INV-WAL-V3-PRESSURE-001`: I1, within a recovery/reset lifetime `wack` advances
only after covering local persistence; I2, checkpoint remains at most `wack`
and the active-session pin floor; I3, record reuse remains below the durable
checkpoint, both-slot floor and dirty-reference retirement; I4, with healthy
local progress and no guest Sync, the reuse floor advances. Enforced by
`syncWALBatchV3Internal`, `persistOwnedMapCheckpointV3` and the existing reclaim
publisher. Tests: `TestWALStoreV3NoClientSyncSixRings`,
`TestWALStoreV3PressureSyncFaultDoesNotPublishFrontiers`,
`TestWALStoreV3PressureSyncSkipsInstalling`,
`TestWALStoreV3PressureProgressWithPendingCutOrClose` and
`TestWALStoreV3PressureWaitBudgetAndPin`. Model correspondence: `WALReclaim.tla` I1/I2/I3 and
`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.
- The v3 pressure admission budget is four seconds of cooperative waiting. It
cannot preempt a blocking occupancy/closed callback, lock acquisition or
physical file I/O. 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.
- A flusher cycle sorts native snapshot entries by record offset and reuses at
most one fully validated record (bounded by WALSize). Every block still checks
its LBA/data offset/LSN/nonce; the cache is local to the snapshot recovery
generation and cannot publish or materialize after that lifetime changes.
`TestWALStoreV3FlushBatchCacheIsBoundToRecoveryLifetime` covers one batch decode
and refusal after Recover. Missing map coverage still forbids checkpoint
advancement; the earlier unmapped dark fixture is not a production geometry.
## Part B. Invariant ledger
80 rows: 69 ACTIVE, 11 STUB; 15 kept from the internal ledger, 65 new.
+28
View File
@@ -274,3 +274,31 @@ Recover/reset snapshot recheck and saved-file readers are covered by the
native `TestCutCOWV3_*` caller controls, not claimed as model proofs.
The earlier thirteen-spec parse statement above predates this imported model;
no new independent TLC/parse or cloud run is claimed here.
### WAL pressure progress without guest Sync
`WALReclaim.tla` models native local pressure persistence and checkpoint/reuse
progress. `InternalSync` is weakly fair and does not take the capture lock;
`GuestSync` has no fairness requirement. `REC_safe.cfg` and `REC_safe_big.cfg`
check I1/I2/I3, ring/pin safety, `AllWritten` and `NoStuckWaiter`. Removing internal
sync (`REC_red_noInternalSync.cfg`) violates liveness; removing the durable clamp
violates I2. The capture-lock mutant and permanently held pin also violate
liveness. The Go implementation bounds a permanent pin with retryable admission
expiry rather than assuming that it always releases.
Run, from `docs/spec`, with the existing TLC tool:
```sh
java -cp /path/to/tla2tools.jar tlc2.TLC -deadlock -config cfg/REC_safe.cfg WALReclaim
java -cp /path/to/tla2tools.jar tlc2.TLC -deadlock -config cfg/REC_red_noInternalSync.cfg WALReclaim
```
The authored LIGHT receipts report exhaustive safe searches at 2,700 and 25,550
states, plus the expected mutant/witness failures. Source and configs are copied
from the sealed `claude05-walreclaim-tla-r0-20261119` artifact with line-ending
normalization only. Those are prior author runs, not a claim that this PR reran
TLC. This is an abstraction: physical fsync success, byte layout, crash recovery,
both-slot retirement, timing and multiple writers remain covered by their other
models and actual Go controls. Do not treat finite liveness checking as an
end-to-end wall-clock latency guarantee. Keep long model runs off tp04.
+119
View File
@@ -0,0 +1,119 @@
----------------------------- MODULE WALReclaim -----------------------------
(***************************************************************************)
(* Liveness of v3 WAL reclaim under write pressure (claude05, 2026-11-19). *)
(* Abstracts core/storage at seaweed-block main 39f11d6a: *)
(* head = WAL head LSN (records appended) *)
(* wack = durable WAL frontier; today advanced only by Sync *)
(* (walstore_v3.go:829) *)
(* flushed = records the flusher has written to the extent *)
(* ckpt = checkpoint = reuse floor, clamped to *)
(* min(flushed, wack, session pin) *)
(* (walstore_map_checkpoint_v3.go:57-62) *)
(* A writer may append only while head - ckpt < Cap (the hard watermark). *)
(* A blocked writer waits INSIDE the capture read lock *)
(* (walstore.go:829-832, admission at :850). A cut takes the capture *)
(* write lock; Go's RWMutex makes a pending writer block new readers. *)
(* *)
(* InternalOn: the fix under review (codex03 design r0) - under pressure *)
(* the store makes its own WAL durable (wack := head) with no guest Sync. *)
(* Mut: *)
(* "none" the design *)
(* "noClamp" checkpoint ignores wack (reclaims non-durable WAL) *)
(* "syncTakesCapture" the internal sync needs the capture read lock *)
(* (finding F2) *)
(* PinFair: a catch-up session pin is eventually released (finding F3). *)
(* The guest's Sync has NO fairness: a guest may never flush. *)
(***************************************************************************)
EXTENDS Naturals
CONSTANTS Cap, MaxLSN, MaxCuts, MaxPins, InternalOn, Mut, PinOn, PinFair
VARIABLES head, wack, flushed, ckpt, inside, cutPending, cuts, pin, pins, gsync
vars == <<head, wack, flushed, ckpt, inside, cutPending, cuts, pin, pins, gsync>>
Min(a, b) == IF a < b THEN a ELSE b
NoPin == MaxLSN + 1
Full == head - ckpt >= Cap
Init == /\ head = 0 /\ wack = 0 /\ flushed = 0 /\ ckpt = 0
/\ inside = FALSE /\ cutPending = FALSE /\ cuts = 0 /\ pin = NoPin /\ pins = 0 /\ gsync = FALSE
\* A writer that finds the ring full enters the admission wait holding the
\* capture read lock; it can enter only if no cut is pending.
EnterWait == /\ head < MaxLSN /\ Full /\ ~inside /\ ~cutPending
/\ inside' = TRUE
/\ UNCHANGED <<head, wack, flushed, ckpt, cutPending, cuts, pin, pins, gsync>>
\* Append: a fresh writer needs the read lock (blocked by a pending cut); a
\* writer already inside the wait holds it.
Append == /\ head < MaxLSN /\ ~Full /\ (inside \/ ~cutPending)
/\ head' = head + 1 /\ inside' = FALSE
/\ UNCHANGED <<wack, flushed, ckpt, cutPending, cuts, pin, pins, gsync>>
\* Guest Flush/Sync: may happen or never (no fairness).
GuestSync == /\ wack < head
/\ wack' = head /\ gsync' = TRUE
/\ UNCHANGED <<head, flushed, ckpt, inside, cutPending, cuts, pin, pins>>
\* The fix: internal sync on pressure. In the mutant it also needs the
\* capture read lock, so it is blocked while a cut is pending.
InternalSync == /\ InternalOn /\ wack < head /\ Full
/\ (Mut = "syncTakesCapture" => ~cutPending)
/\ wack' = head
/\ UNCHANGED <<head, flushed, ckpt, inside, cutPending, cuts, pin, pins, gsync>>
Flush == /\ flushed < head
/\ flushed' = flushed + 1
/\ UNCHANGED <<head, wack, ckpt, inside, cutPending, cuts, pin, pins, gsync>>
Target == IF Mut = "noClamp" THEN Min(flushed, pin) ELSE Min(Min(flushed, wack), pin)
Checkpoint == /\ Target > ckpt
/\ ckpt' = Target
/\ UNCHANGED <<head, wack, flushed, inside, cutPending, cuts, pin, pins, gsync>>
\* A cut requests the capture write lock; it completes once no reader holds
\* the lock (the waiting writer is a reader).
CutStart == /\ cuts < MaxCuts /\ ~cutPending
/\ cutPending' = TRUE /\ cuts' = cuts + 1
/\ UNCHANGED <<head, wack, flushed, ckpt, inside, pin, pins, gsync>>
CutFinish == /\ cutPending /\ ~inside
/\ cutPending' = FALSE
/\ UNCHANGED <<head, wack, flushed, ckpt, inside, cuts, pin, pins, gsync>>
\* An RF2 catch-up session pins the WAL at the current checkpoint, later
\* releases it.
PinSet == /\ PinOn /\ pin = NoPin /\ pins < MaxPins
/\ pin' = ckpt /\ pins' = pins + 1
/\ UNCHANGED <<head, wack, flushed, ckpt, inside, cutPending, cuts, gsync>>
PinRelease == /\ pin # NoPin
/\ pin' = NoPin
/\ UNCHANGED <<head, wack, flushed, ckpt, inside, cutPending, cuts, pins, gsync>>
Next == \/ EnterWait \/ Append \/ GuestSync \/ InternalSync \/ Flush \/ Checkpoint
\/ CutStart \/ CutFinish \/ PinSet \/ PinRelease
Fairness == /\ WF_vars(Append) /\ WF_vars(EnterWait) /\ WF_vars(Flush) /\ WF_vars(Checkpoint)
/\ WF_vars(InternalSync) /\ WF_vars(CutFinish)
/\ (PinFair => WF_vars(PinRelease))
Spec == Init /\ [][Next]_vars /\ Fairness
\* ---- safety ----
TypeOK == /\ head \in 0..MaxLSN /\ wack \in 0..MaxLSN /\ flushed \in 0..MaxLSN
/\ ckpt \in 0..MaxLSN /\ inside \in BOOLEAN /\ cutPending \in BOOLEAN
/\ cuts \in 0..MaxCuts /\ pin \in 0..(MaxLSN + 1) /\ pins \in 0..MaxPins /\ gsync \in BOOLEAN
I1 == wack <= head \* durable frontier never ahead of the head
I2 == ckpt <= wack \* never reclaim WAL that is not durable
I3 == ckpt <= flushed \* never reclaim a record not yet in the extent
IRing == head - ckpt <= Cap \* the ring never overflows
IPin == pin # NoPin => ckpt >= pin \* a pin never moves the floor backwards (sanity)
\* ---- witness: all writes complete with NO guest Sync (must be violated = reachable when InternalOn) ----
W_NeedsGuestSync == ~(head = MaxLSN /\ ~gsync)
\* ---- liveness ----
AllWritten == <>(head = MaxLSN) \* no write stalls forever
NoStuckWaiter == [](inside => <>(~inside)) \* a waiting writer is always admitted
=============================================================================
@@ -0,0 +1,12 @@
\* REC_red_noClamp
SPECIFICATION Spec
CONSTANTS
Cap = 2
MaxLSN = 5
MaxCuts = 2
MaxPins = 1
InternalOn = TRUE
Mut = "noClamp"
PinOn = TRUE
PinFair = TRUE
INVARIANT TypeOK I1 I2 I3 IRing
@@ -0,0 +1,13 @@
\* REC_red_noInternalSync
SPECIFICATION Spec
CONSTANTS
Cap = 2
MaxLSN = 5
MaxCuts = 2
MaxPins = 1
InternalOn = FALSE
Mut = "none"
PinOn = TRUE
PinFair = TRUE
INVARIANT TypeOK I1 I2 I3 IRing
PROPERTY AllWritten
@@ -0,0 +1,13 @@
\* REC_red_pinForever
SPECIFICATION Spec
CONSTANTS
Cap = 2
MaxLSN = 5
MaxCuts = 2
MaxPins = 1
InternalOn = TRUE
Mut = "none"
PinOn = TRUE
PinFair = FALSE
INVARIANT TypeOK I1 I2 I3 IRing
PROPERTY AllWritten
@@ -0,0 +1,13 @@
\* REC_red_syncTakesCapture
SPECIFICATION Spec
CONSTANTS
Cap = 2
MaxLSN = 5
MaxCuts = 2
MaxPins = 1
InternalOn = TRUE
Mut = "syncTakesCapture"
PinOn = TRUE
PinFair = TRUE
INVARIANT TypeOK I1 I2 I3 IRing
PROPERTY AllWritten
@@ -0,0 +1,13 @@
\* REC_red_syncTakesCapture_big
SPECIFICATION Spec
CONSTANTS
Cap = 3
MaxLSN = 9
MaxCuts = 3
MaxPins = 2
InternalOn = TRUE
Mut = "syncTakesCapture"
PinOn = TRUE
PinFair = TRUE
INVARIANT TypeOK I1 I2 I3 IRing
PROPERTY AllWritten
+13
View File
@@ -0,0 +1,13 @@
\* REC_safe
SPECIFICATION Spec
CONSTANTS
Cap = 2
MaxLSN = 5
MaxCuts = 2
MaxPins = 1
InternalOn = TRUE
Mut = "none"
PinOn = TRUE
PinFair = TRUE
INVARIANT TypeOK I1 I2 I3 IRing IPin
PROPERTY AllWritten NoStuckWaiter
@@ -0,0 +1,13 @@
\* REC_safe_big
SPECIFICATION Spec
CONSTANTS
Cap = 3
MaxLSN = 9
MaxCuts = 3
MaxPins = 2
InternalOn = TRUE
Mut = "none"
PinOn = TRUE
PinFair = TRUE
INVARIANT TypeOK I1 I2 I3 IRing IPin
PROPERTY AllWritten NoStuckWaiter
@@ -0,0 +1,12 @@
\* REC_wit_noGuestSync
SPECIFICATION Spec
CONSTANTS
Cap = 2
MaxLSN = 5
MaxCuts = 2
MaxPins = 1
InternalOn = TRUE
Mut = "none"
PinOn = TRUE
PinFair = TRUE
INVARIANT W_NeedsGuestSync
@@ -0,0 +1,29 @@
#!/usr/bin/env python3
"""Check three-sample manifest benchmark scaling; no device or host access.
Run go test with -bench BenchmarkPrepareManifestUnchangedGroups -benchtime=20x
-count=3, save stdout, then pass that file to this checker. A 16x metadata
scale must grow less than 64x on the same serial runner. This is an explicit
qualification benchmark, not a wall-clock CI unit test.
"""
import re
import statistics
import sys
from pathlib import Path
if len(sys.argv) != 2:
raise SystemExit("usage: check-manifest-scaling.py BENCHMARK_LOG")
samples = {256: [], 1024: [], 4096: []}
for count, ns in re.findall(
r"BenchmarkPrepareManifestUnchangedGroups/(256|1024|4096)-\d+\s+\d+\s+(\d+) ns/op",
Path(sys.argv[1]).read_text(encoding="utf-8-sig"),
):
samples[int(count)].append(int(ns))
if any(len(values) != 3 for values in samples.values()):
raise SystemExit("need exactly three samples per group count")
medians = {count: statistics.median(values) for count, values in samples.items()}
if min(medians.values()) <= 0:
raise SystemExit("benchmark durations must be positive")
growth = medians[4096] / medians[256]
print("median_ns", medians, "growth_4096_over_256", growth, "limit", 64)
raise SystemExit(0 if growth < 64 else 1)