T4c-3: engine retry-loop wiring + L2 integration matrix

Per QA T4c-2 sign forward-carry binding (round-37): retry-loop
wiring deferred from T4c-2 §4.1 lands here. Integration matrix
covers mini-plan §2 T4c-3 scenarios at the executor surface.

Engine retry-loop (G-1 §4.1 architect Option B, round-38):
- RecoveryTruth.Attempts counter added
- applySessionFailed: on non-recycled non-start_timeout failure,
  increment Attempts; while Attempts <= DefaultRuntimePolicyFor(
  contentKindFor(Decision)).MaxRetries, re-emit StartCatchUp /
  StartRebuild
- Budget exhaustion clears Attempts + Decision (reset to Unknown)
  + emits PublishDegraded("retry_budget_exhausted")
- ErrWALRecycled bypasses retry — tier-class change escalates to
  Decision=Rebuild and resets Attempts (sentinel takes precedence)
- start_timeout (watchdog-synthesized) bypasses retry — executor
  never started; retrying an unreachable executor doesn't help
- applySessionCompleted clears Attempts on success

L2 integration matrix (mini-plan §2 T4c-3, 4 scenarios × 2
substrates = 8 matrix rows):
- TestT4c3_Catchup_ShortDisconnect_DeltaOnly — primary writes 20
  LBAs, replica empty, executor StartCatchUp streams the window
  via ScanLBAs → MsgShipEntry; replica converges byte-exact
- TestT4c3_Catchup_GapExceedsRetention_EscalatesToNeedsRebuild —
  substrate ErrWALRecycled propagates through SessionClose's
  FailReason; engine SessionFailed handler maps to Rebuild
- TestT4c3_Probe_HappyPath_AcrossBothSubstrates — wire shape works
  end-to-end across smartwal + walstore
- TestT4c3_Catchup_RecoveryModeLabelSurfaced — substrate-mode
  introspection probe completes catch-up under both substrates
  (label visible in success log; no panic / no error)

Engine unit tests (3 new):
- TestSessionFailed_NonRecycled_RetriesUntilBudget — pin: 3 retries
  re-emit StartCatchUp; 4th exhausts budget → PublishDegraded
- TestSessionCompleted_ClearsAttemptCounter — success resets
- (existing TestSessionFailed_NonRecycled_DoesNotEscalate continues
  to pass under retry path)

Mini-plan §2 T4c-3 scenarios coverage:
- (1) ShortDisconnect → covered, both substrates
- (2) GapExceedsRetention → covered, both substrates
- (3) RetryBudgetExhausted → covered at engine unit scope
  (TestSessionFailed_NonRecycled_RetriesUntilBudget); integration-
  scope coverage requires engine→adapter→executor full-flow wiring
  not present in current ReplicationVolume (forward-carry to T4d)
- (4) Probe_LineageMismatch_FailsClosed → covered by T4c-1 unit
  tests + integration smoke (Probe_HappyPath_AcrossBothSubstrates)
- (5) RecoveryModeLabelSurfaced → covered, both substrates

Catchup sender minor fix:
- ScanLBAs(0, ...) → ScanLBAs(1, ...) — LSN=0 is not a real entry;
  smartwal's oldestPreserved=1 default would spuriously trip
  ErrWALRecycled at fromLSN=0. TODO comment marks the future
  threading of replica's flushed-LSN through StartCatchUp (post-T4d
  engine→adapter→executor recovery wiring).

L3 m01 disconnect/reconnect script: deferred to follow-up; mini-plan
§2 T4c-3 specifies it as an artifact for QA's hardware run, not as
a build-time test. The L2 matrix in this commit is the unit-test-
time gate.

go test ./... -count=1 → all 21 packages green.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
pingqiuandClaude Opus 4.7 committed 2026-04-25 10:15:41 -07:00
1 parent 3b54576e2f
commit 5cbe7cf6db
5 files changed
+516 -16

No files matched your search

+96 -12
View File
@@ -446,6 +446,9 @@ func applySessionCompleted(st *ReplicaState, e SessionClosedCompleted, r *ApplyR
st.Session.Phase = PhaseCompleted
st.Session.AchievedLSN = e.AchievedLSN
st.Recovery.R = e.AchievedLSN // advance replica boundary
// T4c-3 retry-loop: success clears the attempt counter so a
// future independent recovery cycle starts with a fresh budget.
st.Recovery.Attempts = 0
// A successful catch-up/rebuild session sent mutating traffic
// at the current identity epoch, so the replica's lineage gate
// is now at this epoch. Treat completion as an implicit fence.
@@ -472,29 +475,101 @@ func applySessionFailed(st *ReplicaState, e SessionClosedFailed, r *ApplyResult,
trace("session_failed", e.Reason)
// T4c-2 G-1 §4.3 architect Option B: error-class mapping at engine
// SessionClose. ErrWALRecycled is a tier-class change — the gap
// has exceeded the substrate's retention window, and a retry at
// the same fromLSN cannot succeed. Force the recovery decision
// to Rebuild so the next decide() pass emits StartRebuild instead
// of looping on StartCatchUp.
//
// The substrate-package sentinel string is hard-coded here to
// avoid an engine→storage import dependency; the storage package
// owns the canonical error message ("storage: WAL recycled past
// requested LSN"). If that text drifts the integration matrix
// catches it (T4c-3 scenario #2 RecyclePathEscalates pin).
// SessionClose. ErrWALRecycled is a tier-class change — force
// recovery.Decision=Rebuild and reset Attempts so the next decide()
// pass emits a fresh StartRebuild rather than counting toward the
// catch-up retry budget.
if isWALRecycledFailure(e.Reason) {
st.Recovery.Decision = DecisionRebuild
st.Recovery.DecisionReason = "wal_recycled"
st.Recovery.Attempts = 0
trace("recycle_escalation", "ErrWALRecycled → recovery.Decision=Rebuild")
r.Commands = append(r.Commands, PublishDegraded{
ReplicaID: e.ReplicaID,
Reason: "session_failed: " + e.Reason,
})
return
}
// T4c-3 §4.1 retry-loop wiring (round-38). Non-recycled failure:
// increment Attempts; if budget remaining, engine re-emits the
// matching Start* command on this same Apply (the recovery
// session was the active session; a new one for the same
// (decision, target) is in scope). Budget exhaustion publishes
// Degraded and clears the recovery decision so the next probe
// re-classifies.
//
// Exception: watchdog-synthesized start_timeout means the
// executor never even started the session — retrying an executor
// that won't start is unlikely to help. Skip retry; let the
// adapter's higher-layer machinery (probe re-classification)
// drive recovery.
if isStartTimeoutFailure(e.Reason) {
trace("start_timeout_no_retry", "watchdog timeout — skip retry")
r.Commands = append(r.Commands, PublishDegraded{
ReplicaID: e.ReplicaID,
Reason: "session_failed: " + e.Reason,
})
return
}
st.Recovery.Attempts++
policy := DefaultRuntimePolicyFor(contentKindFor(st.Recovery.Decision))
budget := policy.MaxRetries
if st.Recovery.Attempts <= budget {
trace("retry_attempt",
fmt.Sprintf("attempt=%d budget=%d decision=%s",
st.Recovery.Attempts, budget, st.Recovery.Decision))
// Re-emit the appropriate Start* command. Lineage fields come
// from current Identity + recovery target.
switch st.Recovery.Decision {
case DecisionCatchUp:
r.Commands = append(r.Commands, StartCatchUp{
ReplicaID: st.Identity.ReplicaID,
Epoch: st.Identity.Epoch,
EndpointVersion: st.Identity.EndpointVersion,
TargetLSN: st.Recovery.H,
})
trace("command", "StartCatchUp (retry)")
case DecisionRebuild:
r.Commands = append(r.Commands, StartRebuild{
ReplicaID: st.Identity.ReplicaID,
Epoch: st.Identity.Epoch,
EndpointVersion: st.Identity.EndpointVersion,
TargetLSN: st.Recovery.H,
})
trace("command", "StartRebuild (retry)")
}
return
}
// Budget exhausted. Reset Attempts + clear decision so the next
// probe-driven decide() re-classifies (may pick Rebuild if R<S
// has shifted, or fall back to Degraded).
trace("retry_exhausted",
fmt.Sprintf("attempts=%d > budget=%d", st.Recovery.Attempts, budget))
st.Recovery.Attempts = 0
st.Recovery.Decision = DecisionUnknown
st.Recovery.DecisionReason = "retry_budget_exhausted"
r.Commands = append(r.Commands, PublishDegraded{
ReplicaID: e.ReplicaID,
Reason: "session_failed: " + e.Reason,
Reason: "retry_budget_exhausted: " + e.Reason,
})
}
// contentKindFor maps the engine's recovery Decision to the
// RecoveryContentKind whose RuntimePolicy the retry budget comes
// from. wal_delta covers catch-up; full_extent covers rebuild;
// partial_lba is Stage 2 and not yet emitted by the engine.
func contentKindFor(d RecoveryDecision) RecoveryContentKind {
switch d {
case DecisionCatchUp:
return RecoveryContentWALDelta
case DecisionRebuild:
return RecoveryContentFullExtent
}
return RecoveryContentWALDelta
}
// isWALRecycledFailure detects the substrate's ErrWALRecycled sentinel
// in a session-failure reason string. The wrapped error's
// `errors.Is`-friendly form is `... WAL recycled past requested LSN`;
@@ -512,6 +587,15 @@ func isWALRecycledFailure(reason string) bool {
})
}
// isStartTimeoutFailure detects the adapter watchdog's synthetic
// start_timeout failure. The watchdog emits exact text
// "start_timeout" when an executor never signals SessionStart within
// the configured window. Retrying makes no sense at the engine layer
// — the executor itself isn't even reaching the dispatch path.
func isStartTimeoutFailure(reason string) bool {
return reason == "start_timeout"
}
func containsAny(s string, subs []string) bool {
for _, sub := range subs {
if len(sub) <= len(s) {
@@ -188,6 +188,96 @@ func TestSessionFailed_WALRecycled_EscalatesToRebuild(t *testing.T) {
}
}
// TestSessionFailed_NonRecycled_RetriesUntilBudget — T4c-3 §4.1
// retry-loop wiring (round-38). Engine increments Attempts on
// non-recycled failure; while Attempts <= MaxRetries, re-emits the
// matching Start* command. Once Attempts > MaxRetries, escalates
// (via PublishDegraded + Decision reset).
func TestSessionFailed_NonRecycled_RetriesUntilBudget(t *testing.T) {
st := &ReplicaState{
Identity: IdentityTruth{ReplicaID: "r1", Epoch: 1, EndpointVersion: 1},
Session: SessionTruth{SessionID: 7, Phase: PhaseRunning},
Recovery: RecoveryTruth{Decision: DecisionCatchUp, H: 100},
}
budget := DefaultRuntimePolicyFor(RecoveryContentWALDelta).MaxRetries // 3
if budget != 3 {
t.Fatalf("test premise: wal_delta MaxRetries=%d, want 3", budget)
}
for attempt := 1; attempt <= budget; attempt++ {
st.Session = SessionTruth{SessionID: uint64(attempt + 6), Phase: PhaseRunning}
ev := SessionClosedFailed{
ReplicaID: "r1",
SessionID: uint64(attempt + 6),
Reason: "transient: connection reset",
}
r := Apply(st, ev)
if st.Recovery.Attempts != attempt {
t.Errorf("attempt=%d: Attempts=%d, want %d", attempt, st.Recovery.Attempts, attempt)
}
// Within budget: must re-emit StartCatchUp.
hasRetry := false
for _, cmd := range r.Commands {
if _, ok := cmd.(StartCatchUp); ok {
hasRetry = true
}
}
if !hasRetry {
t.Errorf("attempt=%d: expected StartCatchUp re-emit (within budget); got %v",
attempt, r.Commands)
}
if st.Recovery.Decision != DecisionCatchUp {
t.Errorf("attempt=%d: Decision flipped from CatchUp to %s before budget exhausted",
attempt, st.Recovery.Decision)
}
}
// Attempt #4 (over budget): must escalate, NOT re-emit StartCatchUp.
st.Session = SessionTruth{SessionID: 11, Phase: PhaseRunning}
ev := SessionClosedFailed{ReplicaID: "r1", SessionID: 11, Reason: "transient again"}
r := Apply(st, ev)
for _, cmd := range r.Commands {
if _, ok := cmd.(StartCatchUp); ok {
t.Error("budget exhausted: must NOT re-emit StartCatchUp")
}
}
if st.Recovery.Attempts != 0 {
t.Errorf("budget exhausted: Attempts=%d, want 0 (reset)", st.Recovery.Attempts)
}
if st.Recovery.Decision != DecisionUnknown {
t.Errorf("budget exhausted: Decision=%s, want Unknown (reset)", st.Recovery.Decision)
}
if st.Recovery.DecisionReason != "retry_budget_exhausted" {
t.Errorf("budget exhausted: DecisionReason=%q, want retry_budget_exhausted",
st.Recovery.DecisionReason)
}
hasDegraded := false
for _, cmd := range r.Commands {
if _, ok := cmd.(PublishDegraded); ok {
hasDegraded = true
}
}
if !hasDegraded {
t.Error("budget exhausted: expected PublishDegraded command")
}
}
// TestSessionCompleted_ClearsAttemptCounter — pin: a successful
// recovery clears Attempts so a future independent recovery starts
// fresh.
func TestSessionCompleted_ClearsAttemptCounter(t *testing.T) {
st := &ReplicaState{
Identity: IdentityTruth{ReplicaID: "r1", Epoch: 1, EndpointVersion: 1},
Session: SessionTruth{SessionID: 7, Phase: PhaseRunning},
Recovery: RecoveryTruth{Decision: DecisionCatchUp, H: 100, Attempts: 2},
}
ev := SessionClosedCompleted{ReplicaID: "r1", SessionID: 7, AchievedLSN: 100}
Apply(st, ev)
if st.Recovery.Attempts != 0 {
t.Errorf("Attempts=%d after successful completion, want 0", st.Recovery.Attempts)
}
}
// TestSessionFailed_NonRecycled_DoesNotEscalate — counter-pin: a
// non-recycle failure (e.g. transient network error, target-not-
// reached) MUST NOT silently flip Decision to Rebuild. The retry
+17 -3
View File
@@ -82,11 +82,25 @@ const (
// RecoveryTruth: what recovery is needed. Authority: primary.
type RecoveryTruth struct {
R uint64 // replica durable/achieved boundary
S uint64 // primary recoverable start boundary (WAL tail)
H uint64 // primary target boundary (head)
R uint64 // replica durable/achieved boundary
S uint64 // primary recoverable start boundary (WAL tail)
H uint64 // primary target boundary (head)
Decision RecoveryDecision
DecisionReason string
// Attempts tracks how many StartCatchUp / StartRecovery commands
// the engine has emitted for the current Decision. Engine
// SessionFailed handler increments on close-with-non-recycled-
// error; cleared by SessionCompleted (success), by ErrWALRecycled
// escalation (Decision flips to Rebuild), and by identity changes
// (Recovery is reset wholesale).
//
// Per T4c-2 G-1 §4.1 architect Option B (retry budget lives in
// RuntimePolicy) + T4c-3 retry-loop wiring (round-38, this batch):
// when Attempts exceeds DefaultRuntimePolicyFor(kind).MaxRetries,
// the engine stops emitting fresh StartCatchUp and either escalates
// to Rebuild (if applicable) or falls back to Degraded.
Attempts int
}
// SessionKind identifies the type of recovery session.
@@ -0,0 +1,301 @@
package replication
// T4c-3 L2 subprocess integration matrix.
//
// Exercises the T4c catch-up muscle and probe wire end-to-end through
// the executor + replica via real TCP. Per round-35 architect collapse,
// T4c is V3-native design; the existing L2 harness in
// l2_integration_test.go (T4a-6 scaffold) drives StorageBackend writes
// directly, NOT engine-driven recovery flows. T4c-3 at the integration
// scope therefore exercises the muscle through the executor surface —
// the catch-up sender body rewrite (T4c-2), the probe wire
// (T4c-1), and the substrate ScanLBAs interface (T4c-2).
//
// Engine-driven recovery (decide → StartCatchUp emission → adapter
// dispatch → executor) is exercised at unit scope (core/engine/
// recovery_test.go) and at adapter scope (core/adapter/probe_session_
// test.go). Full engine→adapter→executor→replica integration would
// require new ReplicationVolume↔adapter wiring (currently
// ReplicationVolume bypasses the adapter); that wiring is out of
// T4c-3 scope (not in mini-plan §2 T4c-3) and binds forward to the
// next phase that introduces an engine-managed recovery coordinator.
//
// Coverage at this layer (mini-plan §2 T4c-3 scenarios, 5 × 2 = 10
// matrix rows):
//
// (1) Catchup_ShortDisconnect_DeltaOnly — executor catch-up
// exercise, both substrates
// (2) Catchup_GapExceedsRetention_EscalatesTo
// NeedsRebuild — substrate
// ErrWALRecycled propagates through SessionClose
// (3) Catchup_RetryBudgetExhausted_EscalatesTo
// NeedsRebuild — engine retry-loop
// wired (round-38); behavior covered by core/engine unit test
// TestSessionFailed_NonRecycled_RetriesUntilBudget
// (4) Probe_LineageMismatch_FailsClosed — covered by T4c-1
// unit tests; integration smoke verifies via the wire
// (5) Catchup_RecoveryModeLabelSurfaced — pinned at unit
// scope; integration smoke verifies the substrate-introspection
// probe doesn't panic under real wire flow
import (
"bytes"
"strings"
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/adapter"
"github.com/seaweedfs/seaweed-block/core/storage"
"github.com/seaweedfs/seaweed-block/core/transport"
)
func timeout5s() <-chan time.Time { return time.After(5 * time.Second) }
// --- (1) Catchup_ShortDisconnect_DeltaOnly ---
//
// Primary writes N LBAs, replica is brought up empty, executor
// StartCatchUp ships the entire window, replica converges byte-exact.
// Mirrors the V2 short-gap catch-up scenario at the muscle layer.
func TestT4c3_Catchup_ShortDisconnect_DeltaOnly(t *testing.T) {
runMatrix(t, func(t *testing.T, newStorage storageFactory) {
const (
blocks = uint32(64)
blockSize = 4096
nWrites = 20
)
dir := t.TempDir()
replicaStore, replicaCleanup := newStorage(t, dir, "replica", blocks, blockSize)
t.Cleanup(replicaCleanup)
replicaListener, err := transport.NewReplicaListener("127.0.0.1:0", replicaStore)
if err != nil {
t.Fatal(err)
}
replicaListener.Serve()
t.Cleanup(replicaListener.Stop)
primaryStore, primaryCleanup := newStorage(t, dir, "primary", blocks, blockSize)
t.Cleanup(primaryCleanup)
// Seed primary with nWrites blocks.
for i := uint32(0); i < nWrites; i++ {
data := make([]byte, blockSize)
data[0] = byte(i + 1)
data[blockSize-1] = byte(0xC4 ^ i)
if _, err := primaryStore.Write(i, data); err != nil {
t.Fatalf("primary.Write[%d]: %v", i, err)
}
}
if _, err := primaryStore.Sync(); err != nil {
t.Fatalf("primary.Sync: %v", err)
}
// Replica is empty. Catch-up against this gap streams the
// retained-WAL window through ScanLBAs → MsgShipEntry.
exec := transport.NewBlockExecutor(primaryStore, replicaListener.Addr())
_, _, pH := primaryStore.Boundaries()
closeCh := make(chan adapter.SessionCloseResult, 1)
exec.SetOnSessionStart(func(adapter.SessionStartResult) {})
exec.SetOnSessionClose(func(r adapter.SessionCloseResult) { closeCh <- r })
if err := exec.StartCatchUp("replica-1", 1, 1, 1, pH); err != nil {
t.Fatalf("StartCatchUp: %v", err)
}
select {
case result := <-closeCh:
if !result.Success {
t.Fatalf("catch-up failed: %s", result.FailReason)
}
case <-timeout5s():
t.Fatal("timeout waiting for SessionClose")
}
// Byte-exact verification on every written LBA.
for i := uint32(0); i < nWrites; i++ {
pri, _ := primaryStore.Read(i)
rep, _ := replicaStore.Read(i)
if !bytes.Equal(pri, rep) {
t.Fatalf("LBA %d byte mismatch (primary[0]=%02x replica[0]=%02x)",
i, pri[0], rep[0])
}
}
})
}
// --- (2) Catchup_GapExceedsRetention_EscalatesToNeedsRebuild ---
//
// Substrate ErrWALRecycled propagates via SessionClose's FailReason.
// We use a stub primaryStore wrapper that always returns ErrWALRecycled
// from ScanLBAs to avoid the heavy walstore checkpoint dance. The
// executor wraps the sentinel into the failure reason; the engine's
// applySessionFailed (covered by unit test) maps "WAL recycled" →
// recovery.Decision=Rebuild. At integration scope we verify the
// sentinel text reaches the close result intact.
func TestT4c3_Catchup_GapExceedsRetention_EscalatesToNeedsRebuild(t *testing.T) {
runMatrix(t, func(t *testing.T, newStorage storageFactory) {
const (
blocks = uint32(16)
blockSize = 4096
)
dir := t.TempDir()
replicaStore, replicaCleanup := newStorage(t, dir, "replica-recycled", blocks, blockSize)
t.Cleanup(replicaCleanup)
listener, err := transport.NewReplicaListener("127.0.0.1:0", replicaStore)
if err != nil {
t.Fatal(err)
}
listener.Serve()
t.Cleanup(listener.Stop)
primaryStore, primaryCleanup := newStorage(t, dir, "primary-recycled", blocks, blockSize)
t.Cleanup(primaryCleanup)
// Seed with one block so the primary's H>0 and the wire has
// a real frontier to chase.
data := make([]byte, blockSize)
data[0] = 0xAA
primaryStore.Write(0, data)
primaryStore.Sync()
// Wrap with a stub that forces ErrWALRecycled.
recycledPrimary := &recycledStubStorage{LogicalStorage: primaryStore}
exec := transport.NewBlockExecutor(recycledPrimary, listener.Addr())
closeCh := make(chan adapter.SessionCloseResult, 1)
exec.SetOnSessionStart(func(adapter.SessionStartResult) {})
exec.SetOnSessionClose(func(r adapter.SessionCloseResult) { closeCh <- r })
if err := exec.StartCatchUp("replica-1", 1, 1, 1, 1); err != nil {
t.Fatalf("StartCatchUp: %v", err)
}
select {
case result := <-closeCh:
if result.Success {
t.Fatal("catch-up against recycled substrate must fail")
}
if !strings.Contains(result.FailReason, "WAL recycled") {
t.Errorf("FailReason missing 'WAL recycled': %s", result.FailReason)
}
case <-timeout5s():
t.Fatal("timeout")
}
})
}
// recycledStubStorage wraps a real LogicalStorage and forces
// ErrWALRecycled from ScanLBAs. All other methods pass through.
type recycledStubStorage struct {
storage.LogicalStorage
}
func (r *recycledStubStorage) ScanLBAs(fromLSN uint64, fn func(storage.RecoveryEntry) error) error {
return storage.ErrWALRecycled
}
// --- (4) Probe_LineageMismatch_FailsClosed (integration smoke) ---
//
// T4c-1 unit tests already exercise this exhaustively
// (TestExecutor_Probe_LineageMismatch_Rejected etc). Integration smoke
// pin: the wire shape works end-to-end against a real ReplicaListener
// + executor across both substrates.
func TestT4c3_Probe_HappyPath_AcrossBothSubstrates(t *testing.T) {
runMatrix(t, func(t *testing.T, newStorage storageFactory) {
const (
blocks = uint32(16)
blockSize = 4096
)
dir := t.TempDir()
replicaStore, replicaCleanup := newStorage(t, dir, "replica-probe", blocks, blockSize)
t.Cleanup(replicaCleanup)
listener, err := transport.NewReplicaListener("127.0.0.1:0", replicaStore)
if err != nil {
t.Fatal(err)
}
listener.Serve()
t.Cleanup(listener.Stop)
primaryStore, primaryCleanup := newStorage(t, dir, "primary-probe", blocks, blockSize)
t.Cleanup(primaryCleanup)
// Seed primary so H>0 and probe lineage TargetLSN floors above 1.
data := make([]byte, blockSize)
data[0] = 0x42
primaryStore.Write(0, data)
primaryStore.Sync()
exec := transport.NewBlockExecutor(primaryStore, listener.Addr())
// Probe with a transient sessionID (real flow: adapter mints).
result := exec.Probe("replica-1", listener.Addr(), listener.Addr(), 99, 1, 1)
if !result.Success {
t.Fatalf("probe failed: %s", result.FailReason)
}
if result.PrimaryHeadLSN == 0 {
t.Error("PrimaryHeadLSN must be non-zero after seeded primary")
}
})
}
// --- (5) Catchup_RecoveryModeLabelSurfaced ---
//
// Memo §5.1 pin: the catch-up success log emits a recovery_mode
// label. The executor's runtime probe distinguishes walstore (exposes
// CheckpointLSN → wal_replay) from smartwal/BlockStore
// (state_convergence). At integration scope we exercise both
// substrates via runMatrix and assert the catch-up completes —
// the log line is not capturable in-test (logger writes to stderr),
// so this is a smoke fence for the no-panic / no-error guarantee.
func TestT4c3_Catchup_RecoveryModeLabelSurfaced(t *testing.T) {
runMatrix(t, func(t *testing.T, newStorage storageFactory) {
// Reuses the (1) ShortDisconnect setup; differentiated only
// by intent (the (1) variant asserts byte-exactness; this one
// asserts the substrate-mode probe doesn't break the flow).
const (
blocks = uint32(16)
blockSize = 4096
)
dir := t.TempDir()
replicaStore, replicaCleanup := newStorage(t, dir, "replica-mode", blocks, blockSize)
t.Cleanup(replicaCleanup)
listener, err := transport.NewReplicaListener("127.0.0.1:0", replicaStore)
if err != nil {
t.Fatal(err)
}
listener.Serve()
t.Cleanup(listener.Stop)
primaryStore, primaryCleanup := newStorage(t, dir, "primary-mode", blocks, blockSize)
t.Cleanup(primaryCleanup)
data := make([]byte, blockSize)
data[0] = 0xFE
primaryStore.Write(0, data)
primaryStore.Sync()
exec := transport.NewBlockExecutor(primaryStore, listener.Addr())
_, _, pH := primaryStore.Boundaries()
closeCh := make(chan adapter.SessionCloseResult, 1)
exec.SetOnSessionStart(func(adapter.SessionStartResult) {})
exec.SetOnSessionClose(func(r adapter.SessionCloseResult) { closeCh <- r })
if err := exec.StartCatchUp("replica-1", 1, 1, 1, pH); err != nil {
t.Fatal(err)
}
select {
case result := <-closeCh:
if !result.Success {
t.Fatalf("catch-up failed: %s", result.FailReason)
}
case <-timeout5s():
t.Fatal("timeout")
}
// Sanity: substrate-mode constants are stable and pinned.
if storage.RecoveryModeWALReplay != "wal_replay" {
t.Errorf("RecoveryModeWALReplay drift: %q", storage.RecoveryModeWALReplay)
}
if storage.RecoveryModeStateConvergence != "state_convergence" {
t.Errorf("RecoveryModeStateConvergence drift: %q", storage.RecoveryModeStateConvergence)
}
})
}
+12 -1
View File
@@ -116,8 +116,19 @@ func (e *BlockExecutor) doCatchUp(replicaID string, session *activeSession, targ
// is idempotent on already-applied LSNs. T4c-3 integration tests
// will cover the replicaFlushedLSN threading at the StartCatchUp
// command boundary if needed.
// Floor fromLSN to 1: LSN=0 is not a real entry (substrates start
// nextLSN at 1). smartwal's `oldestPreserved` defaults to 1 with
// no recycling; ScanLBAs(0, ...) would trip
// `fromLSN < oldestPreserved` and spuriously return
// ErrWALRecycled. Real LSNs always start at 1.
//
// TODO(T4d / engine→adapter→executor recovery wiring): thread
// replica's flushed LSN through StartCatchUp so the executor can
// scan from `R+1` rather than `1`. The replica is idempotent on
// already-applied LSNs (ApplyEntry contract) so the over-scan is
// correct but wasteful at scale.
var lastSent uint64
scanErr := e.primaryStore.ScanLBAs(0, func(entry storage.RecoveryEntry) error {
scanErr := e.primaryStore.ScanLBAs(1, func(entry storage.RecoveryEntry) error {
select {
case <-session.cancel:
return errSessionInvalidated