fix, replication: share the frame writer and guard every raw exchange reference

This commit is contained in:
pingqiu committed 2026-11-28 12:46:05 -08:00
1 parent f8b059a11f
commit cc5941598a
5 files changed
+128 -15

No files matched your search

@@ -11,7 +11,18 @@ import (
)
func TestSaturatedPeerQueueStillOwnsTheHealingExchange(t *testing.T) {
testSaturatedPeerQueueHealing(t, false)
}
func TestSaturatedPeerQueueFailureCleanupUnblocksTheWorker(t *testing.T) {
testSaturatedPeerQueueHealing(t, true)
}
func testSaturatedPeerQueueHealing(t *testing.T, cleanupEarly bool) {
t.Helper()
started, release := make(chan struct{}), make(chan struct{})
var releaseOnce sync.Once
unblock := func() { releaseOnce.Do(func() { close(release) }) }
q := newPeerWorkQueueWithOps("r2", 1, peerWorkQueueOps{
ship: func(context.Context, LocalWrite) (bool, error) {
close(started)
@@ -19,19 +30,37 @@ func TestSaturatedPeerQueueStillOwnsTheHealingExchange(t *testing.T) {
return false, nil
},
})
defer q.closeAndWait()
cleanup := func() {
unblock()
done := make(chan struct{})
go func() { q.closeAndWait(); close(done) }()
select {
case <-done:
case <-time.After(time.Second):
t.Error("worker did not join after unconditional release")
}
}
defer cleanup()
results := make(chan peerWorkResult, 2)
if _, err := q.enqueueWrite(LocalWrite{LSN: 1}, results); err != nil {
t.Fatal(err)
}
<-started
select {
case <-started:
case <-time.After(time.Second):
t.Fatal("worker did not start")
}
if cleanupEarly {
cleanup()
return
}
if _, err := q.enqueueWrite(LocalWrite{LSN: 2}, results); err != nil {
t.Fatal(err)
}
if _, err := q.enqueueWrite(LocalWrite{LSN: 3}, results); !errors.Is(err, ErrPeerQueueSaturated) {
t.Fatalf("saturation: %v", err)
}
close(release)
unblock()
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
ack, err := q.exchange(ctx, func(context.Context) (transport.BarrierAck, error) {
@@ -40,8 +69,17 @@ func TestSaturatedPeerQueueStillOwnsTheHealingExchange(t *testing.T) {
if err != nil || ack.AchievedLSN != 7 {
t.Fatalf("healing exchange: ack=%+v err=%v", ack, err)
}
<-results
if r := <-results; !errors.Is(r.err, ErrPeerQueueSaturated) {
readResult := func() peerWorkResult {
select {
case r := <-results:
return r
case <-ctx.Done():
t.Fatal("queue result deadline")
return peerWorkResult{}
}
}
readResult()
if r := readResult(); !errors.Is(r.err, ErrPeerQueueSaturated) {
t.Fatalf("pending steady work escaped terminal gate: %v", r.err)
}
if _, err := q.enqueueWrite(LocalWrite{LSN: 4}, results); !errors.Is(err, ErrPeerQueueSaturated) {
@@ -61,11 +61,11 @@ func sessionExchangeSites(name string, source []byte) ([]string, error) {
}
var rows []string
for _, decl := range f.Decls {
fn, ok := decl.(*ast.FuncDecl)
if !ok {
continue
owner := "<package>"
if fn, ok := decl.(*ast.FuncDecl); ok {
owner = fn.Name.Name
}
ast.Inspect(fn, func(n ast.Node) bool {
ast.Inspect(decl, func(n ast.Node) bool {
sel, ok := n.(*ast.SelectorExpr)
if !ok {
return true
@@ -82,7 +82,7 @@ func sessionExchangeSites(name string, source []byte) ([]string, error) {
tracked = true
}
if tracked {
rows = append(rows, filepath.Base(name)+":"+fn.Name.Name+":"+sel.Sel.Name)
rows = append(rows, filepath.Base(name)+":"+owner+":"+sel.Sel.Name)
}
return true
})
@@ -90,6 +90,18 @@ func sessionExchangeSites(name string, source []byte) ([]string, error) {
return rows, nil
}
func TestPeerSessionOwnerScanFindsAPackageMethodAlias(t *testing.T) {
rows, err := sessionExchangeSites("alias.go", []byte(`package replication
var rawBarrier = (*ReplicaPeer).barrier
func bypass(p *ReplicaPeer) { rawBarrier(p, ctx, 0) }`))
if err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(rows, []string{"alias.go:<package>:barrier"}) {
t.Fatalf("missed package method alias: %v", rows)
}
}
func TestPeerSessionOwnerScanFindsABypass(t *testing.T) {
rows, err := sessionExchangeSites("bypass.go", []byte(`package replication
func bypass(p *ReplicaPeer) { p.executor.Barrier("r2", lineage, 0) }`))
@@ -0,0 +1,52 @@
package transport
import (
"fmt"
"net"
"sync"
"testing"
"github.com/seaweedfs/seaweed-block/core/storage"
)
// No other goroutine uses the write mutex in this fixture, so a successful
// TryLock at the wire boundary proves this request bypassed the shipper owner.
type barrierWriteOwnerConn struct {
net.Conn
owner *sync.Mutex
}
func (c *barrierWriteOwnerConn) Write(p []byte) (int, error) {
if c.owner.TryLock() {
c.owner.Unlock()
return 0, fmt.Errorf("barrier request bypassed the shipper write owner")
}
return c.Conn.Write(p)
}
func TestBarrierRequestUsesTheShippersWriteOwner(t *testing.T) {
_, _, listener := setupPrimaryReplica(t)
e := NewBlockExecutor(storage.NewBlockStore(64, 4096), listener.Addr())
defer e.Stop()
lineage := shipTestLineage()
if err := e.registerShipSessionForTest(lineage); err != nil {
t.Fatal(err)
}
conn, err := net.Dial("tcp", listener.Addr())
if err != nil {
t.Fatal(err)
}
defer conn.Close()
e.WalShipperFor("r1")
owner := e.WalShipperWriteMu("r1")
guarded := &barrierWriteOwnerConn{Conn: conn, owner: owner}
if err := e.attachConn(e.sessions[lineage.SessionID], guarded); err != nil {
t.Fatal(err)
}
// This is also the steady shipper's emit connection, as FeedLiveWrite
// installs it in production. A timer drain can emit outside the peer queue.
e.updateWalShipperEmitContext("r1", guarded, lineage, EmitProfileSteadyMsgShip)
if _, err := e.Barrier("r1", lineage, 0); err != nil {
t.Fatal(err)
}
}
+10 -1
View File
@@ -573,7 +573,16 @@ func (e *BlockExecutor) Barrier(replicaID string, lineage RecoveryLineage, front
// close it so the next barrier on this session re-dials (a caller that
// does not invalidate the session, such as the store learner, would
// otherwise reuse the dead socket forever).
if err := sendBarrierReq(conn, lineage, recoveryConnTimeout); err != nil {
// FeedLiveWrite installs this session connection as the shipper's
// emitConn. Its timer can write outside the peer worker, so the request
// uses the existing frame writer shared with emit/recovery. The peer
// queue remains the owner of the request/response exchange.
e.WalShipperFor(replicaID)
writeMu := e.WalShipperWriteMu(replicaID)
writeMu.Lock()
sendErr := sendBarrierReq(conn, lineage, recoveryConnTimeout)
writeMu.Unlock()
if err := sendErr; err != nil {
e.detachConn(session, conn)
_ = conn.Close()
return BarrierAck{}, fmt.Errorf("transport: barrier: send replica=%s: %w", replicaID, err)
+6 -4
View File
@@ -263,14 +263,15 @@ The peer queue owns steady-session exchanges, including reconciliation,
promotion seed barriers and durability-coordinator barriers. Only its worker
invokes the raw ship, barrier, store-learning and fence bodies. Saturation
closes steady admission; reconciliation still uses that same worker so a
successful heal can reopen admission. Closing the peer stops the worker.
See `INV-REPL-SESSION-ONE-EXCHANGE-001` (`SessionOrder`).
successful heal can reopen admission. Closing the peer stops the worker. A barrier request also uses the existing
shipper frame-write mutex because the shipper timer can emit on that connection
outside the peer worker.
See `INV-REPL-SESSION-ONE-EXCHANGE-001` (`SessionExchange.OwnAnswer`).
| From | To | Event and guard | Enforced in | Protects |
|---|---|---|---|---|
| `Healthy`, `Unknown` | `Degraded` or `CatchingUp` | ship, barrier or fence failure; or a probe that needs catch-up | `core/replication/peer.go` `ReplicaPeer.SetState`, `replicaStateTransitionAllowed` | `INV-REPL-PEER-TRANSITIONS-001` |
| `Healthy` | `Degraded`, then `NeedsRebuild` | the promotion seed barrier, or a heal (engine healthy verdict, recovery session done), reconciles the peer by (last data epoch, end) against the epoch table and finds it diverged; a sync barrier counts only a `Healthy` peer | `core/replication/volume.go` `seedNewPeerLiveCursorsLocked`, `reconcilePeer`; `core/replication/peer.go` `HealIfInSync`; `core/replication/peer_work_queue.go` | `INV-REPL-SESSION-ONE-EXCHANGE-001` | At most one steady-session exchange is in flight per peer: the peer queue owns ship, barrier, store learning and fence; reconciliation and promotion seeding use it too. Saturation refuses steady work while healing stays on the same worker. | M3 peer session exchange ordering | `core/replication/peer.go`; `core/replication/peer_work_queue.go` | `TestPublishHealthyDoesNotRaceStoreAttestation` (`core/host/volume/peer_reconcile_attestation_test.go`); `TestPeerSessionExchangesHaveOnlyQueuedOwners`, `TestPeerSessionOwnerScanFindsABypass` (`core/replication/session_queue_guard_test.go`); `TestSaturatedPeerQueueStillOwnsTheHealingExchange` (`core/replication/peer_work_queue_test.go`) | `SessionOrder` one exchange in flight per session | ACTIVE |
| `INV-REPL-DIVERGENT-TAIL-001`, `INV-REPL-EPOCH-TABLE-001` |
| `Healthy` | `Degraded`, then `NeedsRebuild` | the promotion seed barrier, or a heal (engine healthy verdict, recovery session done), reconciles the peer by (last data epoch, end) against the epoch table and finds it diverged; a sync barrier counts only a `Healthy` peer | `core/replication/volume.go` `seedNewPeerLiveCursorsLocked`, `reconcilePeer`; `core/replication/peer.go` `HealIfInSync`; `core/replication/peer_work_queue.go` | `INV-REPL-DIVERGENT-TAIL-001`, `INV-REPL-EPOCH-TABLE-001` |
| `Degraded` | `CatchingUp` or `NeedsRebuild` | the engine decides catch-up when the gap is in the primary WAL, rebuild when it is not | `core/engine/apply.go` `decide` | `INV-REPL-CATCHUP-REBUILD-001`, `INV-REPL-RECOVERY-SESSION-UNIQUE-001` |
| `CatchingUp` | `Healthy`, `Degraded` or `NeedsRebuild` | done-acknowledgement; failure; WAL recycled or retries exhausted | `core/replication/peer.go` `ReplicaPeer.SetState` | `INV-REPL-PEER-TRANSITIONS-001` |
| any but `NeedsRebuild` | `Healthy` | recovered | `core/replication/peer.go` `replicaStateTransitionAllowed` | `INV-REPL-PEER-TRANSITIONS-001` |
@@ -776,6 +777,7 @@ Notes:
| `INV-REPL-PEER-TRANSITIONS-001` | `ReplicaPeer.SetState` and `ReplicaPeer.Invalidate` apply only the transitions in the peer table; `NeedsRebuild` has no successor through either. | M3 peer state | `core/replication/peer.go` `ReplicaPeer.SetState`, `ReplicaPeer.Invalidate`, `replicaStateTransitionAllowed` | `TestReplicaStateTransition_AllowedSet`, `TestReplicaStateTransition_RejectedSet`, `TestReplicaStateTransition_NeedsRebuildIsTerminalInT4c` (`core/replication/peer_state_machine_test.go`); `TestReplicaPeer_InvalidatePreservesNeedsRebuildTerminalState` (`core/replication/invalidate_terminal_regression_test.go`); `TestReplicaPeer_InvalidateNonTerminalStatesBecomeDegraded`, `TestReplicaPeer_InvalidateOnNeedsRebuildStillLogsReason` (`core/replication/invalidate_transition_test.go`) | — | ACTIVE |
| `INV-REPL-DURABILITY-MODE-001` | Under `sync_all` a replicated `Sync` fails if any replica barrier fails; under `sync_quorum` it fails unless a majority of nodes, the primary included, are durable. | M3 barrier evaluation | `core/replication/durability.go` `EvaluateBarrierAcks` | `TestDurabilityCoordinator_Quorum_RF3_OneReplicaFailed`, `TestDurabilityCoordinator_Quorum_RF3_BothReplicasFailed`, `TestDurabilityCoordinator_SyncAll_AnyFailure_Fails` (`core/replication/durability_test.go`) | — | ACTIVE |
| `INV-REPL-PROMOTION-READY-001` | A replica reports `promotion_ready` only if it is a member, reachable, caught up, fenced at the current epoch, and has delivered its post-rebuild durable acknowledgement. An active recovery session always refuses readiness, even if delayed bounds select DecisionNone. | M3 Supporting → promotion candidate | `core/engine/promotion_ready.go` `BuildPromotionReadyFact` | `TestBuildPromotionReadyFact_RefusesPendingFence`, `TestBuildPromotionReadyFact_RefusesPostCloseAckGap`, `TestBuildPromotionReadyFact_RefusesNotCaughtUp` (`core/engine/promotion_ready_test.go`), `TestPromotionReadyRefusesDelayedProbeDuringNewRecovery` | `WALReplica` `I3`; `ReplicationFailover` `AckedSurvive`; `ReplicaReviewGuards` ReadyRequiresIdle | ACTIVE |
| `INV-REPL-SESSION-ONE-EXCHANGE-001` | At most one steady-session exchange is in flight per peer: the peer queue owns ship, barrier, store learning and fence; reconciliation and promotion seeding use it too. Saturation refuses steady work while healing stays on the same worker. | M3 peer session exchange ordering | `core/replication/peer.go`; `core/replication/peer_work_queue.go` | `TestPublishHealthyDoesNotRaceStoreAttestation` (`core/host/volume/peer_reconcile_attestation_test.go`); `TestPeerSessionExchangesHaveOnlyQueuedOwners`, `TestPeerSessionOwnerScanFindsABypass`, `TestPeerSessionOwnerScanFindsAPackageMethodAlias` (`core/replication/session_queue_guard_test.go`); `TestSaturatedPeerQueueStillOwnsTheHealingExchange` (`core/replication/peer_work_queue_test.go`) ; `TestBarrierRequestUsesTheShippersWriteOwner` (`core/transport/barrier_write_owner_test.go`) | `SessionExchange.OwnAnswer` | ACTIVE |
| `INV-REPL-DIVERGENT-TAIL-001` | A peer is counted only after a reconciliation in this session finds its (last data epoch, end) in sync with the primary's epoch table; an equal length of another epoch, a tail above the frontier or data without a table is diverged: NeedsRebuild, never healed by length. | M3 Healthy → Degraded → NeedsRebuild (seed, heal) | `core/replication/volume.go` `seedNewPeerLiveCursorsLocked`, `reconcilePeer`, `markDiverged`; `core/replication/peer.go` `HealIfInSync`; `core/replication/peer_work_queue.go` (barrier); `core/host/volume/peer_command_executor.go` `PublishHealthy`; `core/engine/apply.go` `decide` | `TestPromotionSeed_EqualLengthDivergentEpochIsRebuilt`, `TestPromotionSeed_SameEpochStartingElsewhereIsRebuilt`, `TestPromotionSeed_EpochTableControls` (`core/replication/divergent_epoch_seed_test.go`); `TestReplicationVolume_UpdateReplicaSet_DegradesPeerAboveLocalFrontier` (`core/replication/divergent_tail_seed_test.go`); `TestPublishHealthyNeverHealsAnEqualLengthDivergentPeer` (`core/host/volume/peer_heal_reconcile_test.go`); `TestDivergentTailBeforeTheEpochIsAcceptedIsRebuilt` (`core/engine/divergent_tail_test.go`); `TestPeerAdapterRegistry_DivergentTailAboveTheFrontierAtAddIsRebuilt` (`core/host/volume/peer_adapter_divergent_tail_test.go`) | `Promo` row `mut_g4_no_truncate` | ACTIVE |
| `INV-REPL-EPOCH-TABLE-001` | A durable epoch -> first LSN table per volume: a live entry's row is durable before it; a recovery makes it invalid (random token) before its first byte and only that token's final replace makes it valid (invalid = diverged); a load drops rows above the next LSN; at most 512 rows. | M3 replica apply, Primary adoption, rebuild done | `core/transport/epoch_table.go` `EpochTable.Note`, `Replace`, `SharedEnd`, `LastDataEpochAt`; `core/transport/replica.go` (ship entry, rebuild done, barrier reply); `core/transport/rebuild_sender.go`; `cmd/blockvolume/replication_ingress.go` `notePrimaryEpoch` | `TestEpochTable_NoteIsDurableAndOrdered`, `TestEpochTable_InterruptEveryPersistStep`, `TestEpochTable_LastDataEpochAtTheDurableEnd`, `TestEpochTable_SharedEnd` (`core/transport/epoch_table_test.go`); `TestRebuildDoneReplacesTheEpochTableWithThePrimarysRows`, `TestRebuildDoneWithoutTheTableReplaceIsNotAcked`, `TestEpochRowsWire` (`core/transport/epoch_rebuild_test.go`); `TestCatchUpKeepsTheHistorysEpochs` (`core/transport/epoch_catchup_test.go`); `TestCatchUpWithAFailedTableReplaceLeavesItInvalid`, `TestRecoveryLaneCrashBeforeTheFinalBarrierLeavesTheTableInvalid` (`core/transport/epoch_invalid_test.go`); `TestEveryPeerApplyPathHasAnEpochTableRule` (`core/transport/peer_apply_paths_guard_test.go`); `TestEpochTable_OnlyTheMarksOwnerCompletes`, `TestOverlappingRecoveriesAStaleCompletionLeavesTheTableInvalid`, `TestEpochTable_OwnershipChangeWaitsForInFlightAppliesAndRefusesLaterOnes` (`core/transport/epoch_owner_test.go`); `TestEpochTable_ACatchUpOverAnInvalidTableNeedsARebuild`, `TestCatchUpStartRefusedUnlessTheDurableEndMatches`, `TestLiveEntryOfANewEpochOnlyAtTheNextLSN`, `TestRecoveryLaneStartWithoutItsFromLSNIsRefused`, `TestEpochTable_LiveAppliesAreFenced` (`core/transport/epoch_rules_test.go`); `TestPromotionRejoinNeverAcknowledgesConflictingSameLengthTail` (`core/replication/promotion_prefix_regression_test.go`); `TestDelayedOldRecoveryApplyNeverLandsUnderANewValidTable` (`core/replication/epoch_delayed_apply_test.go`); `TestDualLaneRecoveryMakesTheEpochTableValid` (`core/transport/epoch_dual_lane_test.go`); `TestEpochTableReplaceOnlyAtPrimaryAdoption` (`core/transport/epoch_table_writers_guard_test.go`); `TestPrimaryRefusesInboundRecoveryFramesOverItsTable` (`core/transport/epoch_primary_refuses_test.go`); `TestIngressPrimaryAdoptionTableStep` (`cmd/blockvolume/replication_ingress_epoch_test.go`); `TestEpochTable_TrimAboveTheRecoveredEndKeepsTheNewWritesInTheirEpoch`, `TestEpochTable_BoundedSoItAlwaysReloads` (`core/transport/epoch_table_trim_test.go`); `TestEpochTableHasExactlyItsListedWriters`, `TestEpochTableWriterCensusFindsAFourth` (`core/transport/epoch_table_writers_guard_test.go`) | `Promo` Truncate (common prefix by (epoch, LSN)) | ACTIVE |
| `INV-ROLE-STALE-REPLAY-001` | A role call below the host's current desired epoch is refused and cannot clear a newer role-admission failure. | M3 role admission | `core/host/volume/host.go` `fenceSelfWithPeers`, `latchRoleAdmission` | `TestG1_StaleReplayDoesNotClearANewerAdmissionFailure`, `TestG1_StaleSupportingReplayDoesNotClearTheLatch` (`core/host/volume/g1_admission_latch_test.go`) | — | ACTIVE |