T4c-pre-B: unified StartRecovery command + per-kind runtime policy

Per design memo §7a (architect rounds 29-30): introduce semantic
unification at the command boundary — one StartRecovery covers
catch-up / rebuild / partial-LBA — without unifying runtime
behavior. RecoveryRuntimePolicy carries per-content-kind envelope
(timeout / progress cadence / cancellation mode); engine populates
via DefaultRuntimePolicyFor at emit time.

- core/engine: StartRecovery + RecoveryContentKind (wal_delta /
  full_extent / partial_lba) + DurationClass + CancellationMode +
  RecoveryRuntimePolicy + DefaultRuntimePolicyFor.
- core/adapter: CommandExecutor.StartRecoverySession; adapter
  dispatch wired (queue + execute + start watchdog).
- core/transport: BlockExecutor.StartRecoverySession bridges
  wal_delta → catch-up sender, full_extent → rebuild sender;
  partial_lba returns explicit Stage-2 error; validateRecoveryPolicy
  enforces non-empty envelope + wal_delta+CancelOnTimeout requires
  Timeout > 0.
- Test executors (authority, host/volume, ops) updated with stub
  StartRecoverySession.
- 10 new engine tests (command shape, per-kind defaults, label
  strings, cadence/timeout consistency); 8 new transport tests
  (policy validation, dispatch contract — partial_lba rejected,
  unknown kind rejected, policy-validates-before-dispatch).

Legacy StartCatchUp / StartRebuild retained as engine emit shape;
T4c-3 muscle port migrates engine emission to StartRecovery.

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 01:54:52 -07:00
1 parent 9ffc149293
commit eadc113697
13 files changed
+678 -1

No files matched your search

+45 -1
View File
@@ -361,6 +361,28 @@ func (a *VolumeReplicaAdapter) prepareQueuedCommands(cmds []engine.Command) ([]e
NormalizeSessionPrepared(c.ReplicaID, sid, engine.SessionRebuild, c.TargetLSN),
)
queued = append(queued, queuedCommand{cmd: cmd, sessionID: sid})
case engine.StartRecovery:
// T4c-pre-B: forward-compatible dispatch path. Engine
// emission of StartRecovery happens at T4c-3 muscle port;
// today the legacy StartCatchUp / StartRebuild commands
// remain the engine's emit shape. This case ensures the
// adapter is ready when the migration lands.
//
// Map ContentKind to legacy SessionKind so the existing
// session lifecycle (SessionPrepared / Starting / Running
// / Completed) continues to work without churn:
// wal_delta → SessionCatchUp
// full_extent → SessionRebuild
// partial_lba → SessionRebuild (Stage 2 placeholder)
sid := sessionIDCounter.Add(1)
sessionKind := engine.SessionCatchUp
if c.ContentKind != engine.RecoveryContentWALDelta {
sessionKind = engine.SessionRebuild
}
events = append(events,
NormalizeSessionPrepared(c.ReplicaID, sid, sessionKind, c.TargetLSN),
)
queued = append(queued, queuedCommand{cmd: cmd, sessionID: sid})
case engine.FenceAtEpoch:
// Fence mints its own sessionID so the lineage wire frame
// carries a unique tuple. No SessionPrepared event —
@@ -409,6 +431,26 @@ func (a *VolumeReplicaAdapter) executeCommand(q queuedCommand) {
})
}
case engine.StartRecovery:
// T4c-pre-B unified dispatch: route through the executor's
// StartRecoverySession entry. Policy is taken from the
// command (engine populates via DefaultRuntimePolicyFor at
// emit time). On synchronous dispatch failure, normalize to
// SessionClose with a kind-tagged reason.
err := a.executor.StartRecoverySession(
c.ReplicaID,
q.sessionID, c.Epoch, c.EndpointVersion, c.TargetLSN,
c.ContentKind, c.RuntimePolicy,
)
if err != nil {
a.OnSessionClose(SessionCloseResult{
ReplicaID: c.ReplicaID,
SessionID: q.sessionID,
Success: false,
FailReason: fmt.Sprintf("start_recovery_failed[%s]: %v", c.ContentKind, err),
})
}
case engine.InvalidateSession:
a.executor.InvalidateSession(c.ReplicaID, c.SessionID, c.Reason)
@@ -456,7 +498,7 @@ func (a *VolumeReplicaAdapter) armStartWatchdog(q queuedCommand) {
return
}
switch q.cmd.(type) {
case engine.StartCatchUp, engine.StartRebuild:
case engine.StartCatchUp, engine.StartRebuild, engine.StartRecovery:
default:
return
}
@@ -546,6 +588,8 @@ func replicaIDFromCommand(cmd engine.Command) string {
return c.ReplicaID
case engine.StartRebuild:
return c.ReplicaID
case engine.StartRecovery:
return c.ReplicaID
case engine.InvalidateSession:
return c.ReplicaID
case engine.PublishHealthy:
@@ -200,6 +200,18 @@ func (m *mockExecutor) StartRebuild(replicaID string, sessionID, epoch, endpoint
return nil
}
func (m *mockExecutor) StartRecoverySession(
replicaID string,
sessionID, epoch, endpointVersion, targetLSN uint64,
contentKind engine.RecoveryContentKind,
policy engine.RecoveryRuntimePolicy,
) error {
if contentKind == engine.RecoveryContentFullExtent {
return m.StartRebuild(replicaID, sessionID, epoch, endpointVersion, targetLSN)
}
return m.StartCatchUp(replicaID, sessionID, epoch, endpointVersion, targetLSN)
}
func (m *mockExecutor) InvalidateSession(replicaID string, sessionID uint64, reason string) {
m.mu.Lock()
defer m.mu.Unlock()
+36
View File
@@ -1,5 +1,7 @@
package adapter
import "github.com/seaweedfs/seaweed-block/core/engine"
// CommandExecutor is the interface that runtime muscles must satisfy.
// Each method corresponds to one engine command. The adapter calls
// these after engine.Apply() emits commands.
@@ -38,6 +40,40 @@ type CommandExecutor interface {
// Same contract as StartCatchUp.
StartRebuild(replicaID string, sessionID, epoch, endpointVersion, targetLSN uint64) error
// StartRecoverySession begins a recovery session for the given content
// kind under the given runtime policy. Per design memo §7a (T4c-pre-B):
// unifies catch-up / rebuild / partial-LBA execution behind one entry.
//
// ContentKind selects the substrate primitive:
// - RecoveryContentWALDelta → tier-1 WAL-window scan
// (catch-up; subsumes StartCatchUp).
// - RecoveryContentFullExtent → tier-3 full-extent fill
// (rebuild; subsumes StartRebuild).
// - RecoveryContentPartialLBA → tier-2 archive dump (Stage 2;
// implementations may return error).
//
// RuntimePolicy carries the per-content-kind execution envelope
// (timeout / progress cadence / cancellation mode); see engine
// `DefaultRuntimePolicyFor`. The executor MUST honor the policy
// (no hard-coded timeouts that contradict it).
//
// Async lifecycle: same contract as StartCatchUp / StartRebuild —
// completion / failure MUST be reported via the registered
// OnSessionClose callback using the SAME sessionID.
//
// Transition note (T4c-pre-B): existing `StartCatchUp` /
// `StartRebuild` remain as the wire-level entry points until
// T4c-3 muscle port migrates engine emission to `StartRecovery`.
// Adapters / executors MAY implement `StartCatchUp` and
// `StartRebuild` as thin wrappers that build a `StartRecovery`
// command and dispatch through `StartRecoverySession`.
StartRecoverySession(
replicaID string,
sessionID, epoch, endpointVersion, targetLSN uint64,
contentKind engine.RecoveryContentKind,
policy engine.RecoveryRuntimePolicy,
) error
// InvalidateSession cancels an active session.
InvalidateSession(replicaID string, sessionID uint64, reason string)
@@ -692,6 +692,9 @@ func (e *closureExecutor) StartCatchUp(replicaID string, sessionID, epoch, endpo
func (e *closureExecutor) StartRebuild(replicaID string, sessionID, epoch, endpointVersion, targetLSN uint64) error {
return nil
}
func (e *closureExecutor) StartRecoverySession(replicaID string, sessionID, epoch, endpointVersion, targetLSN uint64, contentKind engine.RecoveryContentKind, policy engine.RecoveryRuntimePolicy) error {
return nil
}
func (e *closureExecutor) InvalidateSession(replicaID string, sessionID uint64, reason string) {}
func (e *closureExecutor) PublishHealthy(replicaID string) {}
func (e *closureExecutor) PublishDegraded(replicaID string, reason string) {}
@@ -955,6 +955,9 @@ func (e *policyClosureExecutor) StartCatchUp(replicaID string, sessionID, epoch,
func (e *policyClosureExecutor) StartRebuild(replicaID string, sessionID, epoch, endpointVersion, targetLSN uint64) error {
return nil
}
func (e *policyClosureExecutor) StartRecoverySession(replicaID string, sessionID, epoch, endpointVersion, targetLSN uint64, contentKind engine.RecoveryContentKind, policy engine.RecoveryRuntimePolicy) error {
return nil
}
func (e *policyClosureExecutor) InvalidateSession(replicaID string, sessionID uint64, reason string) {}
func (e *policyClosureExecutor) PublishHealthy(replicaID string) {}
func (e *policyClosureExecutor) PublishDegraded(replicaID string, reason string) {}
@@ -91,6 +91,9 @@ func (e *restartExecutor) StartCatchUp(replicaID string, sessionID, epoch, endpo
func (e *restartExecutor) StartRebuild(replicaID string, sessionID, epoch, endpointVersion, targetLSN uint64) error {
return nil
}
func (e *restartExecutor) StartRecoverySession(replicaID string, sessionID, epoch, endpointVersion, targetLSN uint64, contentKind engine.RecoveryContentKind, policy engine.RecoveryRuntimePolicy) error {
return nil
}
func (e *restartExecutor) InvalidateSession(replicaID string, sessionID uint64, reason string) {}
func (e *restartExecutor) PublishHealthy(replicaID string) {}
func (e *restartExecutor) PublishDegraded(replicaID string, reason string) {}
+141
View File
@@ -1,5 +1,7 @@
package engine
import "time"
// Command is an action the engine requests from the runtime.
// Commands are execution requests, not semantic conclusions.
type Command interface {
@@ -87,3 +89,142 @@ func CommandKind(c Command) string {
}
return c.commandKind()
}
// --- T4c-pre-B: unified recovery command + runtime policy ---
//
// Per design memo §7a (architect rounds 29-30): T4c introduces a
// unified `StartRecovery` semantic command that subsumes the
// `StartCatchUp` / `StartRebuild` split (and forward-accommodates
// `partial_lba` for Stage 2). Existing `StartCatchUp` / `StartRebuild`
// types remain in place as legacy aliases for transition; the
// adapter / executor layers internally bridge to `StartRecoverySession`
// (T4c-pre-B). Engine-emit migration to `StartRecovery` happens at
// T4c-3 muscle port.
//
// Round-30 refinement: unified semantic command, NOT unified runtime
// behavior. Catch-up (~0.1s) and rebuild (~30min) cannot share
// timeout / progress cadence / cancellation. RuntimePolicy carries
// per-content-kind defaults (memo §7a.1a).
// RecoveryContentKind selects which substrate primitive the recovery
// session draws from. Maps 1:1 to the §13.0a tier-1 sub-modes for
// `wal_delta` (see §5.1 substrate-specific labels) and to T5/Stage 2
// content classes for `full_extent` / `partial_lba`.
type RecoveryContentKind string
const (
// RecoveryContentWALDelta — tier-1 content drawn from retained
// WAL window. Substrate provides per-LSN entries (walstore
// `wal_replay`) or per-LBA-dedup entries (smartwal
// `state_convergence`); see memo §13.0a.
RecoveryContentWALDelta RecoveryContentKind = "wal_delta"
// RecoveryContentFullExtent — tier-3 content drawn from full
// extent. T5 scope. Used when WAL retention has been exceeded
// or the replica needs a fresh-from-scratch fill.
RecoveryContentFullExtent RecoveryContentKind = "full_extent"
// RecoveryContentPartialLBA — tier-2 content drawn from a
// persistent LBA-dump archive. Stage 2 scope (post-go-live).
// Master archive subsystem provides the dump; recovery executor
// fetches + ships the dump-listed LBAs.
RecoveryContentPartialLBA RecoveryContentKind = "partial_lba"
)
// DurationClass labels expected runtime envelope. Surfaces in
// projection / log / ops visibility so operators can tell at-a-glance
// whether a given recovery is a 0.1s catch-up or a 30min rebuild
// without parsing payload internals.
type DurationClass string
const (
DurationShort DurationClass = "short" // milliseconds-seconds
DurationLong DurationClass = "long" // minutes-hours
DurationArchiveBound DurationClass = "archive_bound" // includes archive/dump fetch latency
)
// CancellationMode defines how a recovery session terminates on
// non-completion. Catch-up's tight expected duration favors timeout-
// driven failure; rebuild's variable duration favors stall-driven.
type CancellationMode string
const (
// CancelOnTimeout — fixed timeout fires → recovery aborts → tier
// escalation per memo §7.4. Used for catch-up (`wal_delta`).
CancelOnTimeout CancellationMode = "timeout"
// CancelOnExplicit — only cancel on explicit caller signal. Used
// for unbounded operations where neither timeout nor stall is a
// good cancellation signal.
CancelOnExplicit CancellationMode = "explicit"
// CancelOnProgressStall — cancel if no progress for N cadences.
// Used for rebuild (`full_extent`) and Stage-2 partial-LBA
// (`partial_lba`) where total duration is variable but per-step
// progress should be steady.
CancelOnProgressStall CancellationMode = "progress_stall"
)
// RecoveryRuntimePolicy carries the per-content-kind execution
// envelope for a recovery session. Engine selects the policy when
// emitting `StartRecovery`; adapter passes through; executor honors.
//
// Per memo §7a.1a defaults (architect round-30): wal_delta is
// timeout-driven, full_extent and partial_lba are progress-stall-
// driven.
type RecoveryRuntimePolicy struct {
ExpectedDurationClass DurationClass
ProgressCadence time.Duration // progress callback / heartbeat cadence
Timeout time.Duration // 0 = no fixed timeout (use stall detection)
CancellationMode CancellationMode
}
// StartRecovery — unified semantic command that subsumes
// `StartCatchUp` / `StartRebuild` and forward-accommodates
// `partial_lba` (Stage 2). Per memo §7a.1.
//
// Engine emits this command when a replica needs recovery (gap
// detected, peer state Degraded → recovery decision). ContentKind
// selects the substrate primitive; RuntimePolicy carries the
// per-kind execution envelope.
type StartRecovery struct {
ReplicaID string
Epoch uint64
EndpointVersion uint64
TargetLSN uint64
ContentKind RecoveryContentKind
RuntimePolicy RecoveryRuntimePolicy
}
func (StartRecovery) commandKind() string { return "StartRecovery" }
// DefaultRuntimePolicyFor returns the per-content-kind default
// runtime policy from memo §7a.1a. Engine uses this when emitting
// `StartRecovery` without per-call overrides.
func DefaultRuntimePolicyFor(kind RecoveryContentKind) RecoveryRuntimePolicy {
switch kind {
case RecoveryContentWALDelta:
return RecoveryRuntimePolicy{
ExpectedDurationClass: DurationShort,
Timeout: 30 * time.Second,
ProgressCadence: 1 * time.Second,
CancellationMode: CancelOnTimeout,
}
case RecoveryContentFullExtent:
return RecoveryRuntimePolicy{
ExpectedDurationClass: DurationLong,
Timeout: 0, // no fixed timeout — rebuild may legitimately take 30min+
ProgressCadence: 10 * time.Second,
CancellationMode: CancelOnProgressStall,
}
case RecoveryContentPartialLBA:
return RecoveryRuntimePolicy{
ExpectedDurationClass: DurationArchiveBound,
Timeout: 0, // per-deployment tunable; depends on archive fetch SLA
ProgressCadence: 10 * time.Second,
CancellationMode: CancelOnProgressStall,
}
}
// Unknown kind — return zero-value; caller must validate.
return RecoveryRuntimePolicy{}
}
+169
View File
@@ -0,0 +1,169 @@
package engine
import (
"testing"
"time"
)
// T4c-pre-B engine command model upgrade tests.
//
// Per design memo §7a (architect rounds 29-30): unified `StartRecovery`
// + per-content-kind `RecoveryRuntimePolicy`. These tests pin the
// envelope defaults and the command shape; they are the engine-side
// receipt that T4c-pre-B has landed.
func TestStartRecovery_CommandKind(t *testing.T) {
cmd := StartRecovery{
ReplicaID: "r1",
Epoch: 7,
EndpointVersion: 2,
TargetLSN: 1000,
ContentKind: RecoveryContentWALDelta,
RuntimePolicy: DefaultRuntimePolicyFor(RecoveryContentWALDelta),
}
if got := CommandKind(cmd); got != "StartRecovery" {
t.Fatalf("CommandKind: want StartRecovery, got %q", got)
}
}
func TestDefaultRuntimePolicyFor_WALDelta(t *testing.T) {
got := DefaultRuntimePolicyFor(RecoveryContentWALDelta)
if got.ExpectedDurationClass != DurationShort {
t.Errorf("WALDelta DurationClass = %q, want %q", got.ExpectedDurationClass, DurationShort)
}
if got.CancellationMode != CancelOnTimeout {
t.Errorf("WALDelta CancellationMode = %q, want %q", got.CancellationMode, CancelOnTimeout)
}
if got.Timeout <= 0 {
t.Errorf("WALDelta Timeout = %v, want > 0 (CancelOnTimeout requires positive timeout)", got.Timeout)
}
if got.ProgressCadence <= 0 || got.ProgressCadence > got.Timeout {
t.Errorf("WALDelta ProgressCadence = %v, want 0 < cadence <= timeout=%v",
got.ProgressCadence, got.Timeout)
}
}
func TestDefaultRuntimePolicyFor_FullExtent(t *testing.T) {
got := DefaultRuntimePolicyFor(RecoveryContentFullExtent)
if got.ExpectedDurationClass != DurationLong {
t.Errorf("FullExtent DurationClass = %q, want %q", got.ExpectedDurationClass, DurationLong)
}
if got.CancellationMode != CancelOnProgressStall {
t.Errorf("FullExtent CancellationMode = %q, want %q", got.CancellationMode, CancelOnProgressStall)
}
// Memo §7a.1a: rebuilds may legitimately run 30min+; no fixed
// timeout. Stall-driven cancellation handles unbounded runtime.
if got.Timeout != 0 {
t.Errorf("FullExtent Timeout = %v, want 0 (stall-driven, not timeout-driven)", got.Timeout)
}
if got.ProgressCadence <= 0 {
t.Errorf("FullExtent ProgressCadence = %v, want > 0", got.ProgressCadence)
}
}
func TestDefaultRuntimePolicyFor_PartialLBA(t *testing.T) {
got := DefaultRuntimePolicyFor(RecoveryContentPartialLBA)
if got.ExpectedDurationClass != DurationArchiveBound {
t.Errorf("PartialLBA DurationClass = %q, want %q", got.ExpectedDurationClass, DurationArchiveBound)
}
if got.CancellationMode != CancelOnProgressStall {
t.Errorf("PartialLBA CancellationMode = %q, want %q", got.CancellationMode, CancelOnProgressStall)
}
}
func TestDefaultRuntimePolicyFor_UnknownKind(t *testing.T) {
got := DefaultRuntimePolicyFor(RecoveryContentKind("does-not-exist"))
zero := RecoveryRuntimePolicy{}
if got != zero {
t.Errorf("unknown kind: want zero policy, got %+v", got)
}
}
// Memo §7a.1a "duration class is observable" — once labeled, the
// labels must be the documented set so observability tooling can rely
// on them. This pins the public string values.
func TestDurationClass_Labels(t *testing.T) {
cases := []struct{ got, want string }{
{string(DurationShort), "short"},
{string(DurationLong), "long"},
{string(DurationArchiveBound), "archive_bound"},
}
for _, c := range cases {
if c.got != c.want {
t.Errorf("duration class label = %q, want %q", c.got, c.want)
}
}
}
func TestCancellationMode_Labels(t *testing.T) {
cases := []struct{ got, want string }{
{string(CancelOnTimeout), "timeout"},
{string(CancelOnExplicit), "explicit"},
{string(CancelOnProgressStall), "progress_stall"},
}
for _, c := range cases {
if c.got != c.want {
t.Errorf("cancellation mode label = %q, want %q", c.got, c.want)
}
}
}
func TestRecoveryContentKind_Labels(t *testing.T) {
cases := []struct{ got, want string }{
{string(RecoveryContentWALDelta), "wal_delta"},
{string(RecoveryContentFullExtent), "full_extent"},
{string(RecoveryContentPartialLBA), "partial_lba"},
}
for _, c := range cases {
if c.got != c.want {
t.Errorf("content kind label = %q, want %q", c.got, c.want)
}
}
}
// Pin: per-content-kind defaults are independent — changing one MUST
// NOT silently change another (memo §7a.1a explicitly requires
// per-kind separation, not a shared default).
func TestDefaultRuntimePolicyFor_PerKindIndependence(t *testing.T) {
wal := DefaultRuntimePolicyFor(RecoveryContentWALDelta)
full := DefaultRuntimePolicyFor(RecoveryContentFullExtent)
if wal.CancellationMode == full.CancellationMode {
t.Errorf("wal_delta and full_extent share cancellation mode (%q) — memo §7a.1a requires distinct envelopes",
wal.CancellationMode)
}
if wal.ExpectedDurationClass == full.ExpectedDurationClass {
t.Errorf("wal_delta and full_extent share duration class (%q) — memo §7a.1a requires distinct envelopes",
wal.ExpectedDurationClass)
}
}
// Pin: ProgressCadence must be a sub-multiple of any positive
// Timeout. If Timeout is 30s and Cadence is 60s, the timeout fires
// before the first cadence — silent envelope contradiction.
func TestDefaultRuntimePolicyFor_TimeoutCadenceConsistency(t *testing.T) {
for _, kind := range []RecoveryContentKind{
RecoveryContentWALDelta,
RecoveryContentFullExtent,
RecoveryContentPartialLBA,
} {
p := DefaultRuntimePolicyFor(kind)
if p.Timeout > 0 && p.ProgressCadence > p.Timeout {
t.Errorf("kind=%q cadence=%v > timeout=%v: cadence would never fire before timeout",
kind, p.ProgressCadence, p.Timeout)
}
}
}
// Sanity: the policy struct is comparable (all comparable fields).
// If a future change adds a non-comparable field this catches it at
// compile time rather than at usage site.
var _ = func() bool {
a := RecoveryRuntimePolicy{}
b := RecoveryRuntimePolicy{}
return a == b
}
// time import is referenced; suppress unused if a future cleanup
// removes the only Duration check path.
var _ = time.Second
@@ -4,6 +4,7 @@ import (
"sync"
"github.com/seaweedfs/seaweed-block/core/adapter"
"github.com/seaweedfs/seaweed-block/core/engine"
)
// HealthyPathExecutor is the T1 minimum-readiness executor. It
@@ -80,6 +81,16 @@ func (e *HealthyPathExecutor) StartRebuild(replicaID string, sessionID, epoch, e
return nil
}
func (e *HealthyPathExecutor) StartRecoverySession(
replicaID string,
sessionID, epoch, endpointVersion, targetLSN uint64,
contentKind engine.RecoveryContentKind,
policy engine.RecoveryRuntimePolicy,
) error {
e.record("StartRecoverySession:" + replicaID + ":" + string(contentKind))
return nil
}
func (e *HealthyPathExecutor) InvalidateSession(replicaID string, sessionID uint64, reason string) {
e.record("InvalidateSession:" + replicaID)
}
@@ -4,6 +4,7 @@ import (
"sync"
"github.com/seaweedfs/seaweed-block/core/adapter"
"github.com/seaweedfs/seaweed-block/core/engine"
)
// noopExecutor is the T0-scope CommandExecutor stub required by
@@ -72,6 +73,16 @@ func (e *noopExecutor) StartRebuild(replicaID string, sessionID, epoch, endpoint
return nil
}
func (e *noopExecutor) StartRecoverySession(
replicaID string,
sessionID, epoch, endpointVersion, targetLSN uint64,
contentKind engine.RecoveryContentKind,
policy engine.RecoveryRuntimePolicy,
) error {
e.record("StartRecoverySession:" + replicaID + ":" + string(contentKind))
return nil
}
func (e *noopExecutor) InvalidateSession(replicaID string, sessionID uint64, reason string) {
e.record("InvalidateSession:" + replicaID)
}
+4
View File
@@ -9,6 +9,7 @@ import (
"testing"
"github.com/seaweedfs/seaweed-block/core/adapter"
"github.com/seaweedfs/seaweed-block/core/engine"
)
// newTestServer builds a live httptest.Server wrapping the ops handlers.
@@ -205,6 +206,9 @@ func (e *nopExecutor) Probe(string, string, string, uint64, uint64) adapter.Prob
}
func (e *nopExecutor) StartCatchUp(string, uint64, uint64, uint64, uint64) error { return nil }
func (e *nopExecutor) StartRebuild(string, uint64, uint64, uint64, uint64) error { return nil }
func (e *nopExecutor) StartRecoverySession(string, uint64, uint64, uint64, uint64, engine.RecoveryContentKind, engine.RecoveryRuntimePolicy) error {
return nil
}
func (e *nopExecutor) Fence(string, uint64, uint64, uint64) error { return nil }
func (e *nopExecutor) InvalidateSession(string, uint64, string) {}
func (e *nopExecutor) PublishHealthy(string) {}
@@ -0,0 +1,104 @@
package transport
import (
"fmt"
"github.com/seaweedfs/seaweed-block/core/engine"
)
// StartRecoverySession is the unified recovery dispatch entry per
// design memo §7a (T4c-pre-B). One semantic command, per-content-kind
// runtime envelope.
//
// Per round-30 architect refinement: the unification is at the COMMAND
// boundary, not at runtime. ContentKind selects which substrate
// primitive (and therefore which sender goroutine) executes; policy
// carries the per-kind execution envelope.
//
// Today (T4c-pre-B scope):
// - wal_delta → bridges to existing doCatchUp (catch-up ship+barrier)
// - full_extent → bridges to existing doRebuild (rebuild stream)
// - partial_lba → not implemented (Stage 2; returns explicit error)
//
// The legacy `StartCatchUp` / `StartRebuild` methods remain as thin
// wrappers (see catchup_sender.go and rebuild_sender.go) and dispatch
// through this method. T4c-3 muscle port migrates engine emission
// from `StartCatchUp` / `StartRebuild` to `StartRecovery`; at that
// point the legacy methods can be removed.
//
// RuntimePolicy honoring (current scope): the existing senders use
// the package-level `recoveryConnTimeout` constant. Per-policy
// timeout splitting is deferred to T4c-3 (memo §7a.1a). This method
// validates the policy is non-zero / has a known cancellation mode
// but does not yet enforce per-call timeouts. POC report
// `v3-phase-15-t4c-pre-poc-report.md` §3.b documents this gap.
func (e *BlockExecutor) StartRecoverySession(
replicaID string,
sessionID, epoch, endpointVersion, targetLSN uint64,
contentKind engine.RecoveryContentKind,
policy engine.RecoveryRuntimePolicy,
) error {
if err := validateRecoveryPolicy(contentKind, policy); err != nil {
return err
}
switch contentKind {
case engine.RecoveryContentWALDelta:
// Bridge to existing catch-up sender.
return e.StartCatchUp(replicaID, sessionID, epoch, endpointVersion, targetLSN)
case engine.RecoveryContentFullExtent:
// Bridge to existing rebuild sender.
return e.StartRebuild(replicaID, sessionID, epoch, endpointVersion, targetLSN)
case engine.RecoveryContentPartialLBA:
// Stage 2 — archive-driven LBA dump fetch. Not implemented
// in T4c-pre-B. Engine MUST NOT emit StartRecovery with this
// kind during Stage 1; if it does, fail closed.
return fmt.Errorf(
"transport: StartRecoverySession partial_lba is Stage 2 scope (replica=%s session=%d)",
replicaID, sessionID,
)
default:
return fmt.Errorf(
"transport: StartRecoverySession unknown content kind %q (replica=%s session=%d)",
contentKind, replicaID, sessionID,
)
}
}
// validateRecoveryPolicy checks the runtime policy is well-formed
// for the given content kind. Round-30 invariant: every recovery
// session carries an envelope; zero-value policies are a programmer
// error (engine should always populate via DefaultRuntimePolicyFor).
func validateRecoveryPolicy(
kind engine.RecoveryContentKind,
policy engine.RecoveryRuntimePolicy,
) error {
if policy.CancellationMode == "" {
return fmt.Errorf(
"transport: StartRecoverySession kind=%q missing cancellation mode",
kind,
)
}
if policy.ExpectedDurationClass == "" {
return fmt.Errorf(
"transport: StartRecoverySession kind=%q missing expected duration class",
kind,
)
}
// Per memo §7a.1a: wal_delta uses CancelOnTimeout (Timeout > 0
// required); full_extent / partial_lba use CancelOnProgressStall
// (Timeout MAY be 0). Validate the wal_delta path; leave the
// stall-driven paths permissive — the executor falls back to
// recoveryConnTimeout for the per-frame deadline.
if kind == engine.RecoveryContentWALDelta &&
policy.CancellationMode == engine.CancelOnTimeout &&
policy.Timeout == 0 {
return fmt.Errorf(
"transport: StartRecoverySession wal_delta with CancelOnTimeout requires Timeout > 0",
)
}
return nil
}
@@ -0,0 +1,136 @@
package transport
import (
"strings"
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/engine"
)
// T4c-pre-B transport-side tests for unified recovery dispatch.
//
// Goal: pin the dispatch contract — wal_delta routes to catch-up,
// full_extent routes to rebuild, partial_lba is rejected (Stage 2),
// unknown kind is rejected. Policy validation rejects malformed
// envelopes.
//
// We do not exercise the catch-up / rebuild loops themselves — those
// are tested by their own files. We test ONLY the dispatch + policy
// validation surfaces introduced by recovery_session.go.
func TestValidateRecoveryPolicy_Empty(t *testing.T) {
err := validateRecoveryPolicy(engine.RecoveryContentWALDelta, engine.RecoveryRuntimePolicy{})
if err == nil {
t.Fatal("zero-value policy must fail validation")
}
if !strings.Contains(err.Error(), "missing cancellation mode") {
t.Errorf("wrong error: %v", err)
}
}
func TestValidateRecoveryPolicy_MissingDurationClass(t *testing.T) {
policy := engine.RecoveryRuntimePolicy{
CancellationMode: engine.CancelOnTimeout,
Timeout: 1 * time.Second,
}
err := validateRecoveryPolicy(engine.RecoveryContentWALDelta, policy)
if err == nil {
t.Fatal("missing duration class must fail validation")
}
if !strings.Contains(err.Error(), "missing expected duration class") {
t.Errorf("wrong error: %v", err)
}
}
func TestValidateRecoveryPolicy_WALDeltaTimeoutMustBePositive(t *testing.T) {
// CancelOnTimeout with Timeout==0 is a programmer error — without
// a positive timeout the cancellation will never fire.
policy := engine.RecoveryRuntimePolicy{
CancellationMode: engine.CancelOnTimeout,
ExpectedDurationClass: engine.DurationShort,
Timeout: 0,
}
err := validateRecoveryPolicy(engine.RecoveryContentWALDelta, policy)
if err == nil {
t.Fatal("wal_delta + CancelOnTimeout + Timeout==0 must fail validation")
}
if !strings.Contains(err.Error(), "Timeout > 0") {
t.Errorf("wrong error: %v", err)
}
}
func TestValidateRecoveryPolicy_FullExtentZeroTimeoutAllowed(t *testing.T) {
// Memo §7a.1a: full_extent uses CancelOnProgressStall; Timeout=0
// is the documented default (rebuilds may run 30min+).
policy := engine.DefaultRuntimePolicyFor(engine.RecoveryContentFullExtent)
if err := validateRecoveryPolicy(engine.RecoveryContentFullExtent, policy); err != nil {
t.Fatalf("full_extent default policy must validate: %v", err)
}
}
func TestValidateRecoveryPolicy_AllDefaultsPass(t *testing.T) {
for _, kind := range []engine.RecoveryContentKind{
engine.RecoveryContentWALDelta,
engine.RecoveryContentFullExtent,
engine.RecoveryContentPartialLBA,
} {
p := engine.DefaultRuntimePolicyFor(kind)
if err := validateRecoveryPolicy(kind, p); err != nil {
t.Errorf("default policy for kind=%q rejected by validation: %v", kind, err)
}
}
}
// Dispatch contract: BlockExecutor.StartRecoverySession routes
// partial_lba to an explicit Stage-2 error. We do NOT test the
// successful wal_delta / full_extent paths here because those would
// require a real replica connection — they are covered by the
// existing catchup_sender_test.go / rebuild_sender_test.go.
func TestStartRecoverySession_PartialLBARejected(t *testing.T) {
exec := &BlockExecutor{}
policy := engine.DefaultRuntimePolicyFor(engine.RecoveryContentPartialLBA)
err := exec.StartRecoverySession(
"r1", 1, 1, 1, 100,
engine.RecoveryContentPartialLBA, policy,
)
if err == nil {
t.Fatal("partial_lba must return Stage-2 error in T4c-pre-B")
}
if !strings.Contains(err.Error(), "Stage 2") {
t.Errorf("wrong error: %v", err)
}
}
func TestStartRecoverySession_UnknownKindRejected(t *testing.T) {
exec := &BlockExecutor{}
policy := engine.DefaultRuntimePolicyFor(engine.RecoveryContentWALDelta)
err := exec.StartRecoverySession(
"r1", 1, 1, 1, 100,
engine.RecoveryContentKind("nonsense-kind"), policy,
)
if err == nil {
t.Fatal("unknown content kind must be rejected")
}
if !strings.Contains(err.Error(), "unknown content kind") {
t.Errorf("wrong error: %v", err)
}
}
func TestStartRecoverySession_PolicyValidationFiresFirst(t *testing.T) {
// Policy validation must run before content-kind dispatch — a
// malformed policy on a valid kind should still surface as a
// policy error, not a dispatch error.
exec := &BlockExecutor{}
err := exec.StartRecoverySession(
"r1", 1, 1, 1, 100,
engine.RecoveryContentFullExtent,
engine.RecoveryRuntimePolicy{}, // zero policy
)
if err == nil {
t.Fatal("zero policy must be rejected even for valid kind")
}
if !strings.Contains(err.Error(), "missing cancellation mode") {
t.Errorf("expected policy validation error first, got: %v", err)
}
}