Merge pull request #173 from seaweedfs/fix/group-commit-singleton-latency

perf(storage): avoid collection delay for singleton syncs
This commit is contained in:
Ping Qiu authored and GitHub committed 2026-11-16 16:08:11 -08:00
commit 86530111dc
10 files changed
+774 -7

No files matched your search

@@ -0,0 +1,99 @@
package durable_test
import (
"bytes"
"context"
"encoding/json"
"fmt"
"github.com/seaweedfs/seaweed-block/core/frontend"
"github.com/seaweedfs/seaweed-block/core/frontend/durable"
"github.com/seaweedfs/seaweed-block/core/storage"
"os"
"os/exec"
"sort"
"testing"
"time"
)
func BenchmarkQD1PairedBackendSync(b *testing.B) {
for _, impl := range []durable.ImplName{durable.ImplSmartWAL, durable.ImplWALStoreChunk} {
b.Run(string(impl), func(b *testing.B) {
id := frontend.Identity{VolumeID: "v1", ReplicaID: "r1", Epoch: 1, EndpointVersion: 1}
root := b.TempDir()
diagnosticCtx, cancelDiagnostic := context.WithTimeout(context.Background(), 2*time.Second)
out, diagnosticErr := exec.CommandContext(diagnosticCtx, "findmnt", "-T", root, "-no", "SOURCE,FSTYPE,TARGET").CombinedOutput()
cancelDiagnostic()
if diagnosticErr == nil {
fmt.Printf("STUDY_FS %s", out)
}
cfg := durable.ProviderConfig{Impl: impl, StorageRoot: root, NumBlocks: 32768, BlockSize: 4096, ChunkBlocks: 1024}
remote := storage.NewMemChunkRemote()
if impl == durable.ImplWALStoreChunk {
cfg.ChunkRemoteFor = func(string) (storage.ChunkRemote, error) { return remote, nil }
}
p, err := durable.NewDurableProvider(cfg, newStubView(healthyProj(id)))
if err != nil {
b.Fatal(err)
}
defer p.Close()
raw, err := p.Open(context.Background(), "v1")
if err != nil {
b.Fatal(err)
}
if _, err := p.RecoverVolume(context.Background(), "v1"); err != nil {
b.Fatal(err)
}
backend := raw.(*durable.StorageBackend)
payload := make([]byte, 4096)
b.StopTimer()
// Same QD1 request shape as the guest: one write followed by two Sync calls.
for i := 0; i < 20; i++ {
if _, err := backend.Write(context.Background(), 0, payload); err != nil {
b.Fatal(err)
}
for j := 0; j < 2; j++ {
if err := backend.Sync(context.Background()); err != nil {
b.Fatal(err)
}
}
}
profile := backend.WriteProfile()
samples := make([]int64, 0, 2*b.N)
b.ResetTimer()
for i := 0; i < b.N; i++ {
b.StopTimer()
payload[0] = byte(i)
if _, err := backend.Write(context.Background(), int64(i%8192)*4096, payload); err != nil {
b.Fatal(err)
}
b.StartTimer()
for j := 0; j < 2; j++ {
start := time.Now()
if err := backend.Sync(context.Background()); err != nil {
b.Fatal(err)
}
samples = append(samples, time.Since(start).Nanoseconds())
}
}
b.StopTimer()
post := backend.WriteProfile()
n := uint64(2 * b.N)
if post.BackendSyncOps-profile.BackendSyncOps != n {
b.Fatal("D0 Sync count changed")
}
sort.Slice(samples, func(i, j int) bool { return samples[i] < samples[j] })
var total int64
for _, v := range samples {
total += v
}
var got [4096]byte
if _, err := backend.Read(context.Background(), int64((b.N-1)%8192)*4096, got[:]); err != nil || !bytes.Equal(got[:], payload) {
b.Fatal("last write bytes mismatch", err)
}
report := map[string]any{"impl": impl, "iterations": b.N, "syncs": n, "sync_mean_ns": float64(total) / float64(n), "sync_p50_ns": samples[len(samples)/2], "sync_p99_ns": samples[(len(samples)*99-1)/100], "variant": os.Getenv("STUDY_VARIANT")}
data, _ := json.Marshal(report)
fmt.Printf("M5_SYNC_STUDY %s\n", data)
b.ReportMetric(float64(total)/float64(n), "ns/Sync")
})
}
}
@@ -0,0 +1,72 @@
package durable_test
import (
"bytes"
"context"
"fmt"
"os"
"os/exec"
"sync/atomic"
"testing"
"time"
)
type stalledSyncProxy struct {
release chan struct{}
done chan struct{}
exited atomic.Int32
}
func (p *stalledSyncProxy) Write(_ context.Context, _ int64, data []byte) (int, error) {
return len(data), nil
}
func (p *stalledSyncProxy) Sync(context.Context) error {
// Match contextless LogicalStorage.Sync: cancellation cannot release it.
<-p.release
if p.exited.Add(1) == 8 {
close(p.done)
}
return nil
}
func TestConcurrentSyncProxyStallChild(t *testing.T) {
if os.Getenv("SYNC_PROXY_STALL_CHILD") != "1" {
t.Skip("subprocess failure control only")
}
backend := &stalledSyncProxy{release: make(chan struct{}), done: make(chan struct{})}
t.Cleanup(func() {
close(backend.release)
select {
case <-backend.done:
fmt.Println("STALL_CONTROL_CLEANUP all8 Sync workers released")
case <-time.After(time.Second):
t.Error("stalled workers did not settle during cleanup")
}
})
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
_, _ = runConcurrentSyncProxy(t, ctx, backend, 8, 100000)
t.Fatal("stalled real-style Sync unexpectedly completed")
}
func TestConcurrentSyncProxyStallFailsWithinDeadline(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestConcurrentSyncProxyStallChild$", "-test.v")
cmd.Env = append(os.Environ(), "SYNC_PROXY_STALL_CHILD=1")
cmd.WaitDelay = time.Second
out, err := cmd.CombinedOutput()
if ctx.Err() != nil {
t.Fatalf("local wait bound failed; subprocess deadline reached: %v\n%s", ctx.Err(), out)
}
exit, ok := err.(*exec.ExitError)
if !ok || exit.ExitCode() != 1 {
t.Fatalf("expected deliberate test failure exit1: %v\n%s", err, out)
}
for _, marker := range []string{"timed out waiting for backend Sync workers", "goroutine ", "stalledSyncProxy).Sync", "STALL_CONTROL_CLEANUP all8 Sync workers released"} {
if !bytes.Contains(out, []byte(marker)) {
t.Fatalf("missing %q in bounded stall receipt\n%s", marker, out)
}
}
t.Logf("context-ignoring Sync produced bounded failure, stack dump and cleanup: %d receipt bytes", len(out))
}
@@ -0,0 +1,129 @@
package durable_test
import (
"bytes"
"context"
"encoding/json"
"fmt"
"github.com/seaweedfs/seaweed-block/core/frontend"
"github.com/seaweedfs/seaweed-block/core/frontend/durable"
"github.com/seaweedfs/seaweed-block/core/storage"
"os"
"runtime"
"sync"
"testing"
"time"
)
func BenchmarkConcurrentBackendSync(b *testing.B) {
for _, impl := range []durable.ImplName{durable.ImplSmartWAL, durable.ImplWALStoreChunk} {
for _, qd := range []int{8, 32} {
b.Run(fmt.Sprintf("%s/QD%d", impl, qd), func(b *testing.B) {
id := frontend.Identity{VolumeID: "v1", ReplicaID: "r1", Epoch: 1, EndpointVersion: 1}
cfg := durable.ProviderConfig{Impl: impl, StorageRoot: b.TempDir(), NumBlocks: 32768, BlockSize: 4096, ChunkBlocks: 1024}
if impl == durable.ImplWALStoreChunk {
r := storage.NewMemChunkRemote()
cfg.ChunkRemoteFor = func(string) (storage.ChunkRemote, error) { return r, nil }
}
p, err := durable.NewDurableProvider(cfg, newStubView(healthyProj(id)))
if err != nil {
b.Fatal(err)
}
defer p.Close()
raw, err := p.Open(context.Background(), "v1")
if err != nil {
b.Fatal(err)
}
if _, err := p.RecoverVolume(context.Background(), "v1"); err != nil {
b.Fatal(err)
}
backend := raw.(*durable.StorageBackend)
profile := backend.WriteProfile()
workloadCtx, cancelWorkload := context.WithTimeout(context.Background(), 30*time.Second)
b.ResetTimer()
elapsed, workloadErr := runConcurrentSyncProxy(b, workloadCtx, backend, qd, b.N)
b.StopTimer()
cancelWorkload()
if workloadErr != nil {
b.Fatal(workloadErr)
}
post := backend.WriteProfile()
n := uint64(qd * b.N)
if post.BackendSyncOps-profile.BackendSyncOps != n {
b.Fatal("Sync count changed")
}
for w := 0; w < qd; w++ {
got := make([]byte, 4096)
if _, err := backend.Read(context.Background(), int64(w)*4096, got); err != nil || !bytes.Equal(got, bytes.Repeat([]byte{byte(w + 1)}, 4096)) {
b.Fatal("readback", w, err)
}
}
row := map[string]any{"impl": impl, "qd": qd, "iterations": b.N, "syncs": n, "elapsed_ns": elapsed.Nanoseconds(), "syncs_per_second": float64(n) / elapsed.Seconds(), "variant": os.Getenv("STUDY_VARIANT")}
data, _ := json.Marshal(row)
fmt.Printf("M5_CONCURRENT %s\n", data)
b.ReportMetric(float64(n)/elapsed.Seconds(), "Sync/s")
})
}
}
}
// Local file I/O is not interruptible by context. Bound the completion wait;
// a stalled operation fails the benchmark with its goroutine stacks. The caller
// registers backend cleanup before starting this workload.
type concurrentSyncProxyBackend interface {
Write(context.Context, int64, []byte) (int, error)
Sync(context.Context) error
}
func runConcurrentSyncProxy(tb testing.TB, ctx context.Context, backend concurrentSyncProxyBackend, qd, iterations int) (time.Duration, error) {
tb.Helper()
ctx, cancel := context.WithCancel(ctx)
defer cancel()
start := make(chan struct{})
errs := make(chan error, qd)
var wg sync.WaitGroup
for w := 0; w < qd; w++ {
wg.Add(1)
go func(w int) {
defer wg.Done()
<-start
fail := func(err error) { errs <- err; cancel() }
payload := bytes.Repeat([]byte{byte(w + 1)}, 4096)
for i := 0; i < iterations; i++ {
if err := ctx.Err(); err != nil {
fail(err)
return
}
if _, err := backend.Write(ctx, int64(w)*4096, payload); err != nil {
fail(err)
return
}
if err := ctx.Err(); err != nil {
fail(err)
return
}
if err := backend.Sync(ctx); err != nil {
fail(err)
return
}
}
}(w)
}
started := time.Now()
close(start)
done := make(chan struct{})
go func() { wg.Wait(); close(done) }()
select {
case <-done:
case <-ctx.Done():
dump := make([]byte, 1<<20)
n := runtime.Stack(dump, true)
tb.Fatalf("timed out waiting for backend Sync workers: %v\n%s", ctx.Err(), dump[:n])
}
elapsed := time.Since(started)
close(errs)
for err := range errs {
return elapsed, err
}
return elapsed, ctx.Err()
}
@@ -0,0 +1,104 @@
package durable_test
import (
"bytes"
"context"
"fmt"
"os"
"os/exec"
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/frontend"
"github.com/seaweedfs/seaweed-block/core/frontend/durable"
"github.com/seaweedfs/seaweed-block/core/storage"
)
func qd1CrashProvider(t *testing.T, impl durable.ImplName, root string) (*durable.DurableProvider, *durable.StorageBackend) {
t.Helper()
id := frontend.Identity{VolumeID: "v1", ReplicaID: "r1", Epoch: 1, EndpointVersion: 1}
cfg := durable.ProviderConfig{Impl: impl, StorageRoot: root, NumBlocks: 128, BlockSize: 4096, ChunkBlocks: 4}
if impl == durable.ImplWALStoreChunk {
remote := storage.NewMemChunkRemote()
cfg.ChunkRemoteFor = func(string) (storage.ChunkRemote, error) { return remote, nil }
}
p, err := durable.NewDurableProvider(cfg, newStubView(healthyProj(id)))
if err != nil {
t.Fatal(err)
}
setupComplete := false
defer func() {
if !setupComplete {
_ = p.Close()
}
}()
raw, err := p.Open(context.Background(), "v1")
if err != nil {
t.Fatal(err)
}
if _, err := p.RecoverVolume(context.Background(), "v1"); err != nil {
t.Fatal(err)
}
backend := raw.(*durable.StorageBackend)
setupComplete = true
return p, backend
}
func TestQD1BackendSyncCrashWriter(t *testing.T) {
impl := durable.ImplName(os.Getenv("QD1_CRASH_IMPL"))
if impl == "" {
t.Skip("subprocess only")
}
p, b := qd1CrashProvider(t, impl, os.Getenv("QD1_CRASH_ROOT"))
_ = p // Deliberately no Close: the parent reopens after abrupt process exit.
before := b.WriteProfile().BackendSyncOps
for i := 0; i < 64; i++ {
data := bytes.Repeat([]byte{byte(i + 1)}, 4096)
if _, err := b.Write(context.Background(), int64(i)*4096, data); err != nil {
t.Fatal(err)
}
for j := 0; j < 2; j++ {
if err := b.Sync(context.Background()); err != nil {
t.Fatal(err)
}
}
}
if n := b.WriteProfile().BackendSyncOps - before; n != 128 {
t.Fatalf("Sync calls=%d", n)
}
fmt.Printf("QD1_CRASH_READY impl=%s Syncs=128 blocks=64 no_Close=true\n", impl)
os.Exit(0)
}
func TestQD1BackendSyncCrashReopen(t *testing.T) {
for _, impl := range []durable.ImplName{durable.ImplSmartWAL, durable.ImplWALStoreChunk} {
t.Run(string(impl), func(t *testing.T) {
root := t.TempDir()
childCtx, cancelChild := context.WithTimeout(context.Background(), 30*time.Second)
defer cancelChild()
cmd := exec.CommandContext(childCtx, os.Args[0], "-test.run=^TestQD1BackendSyncCrashWriter$", "-test.v")
cmd.WaitDelay = 2 * time.Second
cmd.Env = append(os.Environ(), "QD1_CRASH_IMPL="+string(impl), "QD1_CRASH_ROOT="+root)
out, err := cmd.CombinedOutput()
t.Logf("%s", out)
if err != nil {
t.Fatal(err)
}
marker := fmt.Sprintf("QD1_CRASH_READY impl=%s Syncs=128 blocks=64 no_Close=true", impl)
if !bytes.Contains(out, []byte(marker)) {
t.Fatal("child did not reach acknowledged cut")
}
p, b := qd1CrashProvider(t, impl, root)
defer p.Close()
for i := 0; i < 64; i++ {
got := make([]byte, 4096)
if _, err := b.Read(context.Background(), int64(i)*4096, got); err != nil {
t.Fatal(err)
}
if !bytes.Equal(got, bytes.Repeat([]byte{byte(i + 1)}, 4096)) {
t.Fatalf("acknowledged block %d lost after abrupt exit", i)
}
}
})
}
}
@@ -86,6 +86,12 @@ func TestReplicaApplyFailure_PrimaryDegradesRecoversAndReplaysFailedLSN(t *testi
var replica *transientApplyFailStore
factory := func(t *testing.T, dir, label string, blocks uint32, blockSize int) (storage.LogicalStorage, func()) {
st, cleanup := Walstore(t, dir, label, blocks, blockSize)
if label == "primary" {
// This control requires WAL replay of the failed LSN. A primary
// checkpoint may otherwise retire the WAL before recovery starts,
// legitimately selecting BASE rebuild rather than ApplyEntry replay.
st.(*storage.WALStore).DisableAutoFlushForRecoveryTest()
}
if label == "replica-0" {
replica = &transientApplyFailStore{LogicalStorage: st}
return replica, cleanup
@@ -143,6 +149,9 @@ func TestReplicaApplyFailure_PrimaryDegradesRecoversAndReplaysFailedLSN(t *testi
}
t.Logf("injected failure at LSN %d; peer degraded; replica frontier before recovery H=%d; primary head %d", failedLSN, rH, head)
if _, retained, _ := c.primary.Store.Boundaries(); retained > failedLSN {
t.Fatalf("WAL replay fixture retired failed LSN %d (retained=%d)", failedLSN, retained)
}
cfg := replication.ProbeLoopConfig{Interval: 30 * time.Millisecond, MaxConcurrent: 1, CooldownBase: 20 * time.Millisecond, CooldownCap: 200 * time.Millisecond}
if err := c.primary.RepVol.ConfigureProbeLoop(cfg, volume.ProductionProbeFn(registry.AdapterFor), time.Now); err != nil {
t.Fatalf("ConfigureProbeLoop: %v", err)
@@ -2,6 +2,7 @@ package storage
import (
"errors"
"sync"
"sync/atomic"
"testing"
"time"
@@ -42,12 +43,16 @@ func TestDurabilityLatencyCountsSharedPhysicalSyncAndDedup(t *testing.T) {
func TestDurabilityLatencyGroupWaitIsPerRequest(t *testing.T) {
var calls atomic.Uint64
gc := NewGroupCommitter(GroupCommitterConfig{MaxBatch: 2, MaxDelay: time.Second, SyncFunc: func() error { calls.Add(1); return nil }})
go gc.Run()
defer gc.Stop()
var runner sync.Once
startRunner := func() { runner.Do(func() { go gc.Run() }) }
// Failure in prequeue admission must still start a consumer and drain callers.
t.Cleanup(func() { startRunner(); gc.Stop() })
result := make(chan error, 2)
for i := 0; i < 2; i++ {
go func() { result <- gc.SyncCache() }()
}
waitCommitPending(t, gc, 2)
startRunner()
for i := 0; i < 2; i++ {
select {
case err := <-result:
+8 -1
View File
@@ -68,6 +68,7 @@ func NewGroupCommitter(cfg GroupCommitterConfig) *GroupCommitter {
// run drives the batching loop. Call this once in a goroutine.
func (gc *GroupCommitter) Run() {
defer close(gc.done)
var lastSyncCompleted time.Time
for {
select {
case <-gc.stopCh:
@@ -82,8 +83,13 @@ func (gc *GroupCommitter) Run() {
for {
gc.mu.Lock()
n := len(gc.pending)
// Requests already waiting when the previous sync completed have
// had an I/O interval to accumulate; do not delay that batch again.
followup := n > 0 && !lastSyncCompleted.IsZero() && gc.pending[0].queued.Before(lastSyncCompleted)
gc.mu.Unlock()
if n >= gc.maxBatch {
// A lone caller has nobody to batch with. Followers arriving during
// this physical sync remain queued for the next batch.
if n == 1 || followup || n >= gc.maxBatch {
break
}
select {
@@ -113,6 +119,7 @@ func (gc *GroupCommitter) Run() {
gc.waitLatency.Observe(started.Sub(w.queued))
}
err := gc.fsyncSafe()
lastSyncCompleted = time.Now()
gc.syncCount.Add(1)
for _, ch := range batch {
ch.done <- err
@@ -0,0 +1,172 @@
package storage
import (
"bytes"
"errors"
"os"
"path/filepath"
"runtime"
"sync/atomic"
"testing"
"time"
)
func TestGroupCommitSingletonStartsWithoutCollectionDelay(t *testing.T) {
started := make(chan struct{}, 1)
gc := NewGroupCommitter(GroupCommitterConfig{MaxDelay: 5 * time.Second, SyncFunc: func() error { started <- struct{}{}; return nil }})
go gc.Run()
defer gc.Stop()
result := make(chan error, 1)
go func() { result <- gc.SyncCache() }()
select {
case <-started:
case <-time.After(250 * time.Millisecond):
t.Fatal("singleton waited for collection timer before physical sync")
}
if err := receiveCommitResult(t, result, time.After(2*time.Second)); err != nil {
t.Fatal(err)
}
}
func waitCommitPending(t *testing.T, gc *GroupCommitter, want int) {
t.Helper()
deadline := time.Now().Add(2 * time.Second)
for time.Now().Before(deadline) {
gc.mu.Lock()
n := len(gc.pending)
gc.mu.Unlock()
if n == want {
return
}
runtime.Gosched()
}
t.Fatalf("pending queue did not reach %d", want)
}
func TestGroupCommitSingletonFollowersRequireNextPhysicalSync(t *testing.T) {
firstStarted, secondStarted := make(chan struct{}), make(chan struct{})
releaseFirst, releaseSecond := make(chan struct{}), make(chan struct{})
failed := errors.New("second physical sync failed")
var calls atomic.Int32
gc := NewGroupCommitter(GroupCommitterConfig{MaxDelay: 5 * time.Second, SyncFunc: func() error {
switch calls.Add(1) {
case 1:
close(firstStarted)
<-releaseFirst
return nil
case 2:
close(secondStarted)
<-releaseSecond
return failed
default:
return errors.New("unexpected physical sync")
}
}})
go gc.Run()
defer gc.Stop()
defer func() {
select {
case <-releaseSecond:
default:
close(releaseSecond)
}
select {
case <-releaseFirst:
default:
close(releaseFirst)
}
}()
leader := make(chan error, 1)
go func() { leader <- gc.SyncCache() }()
select {
case <-firstStarted:
case <-time.After(time.Second):
t.Fatal("leader did not start")
}
followers := make(chan error, 8)
for i := 0; i < 8; i++ {
go func() { followers <- gc.SyncCache() }()
}
waitCommitPending(t, gc, 8)
select {
case err := <-followers:
t.Fatal("ack before physical sync", err)
default:
}
close(releaseFirst)
if err := receiveCommitResult(t, leader, time.After(2*time.Second)); err != nil {
t.Fatal(err)
}
select {
case <-secondStarted:
case <-time.After(time.Second):
t.Fatal("follower batch did not start")
}
select {
case err := <-followers:
t.Fatal("followers used preceding sync", err)
default:
}
close(releaseSecond)
completionDeadline := time.NewTimer(2 * time.Second)
defer completionDeadline.Stop()
for i := 0; i < 8; i++ {
if err := receiveCommitResult(t, followers, completionDeadline.C); !errors.Is(err, failed) {
t.Fatal("physical error not propagated", err)
}
}
if calls.Load() != 2 {
t.Fatalf("physical syncs=%d", calls.Load())
}
}
func TestGroupCommitQD1EveryAckFollowsPhysicalSync(t *testing.T) {
path := filepath.Join(t.TempDir(), "wal")
f, err := os.Create(path)
if err != nil {
t.Fatal(err)
}
defer f.Close()
var syncs atomic.Int32
gc := NewGroupCommitter(GroupCommitterConfig{SyncFunc: func() error {
if err := f.Sync(); err != nil {
return err
}
syncs.Add(1)
return nil
}})
go gc.Run()
defer gc.Stop()
want := make([]byte, 32*4096)
for i := 0; i < 32; i++ {
block := bytes.Repeat([]byte{byte(i + 1)}, 4096)
copy(want[i*4096:], block)
if _, err := f.WriteAt(block, int64(i*4096)); err != nil {
t.Fatal(err)
}
if err := gc.SyncCache(); err != nil {
t.Fatal(err)
}
if n := syncs.Load(); n != int32(i+1) {
t.Fatalf("ack without physical fsync: request=%d syncs=%d", i+1, n)
}
}
if err := f.Close(); err != nil {
t.Fatal(err)
}
got, err := os.ReadFile(path)
if err != nil || !bytes.Equal(got, want) {
t.Fatal("fsynced bytes differ on reopen", err)
}
}
func receiveCommitResult(t *testing.T, result <-chan error, deadline <-chan time.Time) error {
t.Helper()
select {
case err := <-result:
return err
case <-deadline:
t.Fatal("physical sync started but completion did not settle within deadline")
return nil
}
}
@@ -0,0 +1,162 @@
package storage
import (
"fmt"
"sync"
"sync/atomic"
"testing"
"time"
)
// Control the legal scheduler order between a completed physical callback and
// its caller publishing/reading the global stable frontier in Sync.
func TestWALGenerationFirstCallerReturnOrdering(t *testing.T) {
for _, laterPublishesFirst := range []bool{false, true} {
t.Run(fmt.Sprintf("later_publishes_first=%v", laterPublishesFirst), func(t *testing.T) {
s := newGenerationStore(t)
firstEntered, secondEntered, firstCacheReturned := make(chan struct{}), make(chan struct{}), make(chan struct{})
releaseFirst, releaseSecond, publishFirst := make(chan struct{}), make(chan struct{}), make(chan struct{})
var workers sync.WaitGroup
closeOnce := func(ch chan struct{}) {
select {
case <-ch:
default:
close(ch)
}
}
t.Cleanup(func() {
closeOnce(releaseFirst)
closeOnce(releaseSecond)
closeOnce(publishFirst)
done := make(chan struct{})
go func() { workers.Wait(); close(done) }()
select {
case <-done:
case <-time.After(2 * time.Second):
t.Error("Sync callers did not settle during cleanup")
}
})
realSync := s.syncWALFile
var attempts, completed atomic.Int32
s.syncWALFile = func() error {
n := attempts.Add(1)
switch n {
case 1:
close(firstEntered)
<-releaseFirst
case 2:
close(secondEntered)
<-releaseSecond
default:
return fmt.Errorf("unexpected physical sync %d", n)
}
err := realSync()
if err == nil {
completed.Store(n)
}
return err
}
realCache := s.syncCache
var calls atomic.Int32
s.syncCache = func() error {
n := calls.Add(1)
err := realCache()
if n == 1 {
close(firstCacheReturned)
<-publishFirst
}
return err
}
type result struct {
frontier uint64
err error
}
leader, followers := make(chan result, 1), make(chan result, 1)
start := func(out chan<- result) {
workers.Add(1)
go func() { defer workers.Done(); n, err := s.Sync(); out <- result{n, err} }()
}
await := func(ch <-chan struct{}, label string) {
t.Helper()
select {
case <-ch:
case <-time.After(2 * time.Second):
t.Fatal("missing", label)
}
}
receive := func(ch <-chan result) result {
t.Helper()
select {
case r := <-ch:
if r.err != nil {
t.Fatal(r.err)
}
return r
case <-time.After(2 * time.Second):
t.Fatal("Sync result did not settle")
return result{}
}
}
if _, err := s.Write(0, makeBlock(4096, 0x31)); err != nil {
t.Fatal(err)
}
start(leader)
await(firstEntered, "first physical callback")
closeOnce(releaseFirst)
await(firstCacheReturned, "first caller after physical completion")
// This write occurs AFTER the first real fsync completed, so only
// the later physical fsync can make it durable.
if _, err := s.Write(1, makeBlock(4096, 0x42)); err != nil {
t.Fatal(err)
}
start(followers)
await(secondEntered, "second physical callback")
if completed.Load() != 1 {
t.Fatalf("second sync completed while held: %d", completed.Load())
}
select {
case r := <-followers:
t.Fatalf("follower ack before second fsync: %+v", r)
default:
}
if laterPublishesFirst {
closeOnce(releaseSecond)
for i := 0; i < 1; i++ {
if r := receive(followers); r.frontier != 2 {
t.Fatal("follower frontier", r)
}
}
if completed.Load() != 2 {
t.Fatal("later frontier has no second completed physical sync")
}
closeOnce(publishFirst)
} else {
closeOnce(publishFirst)
}
first := receive(leader)
// Sync returns the current global stable frontier, not its own cut.
// A later return may include a newer independently completed fsync.
wantFirst := uint64(1)
if laterPublishesFirst {
wantFirst = 2
}
if first.frontier != wantFirst {
t.Fatalf("first batch frontier=%d want %d (completed physical syncs=%d laterPublishesFirst=%v)", first.frontier, wantFirst, completed.Load(), laterPublishesFirst)
}
if !laterPublishesFirst {
if completed.Load() != 1 {
t.Fatal("held second fsync unexpectedly completed")
}
closeOnce(releaseSecond)
for i := 0; i < 1; i++ {
if r := receive(followers); r.frontier != 2 {
t.Fatal("follower frontier", r)
}
}
}
if completed.Load() != 2 || s.WALSyncCount() != 2 {
t.Fatalf("physical counts completed=%d attempts=%d", completed.Load(), s.WALSyncCount())
}
})
}
}
@@ -56,7 +56,7 @@ func TestWALGenerationSyncFollowersAndNewWrite(t *testing.T) {
// Release before store close even if an assertion fails.
defer close(release)
realSync := s.syncWALFile
var attempts atomic.Int32
var attempts, completed atomic.Int32
s.syncWALFile = func() error {
s.committer.mu.Lock()
s.committer.mu.Unlock()
@@ -64,7 +64,11 @@ func TestWALGenerationSyncFollowersAndNewWrite(t *testing.T) {
close(entered)
<-release
}
return realSync()
err := realSync()
if err == nil {
completed.Add(1)
}
return err
}
results := make(chan uint64, 9)
firstResult := make(chan uint64, 1)
@@ -87,8 +91,12 @@ func TestWALGenerationSyncFollowersAndNewWrite(t *testing.T) {
waitGenerationPending(t, s, 8)
release <- struct{}{}
first := generationResult(t, firstResult)
if first != 1 {
t.Fatalf("first batch frontier=%d want 1", first)
// Sync returns the global stable frontier at publication. Its
// caller may resume after the next batch has already fsynced and
// published 2. Accept that widening only with independent physical
// completion evidence; never acknowledge an unflushed new write.
if first != 1 && !(newWrite && first == 2 && completed.Load() >= 2) {
t.Fatalf("first caller frontier=%d, newWrite=%v completed fsyncs=%d", first, newWrite, completed.Load())
}
for i := 0; i < 8; i++ {
n := generationResult(t, results)