From 16f22e903a1bbe9737b0368ba64957f9b5da0aa1 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 15 Nov 2026 15:46:11 -0800 Subject: [PATCH 1/3] test: make Pillar3 SameLBAArbitration deterministic with a pre-barrier hold TestPillar3Slice2_EngineDriven_SameLBAArbitration was flaky (on main baca5fd, -race -count=40: 25/40 failures at -cpu 1, 6/40 at -cpu 2, 1/40 at -cpu 4). Root cause is a timing assumption in the test, not a product race: with a 12-LBA backlog, base copy and DrainBacklog finish in microseconds and Sender.Run seals the recovery cut (SealBeforeBarrier) before the test pushes its same-LBA overwrites. PushLiveWrite then returns ErrSinkBarrierSealed, the documented 'retain the WAL entry for replay' outcome that production FeedLiveWrite maps to LiveWriteRetained, and the test treated it as fatal. Once in a while the whole session also finished inside waitBridgeLiveReady's 1 ms poll gap. Tolerating the error would defeat the test (the overwrites would never ship in-session, so convergence could not be checked), and a larger backlog would only shift the timing. Instead add a test-only hook, PrimaryBridge.SetPreBarrierHook: each sender runs it after base + backlog drain and before SealBeforeBarrier. The test installs it before the probe that starts the rebuild, waits until the sender reaches it (session live, cut not made), pushes the overwrites, releases, and asserts convergence. With no hook installed the sender path is unchanged. The now-unused waitBridgeLiveReady helper in this package is removed. Co-Authored-By: Claude Opus 5.5 --- .../core/recovery/integration_stub.go | 16 ++++++ seaweed-block/core/recovery/sender.go | 8 +++ .../component/dual_lane_engine_test.go | 49 +++++++++++-------- 3 files changed, 52 insertions(+), 21 deletions(-) diff --git a/seaweed-block/core/recovery/integration_stub.go b/seaweed-block/core/recovery/integration_stub.go index af7734d511..795590539c 100644 --- a/seaweed-block/core/recovery/integration_stub.go +++ b/seaweed-block/core/recovery/integration_stub.go @@ -70,6 +70,8 @@ type PrimaryBridge struct { onClose SessionCloseCallback onAck BridgeDurableAckCallback + preBarrierHook func(ReplicaID) // tests only; see SetPreBarrierHook + mu sync.Mutex senders map[ReplicaID]*Sender cancels map[ReplicaID]context.CancelFunc @@ -131,6 +133,17 @@ func (b *PrimaryBridge) SetOnDurableAck(fn BridgeDurableAckCallback) { b.onAck = fn } +// SetPreBarrierHook installs a test-only hook that every sender started +// after this call runs once its base copy and backlog drain are done and +// before it seals the recovery cut (SealBeforeBarrier). While the hook +// blocks, the session is live-ready and live writes ship in-session, so a +// test can place writes in that window deterministically. nil clears it. +func (b *PrimaryBridge) SetPreBarrierHook(fn func(ReplicaID)) { + b.mu.Lock() + defer b.mu.Unlock() + b.preBarrierHook = fn +} + // StartRebuildSession is shaped like CommandExecutor.StartRebuild: // non-blocking, returns immediately after spawning the session // goroutine. After P2c-slice B-2 the session terminates on its own @@ -222,6 +235,9 @@ func (b *PrimaryBridge) startRebuildSessionLocked(ctx context.Context, conn net. sender = NewSenderWithSink(b.store, b.coord, conn, replicaID, sink) } sender.epoch = epoch + if hook := b.preBarrierHook; hook != nil { + sender.preBarrierHook = func() { hook(replicaID) } + } sender.SetOnDurableAck(func(rid ReplicaID, sid, acknowledgedLSN, primaryS, primaryH uint64) { b.mu.Lock() cb := b.onAck diff --git a/seaweed-block/core/recovery/sender.go b/seaweed-block/core/recovery/sender.go index 431df16172..3e7939c76a 100644 --- a/seaweed-block/core/recovery/sender.go +++ b/seaweed-block/core/recovery/sender.go @@ -119,6 +119,11 @@ type Sender struct { liveReady atomic.Bool onDurableAck DurableAckCallback + + // preBarrierHook, when set (tests only, via PrimaryBridge.SetPreBarrierHook), + // runs after base + backlog drain complete and before SealBeforeBarrier: + // the session is live-ready and the recovery cut is not yet made. + preBarrierHook func() } // ackOrResult is the channel payload from the reader goroutine to @@ -563,6 +568,9 @@ func (s *Sender) Run(ctx context.Context, sessionID, fromLSN, frontierHint uint6 return 0, wErr } + if s.preBarrierHook != nil { + s.preBarrierHook() + } if sealer, ok := s.sink.(preBarrierSealer); ok { if err := sealer.SealBeforeBarrier(); err != nil { return 0, err diff --git a/seaweed-block/core/replication/component/dual_lane_engine_test.go b/seaweed-block/core/replication/component/dual_lane_engine_test.go index a48a22824e..244f931c6a 100644 --- a/seaweed-block/core/replication/component/dual_lane_engine_test.go +++ b/seaweed-block/core/replication/component/dual_lane_engine_test.go @@ -3,6 +3,7 @@ package component_test import ( "bytes" "errors" + "sync" "testing" "time" @@ -463,6 +464,25 @@ func TestPillar3Slice2_EngineDriven_SameLBAArbitration(t *testing.T) { CtrlAddr: c.Replica(0).Addr, }) + br, coordRID, ok := c.BlockExecutor(0).DualLanePrimaryBridge() + if !ok || br == nil { + t.Fatal("BlockExecutor missing dual-lane PrimaryBridge") + } + // Hold the sender at its pre-barrier point: base copy and backlog + // drain done, recovery cut not yet sealed, session live. With a + // 12-LBA backlog that window is microseconds wide, so without the + // hold the overwrites below raced the cut and got the documented + // ErrSinkBarrierSealed ("retain for replay") instead of shipping + // in-session. Installed before the probe that starts the rebuild. + reached, release := make(chan struct{}), make(chan struct{}) + var reachedOnce sync.Once + br.SetPreBarrierHook(func(recovery.ReplicaID) { + reachedOnce.Do(func() { close(reached) }) + <-release + }) + releaseHold := sync.OnceFunc(func() { close(release) }) + t.Cleanup(releaseHold) + c.DriveProbeResult(0, adapter.ProbeResult{ ReplicaID: "replica-0", Success: true, @@ -473,14 +493,14 @@ func TestPillar3Slice2_EngineDriven_SameLBAArbitration(t *testing.T) { PrimaryHeadLSN: seedN, }) - // Wait for engine to emit StartRebuild AND for the bridge to be - // reachable (DualLanePrimaryBridge returns once the executor has - // the dual-lane config). - br, coordRID, ok := c.BlockExecutor(0).DualLanePrimaryBridge() - if !ok || br == nil { - t.Fatal("BlockExecutor missing dual-lane PrimaryBridge") + select { + case <-reached: + case <-time.After(8 * time.Second): + t.Fatalf("sender never reached the pre-barrier point; cmd=%v trace=%v", a.CommandLog(), a.Trace()) + } + if !br.HasActiveSession(coordRID) { + t.Fatal("session not live-ready at the pre-barrier hold") } - waitBridgeLiveReady(t, br, coordRID) // Live-overwrite the SAME LBAs as the backlog. Each Write goes // onto primary's WAL with a fresh LSN > seedN; PushLiveWrite @@ -504,6 +524,7 @@ func TestPillar3Slice2_EngineDriven_SameLBAArbitration(t *testing.T) { } bRefs[lba] = data } + releaseHold() // the overwrites shipped in-session; let the sender seal and barrier // Wait for engine's command loop to close: StartRebuild emitted // AND SessionClosedCompleted observed in the adapter's Trace. @@ -597,20 +618,6 @@ func bridgeLiveReadyOrClosed(bridge interface { return false } -func waitBridgeLiveReady(t *testing.T, bridge interface { - HasActiveSession(recovery.ReplicaID) bool -}, replicaID recovery.ReplicaID) { - t.Helper() - deadline := time.Now().Add(2 * time.Second) - for time.Now().Before(deadline) { - if bridge.HasActiveSession(replicaID) { - return - } - time.Sleep(time.Millisecond) - } - t.Fatalf("bridge session for %s did not become live-ready", replicaID) -} - func traceIndex(trace []engine.TraceEntry, start int, step, detail string) int { if start < 0 { return -1 From 02fb0914b4f417af221d6abfa52affae88e46ad6 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 15 Nov 2026 15:57:37 -0800 Subject: [PATCH 2/3] test: Pillar3 SameLBAArbitration holds a stale BASE frame instead of a pre-barrier hook Review follow-up. The pre-barrier hold proved in-session delivery and convergence but no longer the test's point: a newer WAL write for an LBA must win over an OLDER base frame for that LBA that arrives later. Drop the production SetPreBarrierHook seam (core/recovery is back to main) and hold the base lane instead, through the existing WithPrimaryStorageWrap: staleBaseHold captures the base read of LBA 5 (old value A) and holds it; the test pushes the same-LBA overwrites (the session cannot seal its recovery cut while base is held, so they ship in-session: this is also what fixes the flake), waits until the replica holds B at LBA 5, then releases the stale A frame. Convergence requires LBA 5 == B: RebuildSession.ApplyBaseBlock must skip a base frame for an LBA the WAL lane already applied (bitmap). Co-Authored-By: Claude Opus 5.5 --- .../core/recovery/integration_stub.go | 16 ---- seaweed-block/core/recovery/sender.go | 8 -- .../component/dual_lane_engine_test.go | 88 ++++++++++++++----- 3 files changed, 66 insertions(+), 46 deletions(-) diff --git a/seaweed-block/core/recovery/integration_stub.go b/seaweed-block/core/recovery/integration_stub.go index 795590539c..af7734d511 100644 --- a/seaweed-block/core/recovery/integration_stub.go +++ b/seaweed-block/core/recovery/integration_stub.go @@ -70,8 +70,6 @@ type PrimaryBridge struct { onClose SessionCloseCallback onAck BridgeDurableAckCallback - preBarrierHook func(ReplicaID) // tests only; see SetPreBarrierHook - mu sync.Mutex senders map[ReplicaID]*Sender cancels map[ReplicaID]context.CancelFunc @@ -133,17 +131,6 @@ func (b *PrimaryBridge) SetOnDurableAck(fn BridgeDurableAckCallback) { b.onAck = fn } -// SetPreBarrierHook installs a test-only hook that every sender started -// after this call runs once its base copy and backlog drain are done and -// before it seals the recovery cut (SealBeforeBarrier). While the hook -// blocks, the session is live-ready and live writes ship in-session, so a -// test can place writes in that window deterministically. nil clears it. -func (b *PrimaryBridge) SetPreBarrierHook(fn func(ReplicaID)) { - b.mu.Lock() - defer b.mu.Unlock() - b.preBarrierHook = fn -} - // StartRebuildSession is shaped like CommandExecutor.StartRebuild: // non-blocking, returns immediately after spawning the session // goroutine. After P2c-slice B-2 the session terminates on its own @@ -235,9 +222,6 @@ func (b *PrimaryBridge) startRebuildSessionLocked(ctx context.Context, conn net. sender = NewSenderWithSink(b.store, b.coord, conn, replicaID, sink) } sender.epoch = epoch - if hook := b.preBarrierHook; hook != nil { - sender.preBarrierHook = func() { hook(replicaID) } - } sender.SetOnDurableAck(func(rid ReplicaID, sid, acknowledgedLSN, primaryS, primaryH uint64) { b.mu.Lock() cb := b.onAck diff --git a/seaweed-block/core/recovery/sender.go b/seaweed-block/core/recovery/sender.go index 3e7939c76a..431df16172 100644 --- a/seaweed-block/core/recovery/sender.go +++ b/seaweed-block/core/recovery/sender.go @@ -119,11 +119,6 @@ type Sender struct { liveReady atomic.Bool onDurableAck DurableAckCallback - - // preBarrierHook, when set (tests only, via PrimaryBridge.SetPreBarrierHook), - // runs after base + backlog drain complete and before SealBeforeBarrier: - // the session is live-ready and the recovery cut is not yet made. - preBarrierHook func() } // ackOrResult is the channel payload from the reader goroutine to @@ -568,9 +563,6 @@ func (s *Sender) Run(ctx context.Context, sessionID, fromLSN, frontierHint uint6 return 0, wErr } - if s.preBarrierHook != nil { - s.preBarrierHook() - } if sealer, ok := s.sink.(preBarrierSealer); ok { if err := sealer.SealBeforeBarrier(); err != nil { return 0, err diff --git a/seaweed-block/core/replication/component/dual_lane_engine_test.go b/seaweed-block/core/replication/component/dual_lane_engine_test.go index 244f931c6a..fbc559b192 100644 --- a/seaweed-block/core/replication/component/dual_lane_engine_test.go +++ b/seaweed-block/core/replication/component/dual_lane_engine_test.go @@ -4,6 +4,7 @@ import ( "bytes" "errors" "sync" + "sync/atomic" "testing" "time" @@ -11,6 +12,7 @@ import ( "github.com/seaweedfs/seaweed-block/core/engine" "github.com/seaweedfs/seaweed-block/core/recovery" "github.com/seaweedfs/seaweed-block/core/replication/component" + "github.com/seaweedfs/seaweed-block/core/storage" "github.com/seaweedfs/seaweed-block/core/transport" ) @@ -442,14 +444,28 @@ func TestDualLane_EngineDrivenRebuild_WithPushLiveDuringSession(t *testing.T) { // / 9f62ebe / 291e652 / 3495a12. func TestPillar3Slice2_EngineDriven_SameLBAArbitration(t *testing.T) { component.RunSubstrate(t, "memorywal", component.MemoryWAL, func(t *testing.T, c *component.Cluster) { + const seedN = 12 + overwriteLBAs := []uint32{3, 5, 7} + // The discriminating LBA: its BASE frame is read with the old value + // A, held, and released only after the newer WAL write B for the + // same LBA has been applied on the replica. Arbitration must keep B. + // Holding the base lane also keeps the session from sealing its + // recovery cut (it seals only after base completes), so the + // overwrites ship in-session instead of racing the cut, which made + // this test flaky when a 12-LBA rebuild finished first. + hold := &staleBaseHold{lba: 5, captured: make(chan struct{}), release: make(chan struct{})} + releaseHold := sync.OnceFunc(func() { close(hold.release) }) + t.Cleanup(releaseHold) + c.WithReplicas(1). WithEngineDrivenRecovery(). WithDualLaneRecovery(). + WithPrimaryStorageWrap(func(inner storage.LogicalStorage) storage.LogicalStorage { + hold.LogicalStorage = inner + return hold + }). Start() - const seedN = 12 - overwriteLBAs := []uint32{3, 5, 7} - c.PrimaryWriteN(seedN) c.PrimarySync() @@ -468,20 +484,7 @@ func TestPillar3Slice2_EngineDriven_SameLBAArbitration(t *testing.T) { if !ok || br == nil { t.Fatal("BlockExecutor missing dual-lane PrimaryBridge") } - // Hold the sender at its pre-barrier point: base copy and backlog - // drain done, recovery cut not yet sealed, session live. With a - // 12-LBA backlog that window is microseconds wide, so without the - // hold the overwrites below raced the cut and got the documented - // ErrSinkBarrierSealed ("retain for replay") instead of shipping - // in-session. Installed before the probe that starts the rebuild. - reached, release := make(chan struct{}), make(chan struct{}) - var reachedOnce sync.Once - br.SetPreBarrierHook(func(recovery.ReplicaID) { - reachedOnce.Do(func() { close(reached) }) - <-release - }) - releaseHold := sync.OnceFunc(func() { close(release) }) - t.Cleanup(releaseHold) + hold.armed.Store(true) // only the rebuild's base read of LBA 5 is held c.DriveProbeResult(0, adapter.ProbeResult{ ReplicaID: "replica-0", @@ -494,12 +497,15 @@ func TestPillar3Slice2_EngineDriven_SameLBAArbitration(t *testing.T) { }) select { - case <-reached: + case <-hold.captured: case <-time.After(8 * time.Second): - t.Fatalf("sender never reached the pre-barrier point; cmd=%v trace=%v", a.CommandLog(), a.Trace()) + t.Fatalf("base lane never read lba %d; cmd=%v trace=%v", hold.lba, a.CommandLog(), a.Trace()) } - if !br.HasActiveSession(coordRID) { - t.Fatal("session not live-ready at the pre-barrier hold") + // The session cannot seal while the base lane is held, so waiting + // for live-ready here is bounded by the session's own progress, + // not by a race with its completion. + if !bridgeLiveReadyOrClosed(br, coordRID) { + t.Fatal("session never became live-ready while its base lane was held") } // Live-overwrite the SAME LBAs as the backlog. Each Write goes @@ -524,7 +530,20 @@ func TestPillar3Slice2_EngineDriven_SameLBAArbitration(t *testing.T) { } bRefs[lba] = data } - releaseHold() // the overwrites shipped in-session; let the sender seal and barrier + // The newer WAL value must be on the replica BEFORE the stale base + // frame is released, so the release below delivers an older BASE + // frame after a newer WAL write for the same LBA. + deadlineB := time.Now().Add(5 * time.Second) + for { + if rd, err := c.Replica(0).Store.Read(hold.lba); err == nil && bytes.Equal(rd, bRefs[hold.lba]) { + break + } + if time.Now().After(deadlineB) { + t.Fatalf("WAL write for lba %d did not reach the replica while its base frame was held", hold.lba) + } + time.Sleep(5 * time.Millisecond) + } + releaseHold() // deliver the stale BASE frame (old value A) for lba 5 // Wait for engine's command loop to close: StartRebuild emitted // AND SessionClosedCompleted observed in the adapter's Trace. @@ -593,6 +612,31 @@ func TestPillar3Slice2_EngineDriven_SameLBAArbitration(t *testing.T) { }) } +// staleBaseHold wraps the primary store and, once armed, holds the FIRST +// Read of one LBA after capturing its bytes: the base frame built from that +// Read carries the value as of the read and reaches the replica only after +// release. Other reads pass through. +type staleBaseHold struct { + storage.LogicalStorage + lba uint32 + armed atomic.Bool + once sync.Once + captured chan struct{} + release chan struct{} +} + +func (s *staleBaseHold) Read(lba uint32) ([]byte, error) { + data, err := s.LogicalStorage.Read(lba) + if lba == s.lba && s.armed.Load() { + data = append([]byte(nil), data...) // the captured (soon stale) bytes + s.once.Do(func() { + close(s.captured) + <-s.release + }) + } + return data, err +} + // pushRaceOutcome reports the PushLiveWrite errors that the production // caller (transport ship_sender) does not treat as failures. func pushRaceOutcome(err error) bool { From 78f56c31d82d97255611442faa679fda7fc7de9a Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 15 Nov 2026 16:07:23 -0800 Subject: [PATCH 3/3] test: release the stale-BASE hold with a defer, before executor shutdown Review follow-up: the release was a t.Cleanup registered before Start, and cleanups run LIFO, so the executor shutdown Start registers ran first; a t.Fatal while the base frame was held would deadlock StopAndWait. A defer inside the scenario runs before every t.Cleanup, including on t.Fatal. Co-Authored-By: Claude Opus 5.5 --- .../core/replication/component/dual_lane_engine_test.go | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/seaweed-block/core/replication/component/dual_lane_engine_test.go b/seaweed-block/core/replication/component/dual_lane_engine_test.go index fbc559b192..e108032dc7 100644 --- a/seaweed-block/core/replication/component/dual_lane_engine_test.go +++ b/seaweed-block/core/replication/component/dual_lane_engine_test.go @@ -455,7 +455,10 @@ func TestPillar3Slice2_EngineDriven_SameLBAArbitration(t *testing.T) { // this test flaky when a 12-LBA rebuild finished first. hold := &staleBaseHold{lba: 5, captured: make(chan struct{}), release: make(chan struct{})} releaseHold := sync.OnceFunc(func() { close(hold.release) }) - t.Cleanup(releaseHold) + // A defer, not t.Cleanup: defers run before every t.Cleanup (LIFO), + // including the executor shutdown that Start registers, so a t.Fatal + // while the base frame is held cannot deadlock that shutdown. + defer releaseHold() c.WithReplicas(1). WithEngineDrivenRecovery().