fix: require recovery before peer queue reset

This commit is contained in:
pingqiu committed 2026-08-01 03:19:51 -07:00
1 parent e8f02591de
commit 87617aedad
5 files changed
+192 -12

No files matched your search

@@ -93,6 +93,10 @@ type phase174FixedWorkResult struct {
PeerQueueSaturated uint64 `json:"peer_queue_saturated,omitempty"`
PostMeasurementDrain bool `json:"post_measurement_sync_all"`
PostMeasurementDrainNS int64 `json:"post_measurement_sync_all_ns,omitempty"`
PostMeasurementRecovery bool `json:"post_measurement_recovery"`
ReplicaProbeCount int `json:"replica_probe_count,omitempty"`
ReplicaCatchUpCount int `json:"replica_catchup_count,omitempty"`
MaxReplicaLagLSN uint64 `json:"max_replica_lag_lsn,omitempty"`
RemoteReplicaEvidence bool `json:"remote_replica_evidence_required"`
ReplicaCount int `json:"replica_count"`
ReplicaDurableCount int `json:"replica_durable_count"`
@@ -124,6 +128,12 @@ type phase174Pipeline struct {
closed bool
}
type phase174RecoveryEvidence struct {
probeCount int
catchUpCount int
maxLagLSN uint64
}
func TestPhase174FixedWorkContract(t *testing.T) {
for _, layer := range []phase174Layer{phase174DirectWALStore, phase174AdapterRF1, phase174RF3TCP} {
if _, _, err := phase174LayerContract(layer); err != nil {
@@ -175,6 +185,9 @@ func TestPhase174FixedWorkPipeline(t *testing.T) {
if err != nil || set < 1 || set > 2 {
t.Fatalf("%s must be 1 or 2", phase174SetEnv)
}
if os.Getenv(phase174RemoteReplicasEnv) != "" {
peerSessionIDCounter.Store(phase174RemoteSessionBase(set, run, writers))
}
oldLogWriter := log.Writer()
if os.Getenv("SW_BLOCK_BENCH_VERBOSE") == "" {
@@ -353,9 +366,15 @@ func runPhase174FixedWork(t *testing.T, p *phase174Pipeline, set, run, writers i
t.Fatalf("no replica reached final frontier")
}
var postMeasurementDrain time.Duration
var recoveryEvidence phase174RecoveryEvidence
if p.remoteReplicas {
p.replication.SetDurabilityMode(DurabilitySyncAll)
drainStart := time.Now()
_, _, targetLSN := p.primary.Boundaries()
recoveryEvidence, err = p.recoverRemoteReplicas(context.Background(), set, run, writers, targetLSN)
if err != nil {
t.Fatalf("post-measurement replica recovery: %v", err)
}
p.replication.SetDurabilityMode(DurabilitySyncAll)
if err := p.sync(context.Background()); err != nil {
t.Fatalf("post-measurement sync-all: %v", err)
}
@@ -419,8 +438,12 @@ func runPhase174FixedWork(t *testing.T, p *phase174Pipeline, set, run, writers i
FlusherExtentSyncNanos: flusherForeground.ExtentSyncDurationNanos - flusherBefore.ExtentSyncDurationNanos,
PrimaryStableLSN: primaryR, PrimaryHeadLSN: primaryH,
PostMeasurementDrain: p.remoteReplicas, PostMeasurementDrainNS: postMeasurementDrain.Nanoseconds(),
RemoteReplicaEvidence: p.remoteReplicas,
ReplicaCount: p.configuredReplicas, ReplicaDurableCount: durableReplicas,
PostMeasurementRecovery: p.remoteReplicas,
ReplicaProbeCount: recoveryEvidence.probeCount,
ReplicaCatchUpCount: recoveryEvidence.catchUpCount,
MaxReplicaLagLSN: recoveryEvidence.maxLagLSN,
RemoteReplicaEvidence: p.remoteReplicas,
ReplicaCount: p.configuredReplicas, ReplicaDurableCount: durableReplicas,
ReplicaFrontiersEqual: replicasEqual,
FlusherPhaseReset: flusherPhaseReset,
CloseRecoverComplete: true, CorrectnessSamples: correctness,
@@ -487,6 +510,106 @@ func (p *phase174Pipeline) sync(ctx context.Context) error {
return err
}
func phase174RemoteSessionBase(set, run, writers int) uint64 {
return 1_740_000_000 + uint64(set)*100_000_000 + uint64(writers)*1_000_000 + uint64(run)*1_000
}
func (p *phase174Pipeline) recoverRemoteReplicas(
ctx context.Context,
set, run, writers int,
targetLSN uint64,
) (phase174RecoveryEvidence, error) {
var evidence phase174RecoveryEvidence
if p.replication == nil || !p.remoteReplicas {
return evidence, nil
}
p.replication.mu.Lock()
peers := make([]*ReplicaPeer, 0, len(p.replication.peers))
for _, peer := range p.replication.peers {
peers = append(peers, peer)
}
p.replication.mu.Unlock()
sort.Slice(peers, func(i, j int) bool {
return peers[i].Target().ReplicaID < peers[j].Target().ReplicaID
})
for index := range peers {
peer := peers[index]
target := peer.Target()
sessionBase := phase174RemoteSessionBase(set, run, writers) + 100 + uint64(index)*10
probe := peer.Executor().Probe(
target.ReplicaID, target.DataAddr, target.ControlAddr,
sessionBase, target.Epoch, target.EndpointVersion,
)
if !probe.Success {
return evidence, fmt.Errorf("probe peer %s: %s", target.ReplicaID, probe.FailReason)
}
evidence.probeCount++
if probe.ReplicaFlushedLSN > targetLSN {
return evidence, fmt.Errorf("probe peer %s frontier %d exceeds primary target %d",
target.ReplicaID, probe.ReplicaFlushedLSN, targetLSN)
}
lag := targetLSN - probe.ReplicaFlushedLSN
if lag > evidence.maxLagLSN {
evidence.maxLagLSN = lag
}
completedSessionID := sessionBase
achievedLSN := probe.ReplicaFlushedLSN
if lag > 0 {
completedSessionID++
peer.SetState(ReplicaCatchingUp)
req := RuntimeRecoveryRequest{
ReplicaID: target.ReplicaID,
TargetDataAddr: target.DataAddr,
SessionID: completedSessionID,
Epoch: target.Epoch,
EndpointVersion: target.EndpointVersion,
FromLSN: probe.ReplicaFlushedLSN + 1,
FrontierHintLSN: targetLSN,
}
if err := p.replication.StartRuntimeRecovery(ctx, req); err != nil {
peer.Invalidate("phase174 catch-up start failed: " + err.Error())
return evidence, fmt.Errorf("start catch-up peer %s: %w", target.ReplicaID, err)
}
evidence.catchUpCount++
deadline := time.Now().Add(2 * time.Minute)
for {
status, err := p.replication.RuntimeRecoveryStatus(ctx, req)
if err != nil {
return evidence, fmt.Errorf("catch-up status peer %s: %w", target.ReplicaID, err)
}
if status.State == "caught_up" {
achievedLSN = status.AchievedLSN
break
}
if status.State == "failed" {
peer.Invalidate("phase174 catch-up failed: " + status.FailReason)
return evidence, fmt.Errorf("catch-up peer %s failed kind=%s reason=%s",
target.ReplicaID, status.FailureKind, status.FailReason)
}
if time.Now().After(deadline) {
return evidence, fmt.Errorf("catch-up peer %s timed out", target.ReplicaID)
}
select {
case <-ctx.Done():
return evidence, ctx.Err()
case <-time.After(10 * time.Millisecond):
}
}
}
if achievedLSN < targetLSN {
return evidence, fmt.Errorf("peer %s achieved %d below target %d",
target.ReplicaID, achievedLSN, targetLSN)
}
if err := peer.RefreshLiveShipSessionAfter(completedSessionID, achievedLSN, "phase174 recovery completed"); err != nil {
peer.Invalidate("phase174 live session refresh failed: " + err.Error())
return evidence, fmt.Errorf("refresh live session peer %s: %w", target.ReplicaID, err)
}
peer.SetState(ReplicaHealthy)
}
return evidence, nil
}
func (p *phase174Pipeline) replicationStats() VolumeStats {
if p.replication == nil {
return VolumeStats{}
+7 -1
View File
@@ -487,12 +487,18 @@ func (v *ReplicationVolume) replaceTerminalPeerQueueLocked(id string, old *peerW
if old == nil || v.peerQueues[id] != old || !old.isTerminal() {
return v.peerQueues[id]
}
old.closeAndWait()
peer := v.peers[id]
if peer == nil || v.closed {
old.closeAndWait()
delete(v.peerQueues, id)
return nil
}
// Saturation degrades the peer before this call returns. Recovery must
// close the LSN gap before a fresh queue can accept steady writes.
if peer.State() != ReplicaHealthy {
return old
}
old.closeAndWait()
replacement := newPeerWorkQueue(peer, v.peerQueueDepth)
v.peerQueues[id] = replacement
return replacement
@@ -155,11 +155,20 @@ func TestReplicationVolume_SyncAllWaitsForSlowBarrier(t *testing.T) {
}
func TestReplicationVolume_QueueSaturationIsTypedAndCounted(t *testing.T) {
v := NewReplicationVolume("queue-saturation", storage.NewBlockStore(64, 4096))
addr, _ := replicaHarness(t, "queue-saturation")
v := volumeHarness(t, "queue-saturation")
if err := v.UpdateReplicaSet(1, []ReplicaTarget{targetFor("slow", addr, 1, 1)}); err != nil {
t.Fatal(err)
}
started := make(chan struct{})
releaseCh := make(chan struct{})
var releaseOnce sync.Once
release := func() { releaseOnce.Do(func() { close(releaseCh) }) }
v.mu.Lock()
oldQueue := v.peerQueues["slow"]
peer := v.peers["slow"]
v.mu.Unlock()
oldQueue.closeAndWait()
q := newPeerWorkQueueWithOps("slow", 1, peerWorkQueueOps{
ship: func(ctx context.Context, _ LocalWrite) (bool, error) {
select {
@@ -174,11 +183,11 @@ func TestReplicationVolume_QueueSaturationIsTypedAndCounted(t *testing.T) {
return false, ctx.Err()
}
},
invalidate: peer.Invalidate,
})
v.mu.Lock()
v.peerQueues["slow"] = q
v.mu.Unlock()
t.Cleanup(func() { _ = v.Close() })
t.Cleanup(release)
first, err := v.enqueueLocalWrite(LocalWrite{LBA: 0, LSN: 1, Data: make([]byte, 4096)})
@@ -205,6 +214,12 @@ func TestReplicationVolume_QueueSaturationIsTypedAndCounted(t *testing.T) {
if got := v.Stats().PeerQueueSaturated; got != 1 {
t.Fatalf("PeerQueueSaturated=%d want 1", got)
}
v.mu.Lock()
current := v.peerQueues["slow"]
v.mu.Unlock()
if current != q {
t.Fatal("saturated queue changed before peer recovery completed")
}
release()
<-first.result
<-second.result
@@ -22,9 +22,10 @@ provided binary.
- 16,384 deterministic 4 KiB writes and 64 MiB per measured run;
- 1, 4, and 8 writers, five runs each, after a persistent precondition run;
- foreground ACK remains `sync_quorum_rf3`;
- after the measured Sync, an explicitly excluded SyncAll drain makes both
external replicas inspectable without weakening or relabeling foreground
semantics;
- after the measured Sync, an explicitly excluded recovery phase probes each
external replica, catches any lagging replica up from its durable `R+1`,
completes the production-equivalent live-session handoff, and only then
requires SyncAll;
- each remote process stops, reopens WALStore, recovers the exact expected
frontier, and verifies final payload bytes independently;
- the primary also closes, reopens, recovers, and verifies bytes every run.
@@ -34,10 +35,13 @@ provided binary.
- `phase174_distinct_node_rf3_status=ok`;
- 15 primary result rows and six independently recovered remote results;
- `foreground_sync_quorum_preserved=true`;
- `post_measurement_recovery_verified=true`;
- `post_measurement_sync_all_verified=true`;
- `remote_replica_frontiers_and_bytes_equal=true`;
- `rf3_distinct_node_healthy=true`;
- peer queue saturation is reported, not hidden;
- every primary row reports two live probes; catch-up count and maximum LSN lag
are preserved as evidence rather than inferred from the final barrier;
- no cross-ACK-profile throughput ratio, candidate selection, or product
mutation;
- remote process/store cleanup leaves no gate residue.
@@ -22,6 +22,7 @@ M01_ADDR="${M01_DATA_IP}:17411"
TP01_ADDR="${TP01_DATA_IP}:17412"
RUNS=5
WRITERS=(1 4 8)
GATE_COMPLETE=false
SSH=(ssh -T -i "${SSH_KEY}" -o ConnectTimeout=10 -o StrictHostKeyChecking=no -o BatchMode=yes)
SCP=(scp -q -i "${SSH_KEY}" -o ConnectTimeout=10 -o StrictHostKeyChecking=no -o BatchMode=yes)
@@ -37,11 +38,29 @@ write_summary() {
}
cleanup() {
rm -f "${LOCAL_BINARY}"
local exit_status=$?
if [[ "${GATE_COMPLETE}" != "true" ]]; then
mkdir -p "${ARTIFACT_DIR}/remote"
for spec in "${M01_HOST}:m01" "${TP01_HOST}:tp01"; do
local host="${spec%:*}" node="${spec##*:}"
for writers in "${WRITERS[@]}"; do
local dir="${REMOTE_ROOT}/w${writers}-${node}"
"${SCP[@]}" "${host}:${dir}/replica.log" "${ARTIFACT_DIR}/remote/w${writers}-${node}-failure.log" >/dev/null 2>&1 || true
"${SCP[@]}" "${host}:${dir}/result.json" "${ARTIFACT_DIR}/remote/w${writers}-${node}-failure-result.json" >/dev/null 2>&1 || true
done
done
write_summary "phase174_distinct_node_rf3_status=failed"
write_summary "failure_artifact=${PUBLISH_ROOT}/${RUN_ID}.tar.gz"
tar -C "$(dirname "${ARTIFACT_DIR}")" -czf "${ARTIFACT_DIR}.tar.gz" "$(basename "${ARTIFACT_DIR}")" >/dev/null 2>&1 || true
sha256sum "${ARTIFACT_DIR}.tar.gz" >"${ARTIFACT_DIR}.tar.gz.sha256" 2>/dev/null || true
"${SCP[@]}" "${ARTIFACT_DIR}.tar.gz" "${M02_HOST}:${PUBLISH_ROOT}/${RUN_ID}.tar.gz" >/dev/null 2>&1 || true
fi
rm -f "${LOCAL_BINARY}"
for host in "${M01_HOST}" "${TP01_HOST}"; do
remote "${host}" "test '${REMOTE_ROOT}' = '/tmp/${RUN_ID}'; rm -rf -- '${REMOTE_ROOT}'" >/dev/null 2>&1 || true
done
remote "${M02_HOST}" "test '${REMOTE_ROOT}' = '/tmp/${RUN_ID}'; test '${M02_STORE_ROOT}' = '/data/nvme/block/${RUN_ID}-stores'; rm -rf -- '${REMOTE_ROOT}' '${M02_STORE_ROOT}'" >/dev/null 2>&1 || true
remote "${M02_HOST}" "test '${REMOTE_ROOT}' = '/tmp/${RUN_ID}'; test '${M02_STORE_ROOT}' = '/data/nvme/block/${RUN_ID}-stores'; rm -rf -- '${REMOTE_ROOT}' '${M02_STORE_ROOT}'" >/dev/null 2>&1 || true
return "${exit_status}"
}
trap cleanup EXIT
@@ -101,7 +120,7 @@ write_summary "phase174_distinct_node_rf3_status=running"
write_summary "contract=phase174-distinct-node-rf3-v1"
write_summary "source_commit=$(git -C "${ROOT}" rev-parse HEAD)"
write_summary "foreground_ack_profile=sync_quorum_rf3"
write_summary "post_measurement_drain=sync_all"
write_summary "post_measurement_drain=probe_catchup_then_sync_all"
write_summary "transport=tcp"
write_summary "network_class=management_lan"
write_summary "primary_node=m02"
@@ -175,6 +194,9 @@ if len(rows) != 3 * runs:
raise SystemExit(f"primary rows={len(rows)} want {3 * runs}")
queue_saturation_rows = 0
replica_probe_count = 0
replica_catchup_count = 0
max_replica_lag_lsn = 0
for row in rows:
if row["contract"] != "phase174-fixed-work-v1" or row["ack_profile"] != "sync_quorum_rf3":
raise SystemExit(f"bad primary contract: {row}")
@@ -182,6 +204,8 @@ for row in rows:
raise SystemExit(f"bad external replica contract: {row}")
if not row["post_measurement_sync_all"] or row["post_measurement_sync_all_ns"] <= 0:
raise SystemExit(f"missing post-measurement drain: {row}")
if not row["post_measurement_recovery"] or row.get("replica_probe_count") != 2:
raise SystemExit(f"missing post-measurement recovery evidence: {row}")
if row["api_operations"] != 16384 or row["logical_bytes"] != 67108864:
raise SystemExit(f"bad fixed work: {row}")
if row["primary_wal_write_ops"] != 16384 or row["replication_write_ops"] != 16384:
@@ -190,6 +214,9 @@ for row in rows:
raise SystemExit(f"primary recovery mismatch: {row}")
if row.get("peer_queue_saturated", 0) > 0:
queue_saturation_rows += 1
replica_probe_count += row["replica_probe_count"]
replica_catchup_count += row.get("replica_catchup_count", 0)
max_replica_lag_lsn = max(max_replica_lag_lsn, row.get("max_replica_lag_lsn", 0))
remote_paths = sorted(glob.glob(f"{remote_dir}/w*-*-result.json"))
if len(remote_paths) != 6:
@@ -209,8 +236,12 @@ with open(summary_path, "a", encoding="utf-8") as out:
out.write(f"primary_result_count={len(rows)}\n")
out.write(f"remote_recovered_replica_count={len(remote_paths)}\n")
out.write(f"peer_queue_saturation_row_count={queue_saturation_rows}\n")
out.write(f"replica_probe_count={replica_probe_count}\n")
out.write(f"replica_catchup_count={replica_catchup_count}\n")
out.write(f"max_replica_lag_lsn={max_replica_lag_lsn}\n")
out.write("remote_replica_frontiers_and_bytes_equal=true\n")
out.write("foreground_sync_quorum_preserved=true\n")
out.write("post_measurement_recovery_verified=true\n")
out.write("post_measurement_sync_all_verified=true\n")
out.write("rf3_distinct_node_healthy=true\n")
out.write("architecture_candidate_selected=false\n")
@@ -218,6 +249,7 @@ with open(summary_path, "a", encoding="utf-8") as out:
out.write("phase174_distinct_node_rf3_status=ok\n")
PY
GATE_COMPLETE=true
cleanup
trap - EXIT
for host in "${M01_HOST}" "${M02_HOST}" "${TP01_HOST}"; do