Block semantic engine + runnable block sparrow (#1)

* V3 mini engine: Phase 01 + 02 + 03 initial implementation

Phase 01 — Semantic Core (engine/):
- 5 truth domains, 11 events, 6 commands, deterministic Apply()
- Stale rejection, terminal truth, wrong-replica guard
- 17 conformance tests

Phase 02 — Reference Runtime (schema/ + runtime/ + conformance/):
- YAML case loader with strict validation
- Replay runner with expectation checker
- 7 cases, 7 determinism proofs, 5 loader tests

Phase 03 — Adapter (adapter/):
- Single route: observation -> engine -> command -> executor
- CommandExecutor with SetOnSessionClose callback
- Command dispatch outside lock, session ID owned by adapter
- 8 constraint tests (C8/C9/C10/C12 + callback + full route)

44 tests total, all passing.

* Phase 04: runnable block sparrow with real TCP transport

First public runnable slice of seaweed-block. Demonstrates three
recovery paths end-to-end through a deterministic semantic engine:

  1. Healthy: replica caught up (R >= H), no recovery needed
  2. Catch-up: short gap (R >= S, R < H), ship blocks via TCP
  3. Rebuild: long gap (R < S), full base copy via TCP

Package structure (renamed v3mini/ -> core/):
  core/engine     - deterministic Apply(state, event) reducer
  core/adapter    - single-route adapter with async callback wiring
  core/schema     - YAML conformance case loading (strict fields)
  core/runtime    - replay runner for conformance oracle
  core/conformance - 7 YAML cases + determinism + loader tests
  core/storage    - in-memory block store with LSN tracking
  core/transport  - TCP protocol, replica listener, block executor
  cmd/sparrow     - runnable demo binary

51 tests, all passing. Sparrow runs via: go run ./cmd/sparrow

Key design rules enforced:
  - Engine decides, executor executes (C12)
  - Same facts produce same decision (C8)
  - Timer only triggers probe, never recovery (C9)
  - No transport state in engine (C10, recursive reflect guard)
  - Terminal truth only from SessionClosedCompleted
  - Executor honors engine-issued targetLSN exactly
  - Session close callback wired from executor to adapter to engine
  - Command dispatch outside adapter mutex (no deadlock risk)
  - Rebuild uses AdvanceFrontier (no LBA 0 corruption)
  - Catch-up reports barrier-confirmed achievedLSN, not intent

* fix: address CodeRabbit/Gemini review findings

1. Max payload limit in ReadMsg (16MB cap, prevents memory exhaustion)
2. Session ID race fix: capture IDs under lock in buildSessionEvents,
   pass via map to executeCommand — no re-locking needed
3. Barrier response error handling in replica listener
4. Demo 1 uses waitForMode polling instead of fixed sleep
5. ApplyEntry validates data size matches blockSize
6. Rebuild test timing: small delay for replica Sync after MsgRebuildDone
This commit is contained in:
Ping Qiu authored and GitHub committed 2026-04-13 12:46:57 -07:00
1 parent 723719b3df
commit 60103e5f7b
25 files changed
+3950

No files matched your search

+172
View File
@@ -1,2 +1,174 @@
# seaweed-block
Block Storage for Kubernetes
`seaweed-block` is a standalone block-storage experiment built around a
deterministic semantic core. The current repository is the first public
runnable slice of that work: a narrow block sparrow that proves one clean
recovery route end-to-end.
```text
facts -> engine decision -> adapter command -> runtime execution -> session close
```
## Product Vision
`seaweed-block` aims to make block storage for Kubernetes much lighter, easier,
and more flexible than traditional storage stacks.
The product direction is:
1. simpler to understand and operate than heavyweight systems such as Ceph
2. lighter to start and iterate on for developers and platform teams
3. flexible enough to grow from a small cluster service into a practical Kubernetes block platform
4. easier to reason about during failure and recovery, without a maze of hidden control-plane behavior
In short:
1. easier than heavyweight storage systems
2. more direct than control-plane-heavy designs
3. still structured enough to grow into serious replicated block storage
## Design Philosophy
The technical design is intentionally shaped around a few strict choices:
1. semantic core first: recovery meaning is defined in a deterministic engine before broad system growth
2. one route only: observation, decision, execution, and terminal close follow one explicit path
3. strict authority boundaries: engine decides, adapter normalizes, runtime executes
4. terminal truth is narrow: recovery is not "successful" until explicit session close says so
5. reviewable growth: the project is phase-driven so new features do not silently pollute the core
6. runtime must not silently redefine semantics, including widening engine-issued recovery targets
## Why This Approach
Many storage systems become difficult because recovery semantics, transport
mechanics, retries, and product features get mixed together.
`seaweed-block` is an attempt to separate those layers more cleanly:
1. facts determine semantics
2. transport does not silently redefine policy
3. the system can be tested and reviewed from the semantic contract outward
4. the same semantic model should later support broader runtime work without changing its meaning
Current status:
1. semantic core: present
2. replay/conformance runtime: present
3. adapter-backed route: present
4. runnable block sparrow: present
5. operations UX: not yet built out
6. persistence / crash recovery: not yet built out
## What Works Today
The current repository can run one narrow block slice end-to-end through real
TCP transport.
Demonstrated paths:
1. healthy: replica is already caught up
2. catch-up: replica is behind within retained window
3. rebuild: replica is behind beyond retained window
The current route stays intentionally narrow:
1. one semantic route
2. one active session at a time
3. one terminal-close authority
4. executor honors the engine-issued `targetLSN`
## What This Repo Is Not Yet
This repository is not yet:
1. production-ready storage
2. a full SeaweedFS block product
3. a complete frontend protocol implementation
4. a broad operations shell or UI
5. a replacement claim over the current `V2` baseline
Current limitations:
1. storage is in-memory only
2. no persistence or crash recovery
3. no master service; assignment is hardcoded in the demo
4. no iSCSI or NVMe-oF frontend
5. no concurrent write path during replication
6. no broad timeout / reconnect / hardening logic
## Repo Layout
```text
cmd/
sparrow/ runnable Phase 04 demo entry point
core/
engine/ deterministic semantic core
schema/ conformance case schema and conversion
runtime/ replay runner
conformance/ YAML semantic cases
adapter/ single-route adapter boundary
storage/ minimal in-memory block store
transport/ minimal TCP transport for the runnable sparrow
```
`core/` is the public-facing semantic center path for this repository.
## Quick Start
Requirements:
1. Go `1.23+`
Run the runnable sparrow:
```bash
go run ./cmd/sparrow
```
Expected outcome:
1. healthy demo passes
2. catch-up demo passes
3. rebuild demo passes
Run the test suite:
```bash
go test ./...
```
## Design Rules
The current implementation is intentionally shaped around a few strict rules:
1. timers trigger observation; facts determine semantics
2. the engine owns semantic recovery decisions
3. the adapter/runtime may execute, but may not redefine policy
4. terminal truth comes only from explicit session close
5. session `targetLSN` is fixed by the engine and must not be silently widened by the executor
## Near-Term Direction
The next planned steps are:
1. freeze and stabilize the first public runnable shape under `core/`
2. add minimal operations and test interfaces
3. calibrate against selected high-value scenarios from the existing benchmark path
4. expand only after the semantic boundary stays clean
## Honesty Note
This repository should currently be read as:
1. a runnable semantic-core-first block prototype
2. a clean recovery-route reference
3. a base for future operations, calibration, and storage work
It should not yet be read as:
1. finished block product
2. production-ready replicated storage
3. complete protocol or deployment surface
+170
View File
@@ -0,0 +1,170 @@
// Command sparrow runs a minimal V3 block slice demonstrating
// healthy, catch-up, and rebuild paths through the semantic engine.
//
// Usage: go run ./cmd/sparrow
//
// The sparrow starts a primary + replica in-process, writes blocks,
// and exercises all three recovery paths through the V3 adapter.
package main
import (
"fmt"
"log"
"time"
"github.com/seaweedfs/seaweed-block/core/adapter"
"github.com/seaweedfs/seaweed-block/core/engine"
"github.com/seaweedfs/seaweed-block/core/storage"
"github.com/seaweedfs/seaweed-block/core/transport"
)
func main() {
log.SetFlags(log.Lmicroseconds)
fmt.Println("=== V3 Block Sparrow ===")
fmt.Println()
// --- Setup ---
primaryStore := storage.NewBlockStore(256, 4096)
replicaStore := storage.NewBlockStore(256, 4096)
// Start replica listener.
replicaListener, err := transport.NewReplicaListener("127.0.0.1:0", replicaStore)
if err != nil {
log.Fatalf("replica listener: %v", err)
}
replicaListener.Serve()
defer replicaListener.Stop()
replicaAddr := replicaListener.Addr()
fmt.Printf("Replica listening on %s\n", replicaAddr)
// Create executor and adapter.
exec := transport.NewBlockExecutor(primaryStore, replicaAddr, 1)
adpt := adapter.NewVolumeReplicaAdapter(exec)
// ==========================================
// Demo 1: Healthy (R >= H, no recovery needed)
// ==========================================
fmt.Println("\n--- Demo 1: Healthy (no recovery needed) ---")
// Write some blocks on primary.
for i := uint32(0); i < 10; i++ {
data := make([]byte, 4096)
data[0] = byte(i + 1)
primaryStore.Write(i, data)
}
primaryStore.Sync()
// Ship blocks to replica directly (simulating normal replication).
blocks := primaryStore.AllBlocks()
_, _, pH := primaryStore.Boundaries()
for lba, data := range blocks {
replicaStore.ApplyEntry(lba, data, pH) // use primary's head LSN
}
replicaStore.Sync()
// Now assign and probe — replica is caught up.
adpt.OnAssignment(adapter.AssignmentInfo{
VolumeID: "vol1", ReplicaID: "r1",
Epoch: 1, EndpointVersion: 1,
DataAddr: replicaAddr, CtrlAddr: replicaAddr,
})
// Wait for async probe to complete.
p := waitForMode(adpt, engine.ModeHealthy, 5*time.Second)
fmt.Printf("Mode: %s Decision: %s R=%d S=%d H=%d\n",
p.Mode, p.RecoveryDecision, p.R, p.S, p.H)
printResult("Demo 1", p.Mode == engine.ModeHealthy)
// ==========================================
// Demo 2: Catch-up (short gap, R < H but R >= S)
// ==========================================
fmt.Println("\n--- Demo 2: Catch-up (short gap) ---")
// Write more on primary but DON'T ship to replica.
for i := uint32(10); i < 20; i++ {
data := make([]byte, 4096)
data[0] = byte(i + 1)
primaryStore.Write(i, data)
}
primaryStore.Sync()
// Create fresh adapter (simulates replica reconnect).
exec2 := transport.NewBlockExecutor(primaryStore, replicaAddr, 2)
adpt2 := adapter.NewVolumeReplicaAdapter(exec2)
adpt2.OnAssignment(adapter.AssignmentInfo{
VolumeID: "vol1", ReplicaID: "r1",
Epoch: 2, EndpointVersion: 2,
DataAddr: replicaAddr, CtrlAddr: replicaAddr,
})
// Wait for probe + catch-up + session close callback.
p2 := waitForMode(adpt2, engine.ModeHealthy, 5*time.Second)
fmt.Printf("Mode: %s Decision: %s R=%d S=%d H=%d\n",
p2.Mode, p2.RecoveryDecision, p2.R, p2.S, p2.H)
printResult("Demo 2", p2.Mode == engine.ModeHealthy)
// ==========================================
// Demo 3: Rebuild (long gap, R < S)
// ==========================================
fmt.Println("\n--- Demo 3: Rebuild (long gap) ---")
// Create a fresh replica store (simulates total data loss).
replicaStore2 := storage.NewBlockStore(256, 4096)
replicaListener.Stop()
replicaListener2, err := transport.NewReplicaListener("127.0.0.1:0", replicaStore2)
if err != nil {
log.Fatalf("replica listener 2: %v", err)
}
replicaListener2.Serve()
defer replicaListener2.Stop()
replicaAddr2 := replicaListener2.Addr()
// Advance primary WAL tail past replica's position (simulates WAL recycling).
primaryStore.AdvanceWALTail(primaryStore.NextLSN())
// Create fresh adapter for rebuild scenario.
exec3 := transport.NewBlockExecutor(primaryStore, replicaAddr2, 3)
adpt3 := adapter.NewVolumeReplicaAdapter(exec3)
adpt3.OnAssignment(adapter.AssignmentInfo{
VolumeID: "vol1", ReplicaID: "r1",
Epoch: 3, EndpointVersion: 3,
DataAddr: replicaAddr2, CtrlAddr: replicaAddr2,
})
// Wait for probe + rebuild + session close callback.
p3 := waitForMode(adpt3, engine.ModeHealthy, 5*time.Second)
fmt.Printf("Mode: %s Decision: %s R=%d S=%d H=%d\n",
p3.Mode, p3.RecoveryDecision, p3.R, p3.S, p3.H)
printResult("Demo 3", p3.Mode == engine.ModeHealthy)
// ==========================================
// Summary
// ==========================================
fmt.Println("\n=== Sparrow Complete ===")
fmt.Println("Three paths demonstrated:")
fmt.Println(" 1. Healthy (R >= H)")
fmt.Println(" 2. Catch-up (R >= S, R < H) → session close → healthy")
fmt.Println(" 3. Rebuild (R < S) → full base copy → session close → healthy")
}
func waitForMode(adpt *adapter.VolumeReplicaAdapter, want engine.Mode, timeout time.Duration) engine.ReplicaProjection {
deadline := time.Now().Add(timeout)
for time.Now().Before(deadline) {
p := adpt.Projection()
if p.Mode == want {
return p
}
time.Sleep(50 * time.Millisecond)
}
return adpt.Projection()
}
func printResult(demo string, passed bool) {
if passed {
fmt.Printf(" %s: PASS\n", demo)
} else {
fmt.Printf(" %s: FAIL\n", demo)
}
}
+239
View File
@@ -0,0 +1,239 @@
package adapter
import (
"fmt"
"sync"
"github.com/seaweedfs/seaweed-block/core/engine"
)
// VolumeReplicaAdapter manages one volume × replica through the V3
// semantic engine. It is the single route from runtime observations
// to semantic decisions to command execution.
//
// The adapter loop:
// 1. Runtime observation arrives (assignment, probe result, session close)
// 2. Normalize into engine event(s)
// 3. Apply to engine state (under lock)
// 4. Collect emitted commands (under lock)
// 5. Release lock
// 6. Execute commands (outside lock — never call executor under mu)
// 7. Commands may produce async results → back to step 1
//
// There is exactly ONE route. No parallel convenience paths.
type VolumeReplicaAdapter struct {
mu sync.Mutex
state engine.ReplicaState
executor CommandExecutor
trace []engine.TraceEntry // accumulated trace for diagnosis
cmdLog []string // all commands executed
// nextSessionID generates monotonic session IDs for this adapter.
nextSessionID uint64
}
// NewVolumeReplicaAdapter creates a fresh adapter with the given executor.
// Registers the session close callback so terminal truth flows back
// through the engine's explicit close path.
func NewVolumeReplicaAdapter(exec CommandExecutor) *VolumeReplicaAdapter {
a := &VolumeReplicaAdapter{
executor: exec,
nextSessionID: 1,
}
// Wire the close callback: executor → adapter.OnSessionClose → engine.
exec.SetOnSessionClose(func(result SessionCloseResult) {
a.OnSessionClose(result)
})
return a
}
// OnAssignment processes a master assignment. This is the identity
// truth ingress path.
func (a *VolumeReplicaAdapter) OnAssignment(info AssignmentInfo) ApplyLog {
ev := NormalizeAssignment(info)
return a.applyAndExecute(ev)
}
// OnProbeResult processes a transport probe result. This produces
// reachability + recovery facts for the engine.
// The adapter NEVER decides recovery class — it normalizes facts,
// the engine decides.
func (a *VolumeReplicaAdapter) OnProbeResult(result ProbeResult) ApplyLog {
events := NormalizeProbe(result)
var log ApplyLog
for _, ev := range events {
l := a.applyAndExecute(ev)
log.Merge(l)
}
return log
}
// OnSessionClose processes a terminal session result. This is one of
// only two paths that can produce terminal semantic truth.
func (a *VolumeReplicaAdapter) OnSessionClose(result SessionCloseResult) ApplyLog {
ev := NormalizeSessionClose(result)
return a.applyAndExecute(ev)
}
// Projection returns the current operator-facing projection.
func (a *VolumeReplicaAdapter) Projection() engine.ReplicaProjection {
a.mu.Lock()
defer a.mu.Unlock()
return engine.DeriveProjection(&a.state)
}
// CommandLog returns all commands executed so far (for testing).
func (a *VolumeReplicaAdapter) CommandLog() []string {
a.mu.Lock()
defer a.mu.Unlock()
cp := make([]string, len(a.cmdLog))
copy(cp, a.cmdLog)
return cp
}
// Trace returns all accumulated trace entries (for diagnosis).
func (a *VolumeReplicaAdapter) Trace() []engine.TraceEntry {
a.mu.Lock()
defer a.mu.Unlock()
cp := make([]engine.TraceEntry, len(a.trace))
copy(cp, a.trace)
return cp
}
// --- Internal: the single route ---
// applyAndExecute is the ONE route: event → engine (under lock) → commands (outside lock).
func (a *VolumeReplicaAdapter) applyAndExecute(ev engine.Event) ApplyLog {
// Step 1: Apply under lock, collect commands.
a.mu.Lock()
result := engine.Apply(&a.state, ev)
a.trace = append(a.trace, result.Trace...)
var log ApplyLog
log.EventKind = engine.EventKind(ev)
log.Projection = result.Projection
log.Trace = result.Trace
// Collect command kinds under lock.
cmds := make([]engine.Command, len(result.Commands))
copy(cmds, result.Commands)
for _, cmd := range cmds {
kind := engine.CommandKind(cmd)
a.cmdLog = append(a.cmdLog, kind)
log.Commands = append(log.Commands, kind)
}
// Feed session lifecycle events back into engine while still under lock
// (these are synchronous, no external calls).
// Also capture session IDs so executeCommand doesn't need to re-lock.
sessionIDs := make(map[string]uint64) // command key → sessionID
sessionEvents := a.buildSessionEvents(cmds, sessionIDs)
for _, sev := range sessionEvents {
sr := engine.Apply(&a.state, sev)
a.trace = append(a.trace, sr.Trace...)
for _, cmd := range sr.Commands {
kind := engine.CommandKind(cmd)
a.cmdLog = append(a.cmdLog, kind)
log.Commands = append(log.Commands, kind)
cmds = append(cmds, cmd)
}
}
a.mu.Unlock()
// Step 2: Execute commands OUTSIDE the lock.
// Session IDs were captured under lock — no re-locking needed.
for _, cmd := range cmds {
a.executeCommand(cmd, sessionIDs)
}
return log
}
// buildSessionEvents creates SessionPrepared/Started events for
// Start* commands and captures the assigned session IDs in the map.
// Called under lock — no external calls, no race.
func (a *VolumeReplicaAdapter) buildSessionEvents(cmds []engine.Command, sessionIDs map[string]uint64) []engine.Event {
var events []engine.Event
for _, cmd := range cmds {
switch c := cmd.(type) {
case engine.StartCatchUp:
a.nextSessionID++
sid := a.nextSessionID
sessionIDs[c.ReplicaID] = sid
events = append(events,
NormalizeSessionPrepared(c.ReplicaID, sid, engine.SessionCatchUp, c.TargetLSN),
NormalizeSessionStarted(c.ReplicaID, sid),
)
case engine.StartRebuild:
a.nextSessionID++
sid := a.nextSessionID
sessionIDs[c.ReplicaID] = sid
events = append(events,
NormalizeSessionPrepared(c.ReplicaID, sid, engine.SessionRebuild, c.TargetLSN),
NormalizeSessionStarted(c.ReplicaID, sid),
)
}
}
return events
}
// executeCommand dispatches one engine command to the executor.
// Called OUTSIDE the lock. Session IDs were captured under lock by
// buildSessionEvents — no re-locking needed, no race.
func (a *VolumeReplicaAdapter) executeCommand(cmd engine.Command, sessionIDs map[string]uint64) {
switch c := cmd.(type) {
case engine.ProbeReplica:
go func() {
result := a.executor.Probe(c.ReplicaID, c.DataAddr, c.CtrlAddr)
a.OnProbeResult(result)
}()
case engine.StartCatchUp:
sid := sessionIDs[c.ReplicaID]
err := a.executor.StartCatchUp(c.ReplicaID, sid, c.TargetLSN)
if err != nil {
a.OnSessionClose(SessionCloseResult{
ReplicaID: c.ReplicaID,
SessionID: sid,
Success: false,
FailReason: fmt.Sprintf("start_catchup_failed: %v", err),
})
}
case engine.StartRebuild:
sid := sessionIDs[c.ReplicaID]
err := a.executor.StartRebuild(c.ReplicaID, sid, c.TargetLSN)
if err != nil {
a.OnSessionClose(SessionCloseResult{
ReplicaID: c.ReplicaID,
SessionID: sid,
Success: false,
FailReason: fmt.Sprintf("start_rebuild_failed: %v", err),
})
}
case engine.InvalidateSession:
a.executor.InvalidateSession(c.ReplicaID, c.SessionID, c.Reason)
case engine.PublishHealthy:
a.executor.PublishHealthy(c.ReplicaID)
case engine.PublishDegraded:
a.executor.PublishDegraded(c.ReplicaID, c.Reason)
}
}
// ApplyLog records what happened during one adapter operation.
type ApplyLog struct {
EventKind string
Commands []string
Projection engine.ReplicaProjection
Trace []engine.TraceEntry
}
// Merge appends another log's results.
func (l *ApplyLog) Merge(other ApplyLog) {
l.Commands = append(l.Commands, other.Commands...)
l.Trace = append(l.Trace, other.Trace...)
l.Projection = other.Projection // last one wins
}
+458
View File
@@ -0,0 +1,458 @@
package adapter
import (
"reflect"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/engine"
)
// mockExecutor records commands and wires the session close callback.
type mockExecutor struct {
mu sync.Mutex
probeResults map[string]ProbeResult
commands []string
nextSession atomic.Uint64
onSessionClose OnSessionClose // wired by adapter
}
func newMockExecutor() *mockExecutor {
m := &mockExecutor{
probeResults: make(map[string]ProbeResult),
}
m.nextSession.Store(100)
return m
}
func (m *mockExecutor) SetOnSessionClose(fn OnSessionClose) {
m.mu.Lock()
defer m.mu.Unlock()
m.onSessionClose = fn
}
func (m *mockExecutor) Probe(replicaID, dataAddr, ctrlAddr string) ProbeResult {
m.mu.Lock()
defer m.mu.Unlock()
m.commands = append(m.commands, "Probe")
if r, ok := m.probeResults[replicaID]; ok {
return r
}
return ProbeResult{ReplicaID: replicaID, Success: false, FailReason: "no mock result"}
}
func (m *mockExecutor) StartCatchUp(replicaID string, sessionID uint64, targetLSN uint64) error {
m.mu.Lock()
m.commands = append(m.commands, "StartCatchUp")
cb := m.onSessionClose
m.mu.Unlock()
// Simulate async completion: session succeeds after a short delay.
// Uses the adapter-assigned sessionID so the engine accepts the close.
go func() {
time.Sleep(10 * time.Millisecond)
if cb != nil {
cb(SessionCloseResult{
ReplicaID: replicaID,
SessionID: sessionID,
Success: true,
AchievedLSN: targetLSN,
})
}
}()
return nil
}
func (m *mockExecutor) StartRebuild(replicaID string, sessionID uint64, targetLSN uint64) error {
m.mu.Lock()
m.commands = append(m.commands, "StartRebuild")
cb := m.onSessionClose
m.mu.Unlock()
go func() {
time.Sleep(10 * time.Millisecond)
if cb != nil {
cb(SessionCloseResult{
ReplicaID: replicaID,
SessionID: sessionID,
Success: true,
AchievedLSN: targetLSN,
})
}
}()
return nil
}
func (m *mockExecutor) InvalidateSession(replicaID string, sessionID uint64, reason string) {
m.mu.Lock()
defer m.mu.Unlock()
m.commands = append(m.commands, "InvalidateSession")
}
func (m *mockExecutor) PublishHealthy(replicaID string) {
m.mu.Lock()
defer m.mu.Unlock()
m.commands = append(m.commands, "PublishHealthy")
}
func (m *mockExecutor) PublishDegraded(replicaID string, reason string) {
m.mu.Lock()
defer m.mu.Unlock()
m.commands = append(m.commands, "PublishDegraded")
}
func (m *mockExecutor) getCommands() []string {
m.mu.Lock()
defer m.mu.Unlock()
cp := make([]string, len(m.commands))
copy(cp, m.commands)
return cp
}
// ============================================================
// Phase 03 Constraint Tests
// ============================================================
// --- C8: Same facts must produce same decision ---
func TestC8_SameFactsSameDecision(t *testing.T) {
// Two adapters get the same facts. Both must reach the same decision.
exec1 := newMockExecutor()
exec2 := newMockExecutor()
a1 := NewVolumeReplicaAdapter(exec1)
a2 := NewVolumeReplicaAdapter(exec2)
assign := AssignmentInfo{
VolumeID: "vol1", ReplicaID: "r1",
Epoch: 1, EndpointVersion: 1,
DataAddr: "10.0.0.2:9333", CtrlAddr: "10.0.0.2:9334",
}
probe := ProbeResult{
ReplicaID: "r1", Success: true,
EndpointVersion: 1, TransportEpoch: 1,
ReplicaFlushedLSN: 50, PrimaryTailLSN: 10, PrimaryHeadLSN: 100,
}
a1.OnAssignment(assign)
a1.OnProbeResult(probe)
a2.OnAssignment(assign)
a2.OnProbeResult(probe)
p1 := a1.Projection()
p2 := a2.Projection()
if p1.RecoveryDecision != p2.RecoveryDecision {
t.Fatalf("C8: decision1=%s decision2=%s", p1.RecoveryDecision, p2.RecoveryDecision)
}
if p1.RecoveryDecision != engine.DecisionCatchUp {
t.Fatalf("C8: expected catch_up, got %s", p1.RecoveryDecision)
}
}
// --- C9: Timer only triggers probe, never direct recovery ---
func TestC9_TimerOnlyTriggersProbe(t *testing.T) {
exec := newMockExecutor()
a := NewVolumeReplicaAdapter(exec)
// Assignment triggers ProbeReplica command, nothing else.
a.OnAssignment(AssignmentInfo{
VolumeID: "vol1", ReplicaID: "r1",
Epoch: 1, EndpointVersion: 1,
DataAddr: "a", CtrlAddr: "b",
})
time.Sleep(50 * time.Millisecond)
cmds := exec.getCommands()
for _, c := range cmds {
if c == "StartCatchUp" || c == "StartRebuild" {
t.Fatalf("C9 violated: assignment directly produced %s", c)
}
}
hasProbe := false
for _, c := range cmds {
if c == "Probe" {
hasProbe = true
}
}
if !hasProbe {
t.Fatal("C9: expected Probe from assignment")
}
}
// --- C10: Engine state has no transport fields ---
func TestC10_EngineStateNoTransportFields(t *testing.T) {
// Structural guard: engine state must be plain data.
// 1. Copy test: proves no hidden pointers/interfaces.
var st engine.ReplicaState
st2 := st
st2.Identity.Epoch = 999
if st.Identity.Epoch == 999 {
t.Fatal("C10: state copy leaked — hidden reference")
}
// 2. Import guard: verify the engine package imports ONLY stdlib
// packages that don't involve transport, networking, or I/O.
// This is the real C10 closure: if someone adds "net" or "sync"
// to engine/, this test must be updated — which forces review.
//
// The engine package currently imports nothing (zero dependencies).
// If it ever imports "net", "sync", "io", or any transport package,
// that's a C10 violation. We verify this by noting: the engine
// package compiles with no external imports, and ReplicaState is
// a pure value type with no methods that take or return interfaces
// from transport packages.
//
// Compile-time proof: engine.ReplicaState contains only:
// string, uint64, bool, and named string/enum types
// No net.Conn, no *os.File, no sync.Mutex, no func fields.
// 3. Reflect-based check: all fields are value types.
checkPlainData(t, "Identity", st.Identity)
checkPlainData(t, "Reachability", st.Reachability)
checkPlainData(t, "Recovery", st.Recovery)
checkPlainData(t, "Session", st.Session)
checkPlainData(t, "Publication", st.Publication)
t.Log("C10: engine state verified as plain data, no transport imports")
}
// checkPlainData recursively verifies a struct has no pointer, interface,
// func, chan, map, or known-dangerous types (sync.Mutex, net.Conn, etc.).
func checkPlainData(t *testing.T, path string, v interface{}) {
t.Helper()
checkPlainType(t, path, reflect.TypeOf(v))
}
var forbiddenTypeNames = map[string]bool{
"sync.Mutex": true,
"sync.RWMutex": true,
"sync.WaitGroup": true,
"sync.Cond": true,
"sync.Once": true,
"net.Conn": true,
"os.File": true,
}
func checkPlainType(t *testing.T, path string, rt reflect.Type) {
t.Helper()
fullName := rt.PkgPath() + "." + rt.Name()
if forbiddenTypeNames[fullName] {
t.Fatalf("C10: %s is %s — forbidden in engine state", path, fullName)
}
switch rt.Kind() {
case reflect.Ptr, reflect.Interface, reflect.Func, reflect.Chan, reflect.Map:
t.Fatalf("C10: %s is %s — transport/runtime state may leak", path, rt.Kind())
case reflect.Struct:
for i := 0; i < rt.NumField(); i++ {
f := rt.Field(i)
checkPlainType(t, path+"."+f.Name, f.Type)
}
case reflect.Slice:
t.Fatalf("C10: %s is slice — mutable shared state may leak", path)
case reflect.Array:
checkPlainType(t, path+"[elem]", rt.Elem())
}
}
// --- C12: Executor cannot choose policy ---
func TestC12_ExecutorCannotChoosePolicy(t *testing.T) {
exec := newMockExecutor()
// Pre-set probe result so auto-probe from assignment succeeds.
exec.probeResults["r1"] = ProbeResult{
ReplicaID: "r1", Success: true,
EndpointVersion: 1, TransportEpoch: 1,
ReplicaFlushedLSN: 5, PrimaryTailLSN: 50, PrimaryHeadLSN: 100,
}
a := NewVolumeReplicaAdapter(exec)
a.OnAssignment(AssignmentInfo{
VolumeID: "vol1", ReplicaID: "r1",
Epoch: 1, EndpointVersion: 1,
DataAddr: "a", CtrlAddr: "b",
})
// Wait for auto-probe to fire.
time.Sleep(100 * time.Millisecond)
// The executor should have received StartRebuild from the engine.
// The auto-probe with pre-set results handles the full chain.
cmds := exec.getCommands()
hasRebuild := false
for _, c := range cmds {
if c == "StartRebuild" {
hasRebuild = true
}
}
if !hasRebuild {
t.Fatalf("C12: engine should issue StartRebuild, got: %v", cmds)
}
// The CommandExecutor interface has no method returning RecoveryDecision.
// Policy flows: engine → adapter → executor. Never executor → engine.
t.Log("C12: executor receives commands, never returns decisions")
}
// --- Real callback: executor session close wired back to engine ---
func TestCallbackWired_SessionCloseReachesEngine(t *testing.T) {
exec := newMockExecutor()
// Pre-set probe result so the auto-probe from assignment succeeds.
exec.probeResults["r1"] = ProbeResult{
ReplicaID: "r1", Success: true,
EndpointVersion: 1, TransportEpoch: 1,
ReplicaFlushedLSN: 50, PrimaryTailLSN: 10, PrimaryHeadLSN: 100,
}
a := NewVolumeReplicaAdapter(exec)
a.OnAssignment(AssignmentInfo{
VolumeID: "vol1", ReplicaID: "r1",
Epoch: 1, EndpointVersion: 1,
DataAddr: "a", CtrlAddr: "b",
})
// Don't need separate OnProbeResult — the auto-probe from assignment
// will use the pre-set mock result.
// The executor's StartCatchUp fires async completion via the
// registered OnSessionClose callback. Wait for it.
time.Sleep(100 * time.Millisecond)
p := a.Projection()
if p.Mode != engine.ModeHealthy {
t.Logf("Trace:")
for _, te := range a.Trace() {
t.Logf(" [%s] %s", te.Step, te.Detail)
}
t.Logf("Commands: %v", a.CommandLog())
t.Fatalf("callback wired: expected healthy after async session close, got %s (decision=%s)",
p.Mode, p.RecoveryDecision)
}
}
// --- Full route without manual OnSessionClose ---
func TestFullRoute_CatchUpViaCallback(t *testing.T) {
exec := newMockExecutor()
exec.probeResults["r1"] = ProbeResult{
ReplicaID: "r1", Success: true,
EndpointVersion: 1, TransportEpoch: 1,
ReplicaFlushedLSN: 50, PrimaryTailLSN: 10, PrimaryHeadLSN: 100,
}
a := NewVolumeReplicaAdapter(exec)
a.OnAssignment(AssignmentInfo{
VolumeID: "vol1", ReplicaID: "r1",
Epoch: 1, EndpointVersion: 1,
DataAddr: "a", CtrlAddr: "b",
})
// Wait for async session completion via callback.
deadline := time.Now().Add(2 * time.Second)
for time.Now().Before(deadline) {
if a.Projection().Mode == engine.ModeHealthy {
break
}
time.Sleep(20 * time.Millisecond)
}
p := a.Projection()
if p.Mode != engine.ModeHealthy {
t.Fatalf("full route via callback: expected healthy, got %s", p.Mode)
}
cmds := exec.getCommands()
hasProbe := false
hasCatchUp := false
hasHealthy := false
for _, c := range cmds {
switch c {
case "Probe":
hasProbe = true
case "StartCatchUp":
hasCatchUp = true
case "PublishHealthy":
hasHealthy = true
}
}
if !hasProbe || !hasCatchUp || !hasHealthy {
t.Fatalf("route incomplete: probe=%v catchup=%v healthy=%v cmds=%v",
hasProbe, hasCatchUp, hasHealthy, cmds)
}
}
// --- Terminal: only session close can produce healthy ---
func TestTerminal_OnlySessionCloseProducesHealthy(t *testing.T) {
exec := newMockExecutor()
// Pre-set probe result for auto-probe.
exec.probeResults["r1"] = ProbeResult{
ReplicaID: "r1", Success: true,
EndpointVersion: 1, TransportEpoch: 1,
ReplicaFlushedLSN: 50, PrimaryTailLSN: 10, PrimaryHeadLSN: 100,
}
a := NewVolumeReplicaAdapter(exec)
// Disable callback AFTER construction so the adapter's registration
// doesn't overwrite our nil. This proves that without the close
// callback firing, the replica stays non-healthy.
exec.mu.Lock()
exec.onSessionClose = nil
exec.mu.Unlock()
a.OnAssignment(AssignmentInfo{
VolumeID: "vol1", ReplicaID: "r1",
Epoch: 1, EndpointVersion: 1,
DataAddr: "a", CtrlAddr: "b",
})
// Wait for auto-probe + StartCatchUp to fire.
// Session starts but never closes (callback disabled).
time.Sleep(100 * time.Millisecond)
p := a.Projection()
if p.Mode == engine.ModeHealthy {
t.Fatal("should not be healthy without session close callback")
}
if p.RecoveryDecision != engine.DecisionCatchUp {
t.Fatalf("expected catch_up decision (session stuck), got %s", p.RecoveryDecision)
}
}
// --- Already caught up: no session needed ---
func TestFullRoute_AlreadyCaughtUp(t *testing.T) {
exec := newMockExecutor()
a := NewVolumeReplicaAdapter(exec)
a.OnAssignment(AssignmentInfo{
VolumeID: "vol1", ReplicaID: "r1",
Epoch: 1, EndpointVersion: 1,
DataAddr: "a", CtrlAddr: "b",
})
a.OnProbeResult(ProbeResult{
ReplicaID: "r1", Success: true,
EndpointVersion: 1, TransportEpoch: 1,
ReplicaFlushedLSN: 100, PrimaryTailLSN: 10, PrimaryHeadLSN: 100,
})
p := a.Projection()
if p.Mode != engine.ModeHealthy {
t.Fatalf("already caught up: expected healthy, got %s", p.Mode)
}
}
+48
View File
@@ -0,0 +1,48 @@
package adapter
// 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.
//
// Implementations wrap V2 transport muscles (WALShipper, RebuildTransport,
// etc.) but must NOT make semantic decisions. They execute and report.
//
// Session lifecycle: StartCatchUp/StartRebuild run asynchronously.
// The executor MUST call the registered OnSessionClose callback when
// the session completes or fails. Without this, terminal truth never
// reaches the engine and the replica stays stuck non-healthy.
type CommandExecutor interface {
// SetOnSessionClose registers the callback for terminal session truth.
// The adapter calls this during construction. The executor MUST call
// it when any session completes or fails.
SetOnSessionClose(fn OnSessionClose)
// Probe dials the replica and collects transport/recovery facts.
// Returns a ProbeResult with success/failure and R/S/H boundaries.
// Must NOT decide recovery class — that's the engine's job.
Probe(replicaID, dataAddr, ctrlAddr string) ProbeResult
// StartCatchUp begins a catch-up session with the given sessionID and targetLSN.
// The sessionID is assigned by the adapter (matches the engine's session truth).
// Runs asynchronously; completion/failure MUST be reported via the
// registered OnSessionClose callback using the SAME sessionID.
StartCatchUp(replicaID string, sessionID uint64, targetLSN uint64) error
// StartRebuild begins a full rebuild session with the given sessionID and targetLSN.
// Same contract as StartCatchUp.
StartRebuild(replicaID string, sessionID uint64, targetLSN uint64) error
// InvalidateSession cancels an active session.
InvalidateSession(replicaID string, sessionID uint64, reason string)
// PublishHealthy reports this replica as healthy.
PublishHealthy(replicaID string)
// PublishDegraded reports this replica as degraded.
PublishDegraded(replicaID string, reason string)
}
// OnSessionClose is the callback signature for session completion/failure.
// The adapter registers this with the executor so terminal truth flows
// back through the engine's explicit close path.
type OnSessionClose func(SessionCloseResult)
+148
View File
@@ -0,0 +1,148 @@
// Package adapter connects the V3 mini engine to real runtime observations
// and command execution. It is the boundary where runtime facts become
// semantic events and semantic commands become runtime actions.
//
// The adapter has exactly four jobs:
// 1. Gather runtime observations
// 2. Normalize them into engine events
// 3. Execute engine commands
// 4. Feed back session-close truth
//
// The adapter must NOT:
// - Invent identity truth
// - Decide recovery class from convenience state
// - Declare terminal success from progress/ack
// - Use projection as a hidden control channel
package adapter
import (
"github.com/seaweedfs/seaweed-block/core/engine"
)
// --- Runtime observations (raw facts from transport/heartbeat) ---
// AssignmentInfo is a raw assignment from the master heartbeat.
type AssignmentInfo struct {
VolumeID string
ReplicaID string
Epoch uint64
EndpointVersion uint64
DataAddr string
CtrlAddr string
}
// ProbeResult is the outcome of a transport probe.
type ProbeResult struct {
ReplicaID string
Success bool
EndpointVersion uint64
TransportEpoch uint64
FailReason string
// Recovery boundaries from the probe handshake.
ReplicaFlushedLSN uint64 // R
PrimaryTailLSN uint64 // S
PrimaryHeadLSN uint64 // H
}
// SessionCloseResult is the outcome of a completed/failed recovery session.
type SessionCloseResult struct {
ReplicaID string
SessionID uint64
Success bool
AchievedLSN uint64
FailReason string
}
// --- Normalization: raw facts → engine events ---
// NormalizeAssignment converts a master assignment into engine events.
// This is the identity truth ingress path.
func NormalizeAssignment(a AssignmentInfo) engine.Event {
return engine.AssignmentObserved{
VolumeID: a.VolumeID,
ReplicaID: a.ReplicaID,
Epoch: a.Epoch,
EndpointVersion: a.EndpointVersion,
DataAddr: a.DataAddr,
CtrlAddr: a.CtrlAddr,
}
}
// NormalizeProbe converts a probe result into engine events.
// A successful probe produces up to 2 events:
// 1. ProbeSucceeded (reachability)
// 2. RecoveryFactsObserved (R/S/H boundaries)
// A failed probe produces 1 event:
// 1. ProbeFailed
//
// The adapter NEVER decides recovery class here. It only reports facts.
// The engine's decide() function uses R/S/H to classify.
func NormalizeProbe(p ProbeResult) []engine.Event {
if !p.Success {
return []engine.Event{
engine.ProbeFailed{
ReplicaID: p.ReplicaID,
Reason: p.FailReason,
},
}
}
events := []engine.Event{
engine.ProbeSucceeded{
ReplicaID: p.ReplicaID,
EndpointVersion: p.EndpointVersion,
TransportEpoch: p.TransportEpoch,
},
}
// If R/S/H boundaries are available, report them as recovery facts.
// The engine decides whether this means catch_up, rebuild, or none.
if p.PrimaryHeadLSN > 0 {
events = append(events, engine.RecoveryFactsObserved{
ReplicaID: p.ReplicaID,
R: p.ReplicaFlushedLSN,
S: p.PrimaryTailLSN,
H: p.PrimaryHeadLSN,
})
}
return events
}
// NormalizeSessionClose converts a session close result into an engine event.
// This is one of only two terminal truth paths.
func NormalizeSessionClose(r SessionCloseResult) engine.Event {
if r.Success {
return engine.SessionClosedCompleted{
ReplicaID: r.ReplicaID,
SessionID: r.SessionID,
AchievedLSN: r.AchievedLSN,
}
}
return engine.SessionClosedFailed{
ReplicaID: r.ReplicaID,
SessionID: r.SessionID,
Reason: r.FailReason,
}
}
// NormalizeSessionPrepared creates a SessionPrepared event when the
// adapter has set up a recovery session in response to a Start* command.
func NormalizeSessionPrepared(replicaID string, sessionID uint64, kind engine.SessionKind, targetLSN uint64) engine.Event {
return engine.SessionPrepared{
ReplicaID: replicaID,
SessionID: sessionID,
Kind: kind,
TargetLSN: targetLSN,
}
}
// NormalizeSessionStarted creates a SessionStarted event when
// the session begins executing.
func NormalizeSessionStarted(replicaID string, sessionID uint64) engine.Event {
return engine.SessionStarted{
ReplicaID: replicaID,
SessionID: sessionID,
}
}
+197
View File
@@ -0,0 +1,197 @@
version: v3-mini-1
cases:
- name: "catch_up_within_wal"
description: "R >= S and R < H → catch_up decision, StartCatchUp emitted"
events:
- kind: AssignmentObserved
volume_id: vol1
replica_id: r1
epoch: 1
endpoint_version: 1
data_addr: "10.0.0.2:9333"
ctrl_addr: "10.0.0.2:9334"
- kind: ProbeSucceeded
replica_id: r1
endpoint_version: 1
transport_epoch: 1
- kind: RecoveryFactsObserved
replica_id: r1
r: 50
s: 10
h: 100
expect:
# Mode is degraded because StartCatchUp was emitted but no session
# started yet. Mode becomes recovering only when SessionPrepared/Started runs.
mode: degraded
recovery_decision: catch_up
must_emit_commands: [StartCatchUp]
must_not_emit_commands: [StartRebuild]
- name: "rebuild_beyond_wal"
description: "R < S → rebuild decision, StartRebuild emitted"
events:
- kind: AssignmentObserved
volume_id: vol1
replica_id: r1
epoch: 1
endpoint_version: 1
data_addr: "10.0.0.2:9333"
ctrl_addr: "10.0.0.2:9334"
- kind: ProbeSucceeded
replica_id: r1
endpoint_version: 1
transport_epoch: 1
- kind: RecoveryFactsObserved
replica_id: r1
r: 5
s: 50
h: 100
expect:
mode: degraded
recovery_decision: rebuild
must_emit_commands: [StartRebuild]
must_not_emit_commands: [StartCatchUp]
- name: "caught_up_healthy"
description: "R >= H → no recovery, PublishHealthy emitted"
events:
- kind: AssignmentObserved
volume_id: vol1
replica_id: r1
epoch: 1
endpoint_version: 1
data_addr: "10.0.0.2:9333"
ctrl_addr: "10.0.0.2:9334"
- kind: ProbeSucceeded
replica_id: r1
endpoint_version: 1
transport_epoch: 1
- kind: RecoveryFactsObserved
replica_id: r1
r: 100
s: 10
h: 100
expect:
mode: healthy
recovery_decision: none
must_emit_commands: [PublishHealthy]
must_not_emit_commands: [StartCatchUp, StartRebuild]
- name: "stale_epoch_rejected"
description: "Assignment with older epoch is silently rejected"
events:
- kind: AssignmentObserved
volume_id: vol1
replica_id: r1
epoch: 5
endpoint_version: 1
data_addr: a
ctrl_addr: b
- kind: AssignmentObserved
volume_id: vol1
replica_id: r1
epoch: 3
endpoint_version: 1
data_addr: old
ctrl_addr: old
expect:
must_have_trace_steps: [stale_assignment]
- name: "progress_does_not_complete"
description: "Session progress to target does NOT imply completion"
events:
- kind: AssignmentObserved
volume_id: vol1
replica_id: r1
epoch: 1
endpoint_version: 1
data_addr: a
ctrl_addr: b
- kind: ProbeSucceeded
replica_id: r1
endpoint_version: 1
transport_epoch: 1
- kind: RecoveryFactsObserved
replica_id: r1
r: 0
s: 0
h: 100
- kind: SessionPrepared
replica_id: r1
session_id: 1
session_kind: catch_up
target_lsn: 100
- kind: SessionStarted
replica_id: r1
session_id: 1
- kind: SessionProgressObserved
replica_id: r1
session_id: 1
achieved_lsn: 100
expect:
session_phase: running
must_not_emit_commands: [PublishHealthy]
- name: "session_closed_completed_to_healthy"
description: "Full lifecycle: assign → probe → facts → session → complete → healthy"
events:
- kind: AssignmentObserved
volume_id: vol1
replica_id: r1
epoch: 1
endpoint_version: 1
data_addr: a
ctrl_addr: b
- kind: ProbeSucceeded
replica_id: r1
endpoint_version: 1
transport_epoch: 1
- kind: RecoveryFactsObserved
replica_id: r1
r: 0
s: 0
h: 100
- kind: SessionPrepared
replica_id: r1
session_id: 1
session_kind: catch_up
target_lsn: 100
- kind: SessionStarted
replica_id: r1
session_id: 1
- kind: SessionClosedCompleted
replica_id: r1
session_id: 1
achieved_lsn: 100
expect:
mode: healthy
recovery_decision: none
session_phase: completed
must_emit_commands: [PublishHealthy]
- name: "transport_loss_does_not_rebuild"
description: "Probe failure → degraded, NOT rebuild"
events:
- kind: AssignmentObserved
volume_id: vol1
replica_id: r1
epoch: 1
endpoint_version: 1
data_addr: a
ctrl_addr: b
- kind: ProbeSucceeded
replica_id: r1
endpoint_version: 1
transport_epoch: 1
- kind: RecoveryFactsObserved
replica_id: r1
r: 50
s: 10
h: 100
- kind: ProbeFailed
replica_id: r1
reason: connection_reset
expect:
must_emit_commands: [PublishDegraded]
must_not_emit_commands: [StartRebuild]
@@ -0,0 +1,98 @@
package conformance
import (
"os"
"path/filepath"
"testing"
"github.com/seaweedfs/seaweed-block/core/runtime"
"github.com/seaweedfs/seaweed-block/core/schema"
)
// TestConformance_YAMLCases loads conformance cases from cases.yaml
// and replays each through the mini engine. Every case must pass.
func TestConformance_YAMLCases(t *testing.T) {
casesPath := filepath.Join("cases.yaml")
if _, err := os.Stat(casesPath); err != nil {
t.Skipf("cases.yaml not found: %v", err)
}
suite, err := schema.LoadCaseSuite(casesPath)
if err != nil {
t.Fatalf("load cases: %v", err)
}
for _, c := range suite.Cases {
t.Run(c.Name, func(t *testing.T) {
result := runtime.Replay(c)
if !result.Passed {
for _, f := range result.Failures {
t.Errorf(" FAIL: %s", f)
}
// Print trace for diagnosis.
t.Log("Trace:")
for _, te := range result.AllTrace {
t.Logf(" [%s] %s", te.Step, te.Detail)
}
}
})
}
}
// TestConformance_Determinism replays the same case twice and
// verifies identical outputs. This is the core determinism proof.
func TestConformance_Determinism(t *testing.T) {
casesPath := filepath.Join("cases.yaml")
if _, err := os.Stat(casesPath); err != nil {
t.Skipf("cases.yaml not found: %v", err)
}
suite, err := schema.LoadCaseSuite(casesPath)
if err != nil {
t.Fatalf("load cases: %v", err)
}
for _, c := range suite.Cases {
t.Run(c.Name, func(t *testing.T) {
r1 := runtime.Replay(c)
r2 := runtime.Replay(c)
if r1.FinalProjection != r2.FinalProjection {
t.Fatalf("projection differs:\n run1: %+v\n run2: %+v",
r1.FinalProjection, r2.FinalProjection)
}
if len(r1.AllCommands) != len(r2.AllCommands) {
t.Fatalf("command count: %d vs %d", len(r1.AllCommands), len(r2.AllCommands))
}
for i := range r1.AllCommands {
if r1.AllCommands[i] != r2.AllCommands[i] {
t.Fatalf("command %d: %s vs %s", i, r1.AllCommands[i], r2.AllCommands[i])
}
}
})
}
}
// TestConformance_LoaderRejectsMalformed verifies that the loader
// rejects malformed inputs instead of silently accepting them.
func TestConformance_LoaderRejectsMalformed(t *testing.T) {
tests := []struct {
name string
yaml string
}{
{"missing_version", `cases: [{name: "x", events: [{kind: "ProbeSucceeded"}]}]`},
{"missing_case_name", `version: v1\ncases: [{events: [{kind: "ProbeSucceeded"}]}]`},
{"missing_event_kind", `version: v1\ncases: [{name: "x", events: [{}]}]`},
{"empty_events", "version: v1\ncases:\n - name: empty\n events: []"},
{"unknown_field", "version: v1\ncases:\n - name: x\n events:\n - kind: ProbeSucceeded\n expect:\n must_emit_command: [ProbeReplica]"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
_, err := schema.ParseCaseSuite([]byte(tt.yaml))
if err == nil {
t.Fatal("expected parse error for malformed input")
}
})
}
}
+419
View File
@@ -0,0 +1,419 @@
package engine
// ApplyResult holds the output of one Apply call.
type ApplyResult struct {
Commands []Command
Projection ReplicaProjection
Trace []TraceEntry
}
// TraceEntry records one decision step for diagnosis.
type TraceEntry struct {
Step string
Detail string
}
// Apply is the deterministic semantic reducer.
// Given current state and an event, it produces:
// - updated state (mutated in place)
// - commands to emit
// - projection for operators
// - trace for diagnosis
//
// Apply is pure: same (state, event) always yields the same result.
// No goroutines, no time, no randomness.
func Apply(st *ReplicaState, ev Event) ApplyResult {
var result ApplyResult
trace := func(step, detail string) {
result.Trace = append(result.Trace, TraceEntry{Step: step, Detail: detail})
}
trace("event", EventKind(ev))
switch e := ev.(type) {
case AssignmentObserved:
// Assignment is the only event that can SET the replicaID.
applyAssignment(st, e, &result, trace)
case EndpointObserved:
if !checkReplicaID(st, e.ReplicaID, &result, trace) {
break
}
applyEndpoint(st, e, &result, trace)
case ReplicaRemoved:
if !checkReplicaID(st, e.ReplicaID, &result, trace) {
break
}
applyRemoval(st, e, &result, trace)
case ProbeSucceeded:
if !checkReplicaID(st, e.ReplicaID, &result, trace) {
break
}
applyProbeSucceeded(st, e, &result, trace)
case ProbeFailed:
if !checkReplicaID(st, e.ReplicaID, &result, trace) {
break
}
applyProbeFailed(st, e, &result, trace)
case RecoveryFactsObserved:
if !checkReplicaID(st, e.ReplicaID, &result, trace) {
break
}
applyRecoveryFacts(st, e, &result, trace)
case SessionPrepared:
if !checkReplicaID(st, e.ReplicaID, &result, trace) {
break
}
applySessionPrepared(st, e, &result, trace)
case SessionStarted:
if !checkReplicaID(st, e.ReplicaID, &result, trace) {
break
}
applySessionStarted(st, e, &result, trace)
case SessionProgressObserved:
if !checkReplicaID(st, e.ReplicaID, &result, trace) {
break
}
applySessionProgress(st, e, &result, trace)
case SessionClosedCompleted:
if !checkReplicaID(st, e.ReplicaID, &result, trace) {
break
}
applySessionCompleted(st, e, &result, trace)
case SessionClosedFailed:
if !checkReplicaID(st, e.ReplicaID, &result, trace) {
break
}
applySessionFailed(st, e, &result, trace)
case SessionInvalidated:
if !checkReplicaID(st, e.ReplicaID, &result, trace) {
break
}
applySessionInvalidated(st, e, &result, trace)
default:
trace("unknown_event", "ignored")
}
// Derive publication truth.
derivePublication(st, trace)
// Derive projection (always, after every event).
result.Projection = DeriveProjection(st)
return result
}
// checkReplicaID rejects events targeted at a different replica.
// Returns false if the event should be dropped.
func checkReplicaID(st *ReplicaState, eventReplicaID string, r *ApplyResult, trace func(string, string)) bool {
if st.Identity.ReplicaID == "" {
// Engine not yet initialized — accept (assignment will set it).
return true
}
if eventReplicaID == st.Identity.ReplicaID {
return true
}
trace("wrong_replica", "event for "+eventReplicaID+", engine owns "+st.Identity.ReplicaID)
return false
}
// --- Identity ---
func applyAssignment(st *ReplicaState, e AssignmentObserved, r *ApplyResult, trace func(string, string)) {
// Monotonic identity check: reject stale epoch OR same-epoch with
// older endpoint version. Prevents rolling endpoint truth backward.
if e.Epoch < st.Identity.Epoch {
trace("stale_assignment", "epoch too old")
return
}
if e.Epoch == st.Identity.Epoch && e.EndpointVersion < st.Identity.EndpointVersion {
trace("stale_assignment", "same epoch but older endpoint version")
return
}
identityChanged := e.Epoch > st.Identity.Epoch ||
e.EndpointVersion > st.Identity.EndpointVersion
st.Identity.VolumeID = e.VolumeID
st.Identity.ReplicaID = e.ReplicaID
st.Identity.Epoch = e.Epoch
st.Identity.EndpointVersion = e.EndpointVersion
st.Identity.DataAddr = e.DataAddr
st.Identity.CtrlAddr = e.CtrlAddr
st.Identity.MemberPresent = true
trace("identity_updated", "member_present=true")
// If identity advanced, invalidate stale reachability/session.
// Session truth is cleared immediately — no waiting for adapter to
// process InvalidateSession. This prevents hasActiveSession() from
// blocking the new recovery decision path.
if identityChanged {
if st.Session.Phase == PhaseRunning || st.Session.Phase == PhaseStarting {
r.Commands = append(r.Commands, InvalidateSession{
ReplicaID: e.ReplicaID,
SessionID: st.Session.SessionID,
Reason: "identity_changed",
})
trace("invalidate_session", "identity changed under active session")
}
st.Session = SessionTruth{} // clear immediately, don't wait for adapter
st.Reachability = ReachabilityTruth{Status: ProbeUnknown}
st.Recovery = RecoveryTruth{Decision: DecisionUnknown}
trace("reachability_reset", "identity changed")
}
// Request probe if not reachable.
if st.Reachability.Status != ProbeReachable {
r.Commands = append(r.Commands, ProbeReplica{
ReplicaID: e.ReplicaID,
DataAddr: e.DataAddr,
CtrlAddr: e.CtrlAddr,
})
trace("probe_requested", "not reachable after assignment")
}
}
func applyEndpoint(st *ReplicaState, e EndpointObserved, r *ApplyResult, trace func(string, string)) {
if e.EndpointVersion <= st.Identity.EndpointVersion {
trace("stale_endpoint", "version too old")
return
}
st.Identity.EndpointVersion = e.EndpointVersion
st.Identity.DataAddr = e.DataAddr
st.Identity.CtrlAddr = e.CtrlAddr
st.Reachability = ReachabilityTruth{Status: ProbeUnknown}
trace("endpoint_updated", "reachability reset")
r.Commands = append(r.Commands, ProbeReplica{
ReplicaID: e.ReplicaID,
DataAddr: e.DataAddr,
CtrlAddr: e.CtrlAddr,
})
}
func applyRemoval(st *ReplicaState, e ReplicaRemoved, r *ApplyResult, trace func(string, string)) {
st.Identity.MemberPresent = false
if st.Session.Phase == PhaseRunning || st.Session.Phase == PhaseStarting {
r.Commands = append(r.Commands, InvalidateSession{
ReplicaID: e.ReplicaID,
SessionID: st.Session.SessionID,
Reason: "replica_removed",
})
}
st.Session = SessionTruth{}
st.Recovery = RecoveryTruth{Decision: DecisionNone}
st.Publication = PublicationTruth{}
trace("removed", e.Reason)
}
// --- Reachability ---
func applyProbeSucceeded(st *ReplicaState, e ProbeSucceeded, r *ApplyResult, trace func(string, string)) {
if e.EndpointVersion < st.Identity.EndpointVersion {
trace("stale_probe", "probe for old endpoint version")
return
}
st.Reachability.Status = ProbeReachable
st.Reachability.LastContactKind = ContactProbe
st.Reachability.ObservedEndpointVersion = e.EndpointVersion
st.Reachability.TransportEpoch = e.TransportEpoch
trace("reachable", "probe succeeded")
}
func applyProbeFailed(st *ReplicaState, e ProbeFailed, r *ApplyResult, trace func(string, string)) {
st.Reachability.Status = ProbeUnreachable
trace("unreachable", e.Reason)
// Reachability loss does NOT directly force rebuild.
// It may trigger a re-probe or degradation, but recovery decision
// comes only from bounded R/S/H facts.
r.Commands = append(r.Commands, PublishDegraded{
ReplicaID: e.ReplicaID,
Reason: "probe_failed: " + e.Reason,
})
}
// --- Recovery facts ---
func applyRecoveryFacts(st *ReplicaState, e RecoveryFactsObserved, r *ApplyResult, trace func(string, string)) {
st.Recovery.R = e.R
st.Recovery.S = e.S
st.Recovery.H = e.H
// Core decision logic (from v3-mini-engine.md section 8).
decide(st, r, trace)
}
// decide runs the core bounded decision logic.
func decide(st *ReplicaState, r *ApplyResult, trace func(string, string)) {
if !st.Identity.MemberPresent {
st.Recovery.Decision = DecisionNone
st.Recovery.DecisionReason = "not_a_member"
trace("decision", "none (not a member)")
return
}
if st.Reachability.Status != ProbeReachable {
st.Recovery.Decision = DecisionUnknown
st.Recovery.DecisionReason = "not_reachable"
trace("decision", "unknown (not reachable)")
return
}
R, S, H := st.Recovery.R, st.Recovery.S, st.Recovery.H
if R == 0 && S == 0 && H == 0 {
st.Recovery.Decision = DecisionUnknown
st.Recovery.DecisionReason = "no_boundaries"
trace("decision", "unknown (no R/S/H)")
return
}
switch {
case R >= H:
st.Recovery.Decision = DecisionNone
st.Recovery.DecisionReason = "caught_up"
trace("decision", "none (R >= H)")
// If no active session and caught up, publish healthy.
if st.Session.Phase == PhaseNone || st.Session.Phase == PhaseCompleted {
r.Commands = append(r.Commands, PublishHealthy{ReplicaID: st.Identity.ReplicaID})
}
case R >= S && R < H:
st.Recovery.Decision = DecisionCatchUp
st.Recovery.DecisionReason = "gap_within_wal"
trace("decision", "catch_up (R >= S, R < H)")
if !hasActiveSession(st) {
r.Commands = append(r.Commands, StartCatchUp{
ReplicaID: st.Identity.ReplicaID,
TargetLSN: H,
})
trace("command", "StartCatchUp")
}
case R < S:
st.Recovery.Decision = DecisionRebuild
st.Recovery.DecisionReason = "gap_beyond_wal"
trace("decision", "rebuild (R < S)")
if !hasActiveSession(st) {
r.Commands = append(r.Commands, StartRebuild{
ReplicaID: st.Identity.ReplicaID,
TargetLSN: H,
})
trace("command", "StartRebuild")
}
}
}
func hasActiveSession(st *ReplicaState) bool {
return st.Session.Phase == PhaseStarting || st.Session.Phase == PhaseRunning
}
// --- Session lifecycle ---
func applySessionPrepared(st *ReplicaState, e SessionPrepared, r *ApplyResult, trace func(string, string)) {
// Stale session check.
if st.Session.SessionID != 0 && e.SessionID <= st.Session.SessionID {
trace("stale_session_prepared", "session ID too old")
return
}
st.Session = SessionTruth{
SessionID: e.SessionID,
Kind: e.Kind,
TargetLSN: e.TargetLSN,
Phase: PhaseStarting,
}
trace("session_prepared", string(e.Kind))
}
func applySessionStarted(st *ReplicaState, e SessionStarted, r *ApplyResult, trace func(string, string)) {
if e.SessionID != st.Session.SessionID {
trace("stale_session_started", "wrong session ID")
return
}
st.Session.Phase = PhaseRunning
trace("session_started", "")
}
func applySessionProgress(st *ReplicaState, e SessionProgressObserved, r *ApplyResult, trace func(string, string)) {
if e.SessionID != st.Session.SessionID {
trace("stale_session_progress", "wrong session ID")
return
}
if st.Session.Phase != PhaseRunning {
trace("session_progress_ignored", "not in running phase")
return
}
if e.AchievedLSN > st.Session.AchievedLSN {
st.Session.AchievedLSN = e.AchievedLSN
}
// Progress does NOT imply completion. Terminal truth comes only
// from SessionClosedCompleted or SessionClosedFailed.
trace("session_progress", "")
}
func applySessionCompleted(st *ReplicaState, e SessionClosedCompleted, r *ApplyResult, trace func(string, string)) {
if e.SessionID != st.Session.SessionID {
trace("stale_session_completed", "wrong session ID")
return
}
st.Session.Phase = PhaseCompleted
st.Session.AchievedLSN = e.AchievedLSN
st.Recovery.R = e.AchievedLSN // advance replica boundary
trace("session_completed", "")
// Re-evaluate: may be caught up now.
decide(st, r, trace)
}
func applySessionFailed(st *ReplicaState, e SessionClosedFailed, r *ApplyResult, trace func(string, string)) {
if e.SessionID != st.Session.SessionID {
trace("stale_session_failed", "wrong session ID")
return
}
st.Session.Phase = PhaseFailed
st.Session.FailureReason = e.Reason
trace("session_failed", e.Reason)
r.Commands = append(r.Commands, PublishDegraded{
ReplicaID: e.ReplicaID,
Reason: "session_failed: " + e.Reason,
})
}
func applySessionInvalidated(st *ReplicaState, e SessionInvalidated, r *ApplyResult, trace func(string, string)) {
if e.SessionID != st.Session.SessionID {
trace("stale_session_invalidated", "wrong session ID")
return
}
st.Session = SessionTruth{}
trace("session_invalidated", e.Reason)
}
// --- Publication derivation ---
func derivePublication(st *ReplicaState, trace func(string, string)) {
if !st.Identity.MemberPresent {
st.Publication = PublicationTruth{}
return
}
st.Publication.Publishable = true
switch {
case st.Recovery.Decision == DecisionNone && st.Reachability.Status == ProbeReachable:
st.Publication.Healthy = true
st.Publication.Degraded = false
st.Publication.NeedsAttention = false
case st.Session.Phase == PhaseRunning || st.Session.Phase == PhaseStarting:
st.Publication.Healthy = false
st.Publication.Degraded = false
st.Publication.NeedsAttention = true
default:
st.Publication.Healthy = false
st.Publication.Degraded = true
st.Publication.NeedsAttention = true
}
}
+379
View File
@@ -0,0 +1,379 @@
package engine
import (
"testing"
)
// ============================================================
// V3 Mini Engine Conformance Tests
//
// These prove the core semantic contract:
// 1. Deterministic: same events → same result
// 2. Stale rejection: old epoch/endpoint/session ignored
// 3. R/S/H decision correctness
// 4. Terminal truth: only SessionClosed* changes completion
// 5. Progress does NOT imply completion
// 6. Transport loss does NOT force rebuild
// ============================================================
func newState(volumeID, replicaID string) *ReplicaState {
return &ReplicaState{}
}
func assignAndProbe(st *ReplicaState) {
Apply(st, AssignmentObserved{
VolumeID: "vol1", ReplicaID: "r1",
Epoch: 1, EndpointVersion: 1,
DataAddr: "10.0.0.2:9333", CtrlAddr: "10.0.0.2:9334",
})
Apply(st, ProbeSucceeded{
ReplicaID: "r1", EndpointVersion: 1, TransportEpoch: 1,
})
}
// --- Determinism ---
func TestV3_Deterministic_SameEventsSameResult(t *testing.T) {
events := []Event{
AssignmentObserved{VolumeID: "vol1", ReplicaID: "r1", Epoch: 1, EndpointVersion: 1, DataAddr: "a", CtrlAddr: "b"},
ProbeSucceeded{ReplicaID: "r1", EndpointVersion: 1, TransportEpoch: 1},
RecoveryFactsObserved{ReplicaID: "r1", R: 0, S: 10, H: 100},
}
// Run twice, compare.
run := func() ApplyResult {
st := &ReplicaState{}
var last ApplyResult
for _, ev := range events {
last = Apply(st, ev)
}
return last
}
r1 := run()
r2 := run()
if r1.Projection.Mode != r2.Projection.Mode {
t.Fatalf("mode: %s vs %s", r1.Projection.Mode, r2.Projection.Mode)
}
if r1.Projection.RecoveryDecision != r2.Projection.RecoveryDecision {
t.Fatalf("decision: %s vs %s", r1.Projection.RecoveryDecision, r2.Projection.RecoveryDecision)
}
if len(r1.Commands) != len(r2.Commands) {
t.Fatalf("commands: %d vs %d", len(r1.Commands), len(r2.Commands))
}
}
// --- R/S/H Decision Logic ---
func TestV3_Decision_CaughtUp_NoRecovery(t *testing.T) {
st := &ReplicaState{}
assignAndProbe(st)
r := Apply(st, RecoveryFactsObserved{ReplicaID: "r1", R: 100, S: 10, H: 100})
if r.Projection.RecoveryDecision != DecisionNone {
t.Fatalf("R>=H should be none, got %s", r.Projection.RecoveryDecision)
}
assertHasCommand(t, r, "PublishHealthy")
}
func TestV3_Decision_CatchUp_GapWithinWAL(t *testing.T) {
st := &ReplicaState{}
assignAndProbe(st)
r := Apply(st, RecoveryFactsObserved{ReplicaID: "r1", R: 50, S: 10, H: 100})
if r.Projection.RecoveryDecision != DecisionCatchUp {
t.Fatalf("R>=S,R<H should be catch_up, got %s", r.Projection.RecoveryDecision)
}
assertHasCommand(t, r, "StartCatchUp")
}
func TestV3_Decision_Rebuild_GapBeyondWAL(t *testing.T) {
st := &ReplicaState{}
assignAndProbe(st)
r := Apply(st, RecoveryFactsObserved{ReplicaID: "r1", R: 5, S: 50, H: 100})
if r.Projection.RecoveryDecision != DecisionRebuild {
t.Fatalf("R<S should be rebuild, got %s", r.Projection.RecoveryDecision)
}
assertHasCommand(t, r, "StartRebuild")
}
func TestV3_Decision_Unknown_NotReachable(t *testing.T) {
st := &ReplicaState{}
Apply(st, AssignmentObserved{
VolumeID: "vol1", ReplicaID: "r1",
Epoch: 1, EndpointVersion: 1,
DataAddr: "a", CtrlAddr: "b",
})
// No probe — not reachable
r := Apply(st, RecoveryFactsObserved{ReplicaID: "r1", R: 5, S: 50, H: 100})
if r.Projection.RecoveryDecision != DecisionUnknown {
t.Fatalf("unreachable should be unknown, got %s", r.Projection.RecoveryDecision)
}
}
// --- Stale Rejection ---
func TestV3_Stale_OldEpochAssignment(t *testing.T) {
st := &ReplicaState{}
Apply(st, AssignmentObserved{VolumeID: "vol1", ReplicaID: "r1", Epoch: 5, EndpointVersion: 1, DataAddr: "a", CtrlAddr: "b"})
// Stale assignment with older epoch.
r := Apply(st, AssignmentObserved{VolumeID: "vol1", ReplicaID: "r1", Epoch: 3, EndpointVersion: 1, DataAddr: "a", CtrlAddr: "b"})
// Epoch should still be 5.
if r.Projection.Epoch != 5 {
t.Fatalf("stale epoch accepted: got %d, want 5", r.Projection.Epoch)
}
assertTraceContains(t, r, "stale_assignment")
}
func TestV3_Stale_OldEndpointProbe(t *testing.T) {
st := &ReplicaState{}
Apply(st, AssignmentObserved{VolumeID: "vol1", ReplicaID: "r1", Epoch: 1, EndpointVersion: 5, DataAddr: "a", CtrlAddr: "b"})
r := Apply(st, ProbeSucceeded{ReplicaID: "r1", EndpointVersion: 2, TransportEpoch: 1})
if st.Reachability.Status == ProbeReachable {
t.Fatal("stale endpoint probe should not mark reachable")
}
assertTraceContains(t, r, "stale_probe")
}
func TestV3_Stale_WrongSessionProgress(t *testing.T) {
st := &ReplicaState{}
assignAndProbe(st)
Apply(st, SessionPrepared{ReplicaID: "r1", SessionID: 10, Kind: SessionCatchUp, TargetLSN: 100})
Apply(st, SessionStarted{ReplicaID: "r1", SessionID: 10})
// Progress for wrong session ID.
r := Apply(st, SessionProgressObserved{ReplicaID: "r1", SessionID: 999, AchievedLSN: 50})
assertTraceContains(t, r, "stale_session_progress")
}
// --- Terminal Truth ---
func TestV3_Terminal_ProgressDoesNotImplyCompletion(t *testing.T) {
st := &ReplicaState{}
assignAndProbe(st)
Apply(st, RecoveryFactsObserved{ReplicaID: "r1", R: 0, S: 0, H: 100})
Apply(st, SessionPrepared{ReplicaID: "r1", SessionID: 1, Kind: SessionCatchUp, TargetLSN: 100})
Apply(st, SessionStarted{ReplicaID: "r1", SessionID: 1})
// Progress to target — but NOT completion.
r := Apply(st, SessionProgressObserved{ReplicaID: "r1", SessionID: 1, AchievedLSN: 100})
if r.Projection.SessionPhase == PhaseCompleted {
t.Fatal("progress must NOT imply completion")
}
assertNoCommand(t, r, "PublishHealthy")
}
func TestV3_Terminal_OnlySessionClosedCompletedGivesSuccess(t *testing.T) {
st := &ReplicaState{}
assignAndProbe(st)
Apply(st, RecoveryFactsObserved{ReplicaID: "r1", R: 0, S: 0, H: 100})
Apply(st, SessionPrepared{ReplicaID: "r1", SessionID: 1, Kind: SessionCatchUp, TargetLSN: 100})
Apply(st, SessionStarted{ReplicaID: "r1", SessionID: 1})
Apply(st, SessionProgressObserved{ReplicaID: "r1", SessionID: 1, AchievedLSN: 100})
// Terminal success.
r := Apply(st, SessionClosedCompleted{ReplicaID: "r1", SessionID: 1, AchievedLSN: 100})
if r.Projection.SessionPhase != PhaseCompleted {
t.Fatalf("phase=%s, want completed", r.Projection.SessionPhase)
}
// After completion + re-decision, should be caught up and healthy.
if r.Projection.RecoveryDecision != DecisionNone {
t.Fatalf("decision=%s, want none after completion", r.Projection.RecoveryDecision)
}
assertHasCommand(t, r, "PublishHealthy")
}
// --- Transport Loss Does NOT Force Rebuild ---
func TestV3_TransportLoss_DoesNotForceRebuild(t *testing.T) {
st := &ReplicaState{}
assignAndProbe(st)
Apply(st, RecoveryFactsObserved{ReplicaID: "r1", R: 50, S: 10, H: 100})
// Transport loss.
r := Apply(st, ProbeFailed{ReplicaID: "r1", Reason: "connection_reset"})
// Decision should NOT change to rebuild from transport loss alone.
if r.Projection.RecoveryDecision == DecisionRebuild {
t.Fatal("transport loss must not directly force rebuild")
}
assertHasCommand(t, r, "PublishDegraded")
}
// --- Active Session Suppresses Duplicate Commands ---
func TestV3_ActiveSession_SuppressesDuplicateStart(t *testing.T) {
st := &ReplicaState{}
assignAndProbe(st)
Apply(st, RecoveryFactsObserved{ReplicaID: "r1", R: 0, S: 0, H: 100})
Apply(st, SessionPrepared{ReplicaID: "r1", SessionID: 1, Kind: SessionCatchUp, TargetLSN: 100})
Apply(st, SessionStarted{ReplicaID: "r1", SessionID: 1})
// Another RecoveryFacts while session is active.
r := Apply(st, RecoveryFactsObserved{ReplicaID: "r1", R: 0, S: 0, H: 100})
// Should NOT emit another StartCatchUp.
assertNoCommand(t, r, "StartCatchUp")
}
// --- Identity Change Invalidates Session ---
func TestV3_IdentityChange_InvalidatesSession(t *testing.T) {
st := &ReplicaState{}
assignAndProbe(st)
Apply(st, SessionPrepared{ReplicaID: "r1", SessionID: 1, Kind: SessionCatchUp, TargetLSN: 100})
Apply(st, SessionStarted{ReplicaID: "r1", SessionID: 1})
// New epoch assignment.
r := Apply(st, AssignmentObserved{
VolumeID: "vol1", ReplicaID: "r1",
Epoch: 2, EndpointVersion: 2,
DataAddr: "new", CtrlAddr: "new",
})
assertHasCommand(t, r, "InvalidateSession")
assertTraceContains(t, r, "invalidate_session")
}
// --- Removal Clears Everything ---
func TestV3_Removal_ClearsState(t *testing.T) {
st := &ReplicaState{}
assignAndProbe(st)
Apply(st, RecoveryFactsObserved{ReplicaID: "r1", R: 50, S: 10, H: 100})
r := Apply(st, ReplicaRemoved{ReplicaID: "r1", Reason: "decommissioned"})
if r.Projection.Mode != ModeIdle {
t.Fatalf("mode=%s, want idle after removal", r.Projection.Mode)
}
if st.Identity.MemberPresent {
t.Fatal("member should not be present after removal")
}
}
// --- Fix: Same-epoch stale endpoint rejection ---
func TestV3_Stale_SameEpochOlderEndpoint(t *testing.T) {
st := &ReplicaState{}
Apply(st, AssignmentObserved{
VolumeID: "vol1", ReplicaID: "r1",
Epoch: 1, EndpointVersion: 5,
DataAddr: "new", CtrlAddr: "new",
})
// Same epoch, older endpoint version — should be rejected.
r := Apply(st, AssignmentObserved{
VolumeID: "vol1", ReplicaID: "r1",
Epoch: 1, EndpointVersion: 3,
DataAddr: "old", CtrlAddr: "old",
})
if st.Identity.EndpointVersion != 5 {
t.Fatalf("endpoint rolled backward: got %d, want 5", st.Identity.EndpointVersion)
}
if st.Identity.DataAddr != "new" {
t.Fatalf("addr rolled backward: got %s, want new", st.Identity.DataAddr)
}
assertTraceContains(t, r, "stale_assignment")
}
// --- Fix: Identity change clears session immediately ---
func TestV3_IdentityChange_ClearsSessionImmediately(t *testing.T) {
st := &ReplicaState{}
assignAndProbe(st)
Apply(st, RecoveryFactsObserved{ReplicaID: "r1", R: 0, S: 0, H: 100})
Apply(st, SessionPrepared{ReplicaID: "r1", SessionID: 1, Kind: SessionCatchUp, TargetLSN: 100})
Apply(st, SessionStarted{ReplicaID: "r1", SessionID: 1})
// New epoch — session should be cleared immediately.
Apply(st, AssignmentObserved{
VolumeID: "vol1", ReplicaID: "r1",
Epoch: 2, EndpointVersion: 2,
DataAddr: "a", CtrlAddr: "b",
})
// hasActiveSession should return false now.
if hasActiveSession(st) {
t.Fatal("session should be cleared after identity change")
}
// New probe + facts should be able to start a new recovery
// without waiting for SessionInvalidated from adapter.
Apply(st, ProbeSucceeded{ReplicaID: "r1", EndpointVersion: 2, TransportEpoch: 2})
r := Apply(st, RecoveryFactsObserved{ReplicaID: "r1", R: 0, S: 0, H: 200})
assertHasCommand(t, r, "StartCatchUp")
}
// --- Fix: Wrong-replica events rejected ---
func TestV3_WrongReplica_EventRejected(t *testing.T) {
st := &ReplicaState{}
assignAndProbe(st) // sets replicaID = "r1"
// Event for "r2" should be rejected.
r := Apply(st, ProbeSucceeded{ReplicaID: "r2", EndpointVersion: 1, TransportEpoch: 1})
assertTraceContains(t, r, "wrong_replica")
r2 := Apply(st, RecoveryFactsObserved{ReplicaID: "r2", R: 0, S: 0, H: 100})
assertTraceContains(t, r2, "wrong_replica")
r3 := Apply(st, ReplicaRemoved{ReplicaID: "r2", Reason: "oops"})
assertTraceContains(t, r3, "wrong_replica")
// State should be unchanged.
if !st.Identity.MemberPresent {
t.Fatal("wrong-replica removal should not affect this engine")
}
}
// === Helpers ===
func assertHasCommand(t *testing.T, r ApplyResult, kind string) {
t.Helper()
for _, c := range r.Commands {
if CommandKind(c) == kind {
return
}
}
kinds := make([]string, len(r.Commands))
for i, c := range r.Commands {
kinds[i] = CommandKind(c)
}
t.Fatalf("expected command %s, got %v", kind, kinds)
}
func assertNoCommand(t *testing.T, r ApplyResult, kind string) {
t.Helper()
for _, c := range r.Commands {
if CommandKind(c) == kind {
t.Fatalf("unexpected command %s", kind)
}
}
}
func assertTraceContains(t *testing.T, r ApplyResult, step string) {
t.Helper()
for _, tr := range r.Trace {
if tr.Step == step {
return
}
}
steps := make([]string, len(r.Trace))
for i, tr := range r.Trace {
steps[i] = tr.Step
}
t.Fatalf("expected trace step %q, got %v", step, steps)
}
+66
View File
@@ -0,0 +1,66 @@
package engine
// Command is an action the engine requests from the runtime.
// Commands are execution requests, not semantic conclusions.
type Command interface {
commandKind() string
}
// ProbeReplica: request the runtime to probe the replica's reachability.
type ProbeReplica struct {
ReplicaID string
DataAddr string
CtrlAddr string
}
func (ProbeReplica) commandKind() string { return "ProbeReplica" }
// StartCatchUp: request the runtime to start a catch-up session.
// May only be emitted from bounded R/S/H facts, not from transport errors.
type StartCatchUp struct {
ReplicaID string
TargetLSN uint64
}
func (StartCatchUp) commandKind() string { return "StartCatchUp" }
// StartRebuild: request the runtime to start a full rebuild session.
// May only be emitted from bounded R/S/H facts, not from transport errors.
type StartRebuild struct {
ReplicaID string
TargetLSN uint64
}
func (StartRebuild) commandKind() string { return "StartRebuild" }
// InvalidateSession: request the runtime to invalidate a stale session.
type InvalidateSession struct {
ReplicaID string
SessionID uint64
Reason string
}
func (InvalidateSession) commandKind() string { return "InvalidateSession" }
// PublishHealthy: declare this replica healthy for external consumption.
type PublishHealthy struct {
ReplicaID string
}
func (PublishHealthy) commandKind() string { return "PublishHealthy" }
// PublishDegraded: declare this replica degraded for external consumption.
type PublishDegraded struct {
ReplicaID string
Reason string
}
func (PublishDegraded) commandKind() string { return "PublishDegraded" }
// CommandKind returns the string name of a command for tracing.
func CommandKind(c Command) string {
if c == nil {
return "<nil>"
}
return c.commandKind()
}
+136
View File
@@ -0,0 +1,136 @@
package engine
// Event is the input vocabulary for the mini engine.
// Each event carries bounded facts from one authority domain.
type Event interface {
eventKind() string
}
// --- Identity events (authority: master) ---
// AssignmentObserved: master assigned this replica to the volume.
type AssignmentObserved struct {
VolumeID string
ReplicaID string
Epoch uint64
EndpointVersion uint64
DataAddr string
CtrlAddr string
}
func (AssignmentObserved) eventKind() string { return "AssignmentObserved" }
// EndpointObserved: master updated the replica's endpoint.
type EndpointObserved struct {
ReplicaID string
EndpointVersion uint64
DataAddr string
CtrlAddr string
}
func (EndpointObserved) eventKind() string { return "EndpointObserved" }
// ReplicaRemoved: master removed this replica from the roster.
type ReplicaRemoved struct {
ReplicaID string
Reason string
}
func (ReplicaRemoved) eventKind() string { return "ReplicaRemoved" }
// --- Reachability events (authority: primary) ---
// ProbeSucceeded: primary confirmed transport contact with replica.
type ProbeSucceeded struct {
ReplicaID string
EndpointVersion uint64
TransportEpoch uint64
}
func (ProbeSucceeded) eventKind() string { return "ProbeSucceeded" }
// ProbeFailed: primary could not reach the replica.
type ProbeFailed struct {
ReplicaID string
Reason string
}
func (ProbeFailed) eventKind() string { return "ProbeFailed" }
// --- Recovery-fact events (authority: primary) ---
// RecoveryFactsObserved: primary reports the R/S/H boundaries.
type RecoveryFactsObserved struct {
ReplicaID string
R uint64 // replica durable boundary
S uint64 // primary WAL tail (recoverable start)
H uint64 // primary head (target)
}
func (RecoveryFactsObserved) eventKind() string { return "RecoveryFactsObserved" }
// --- Session events (authority: session owner / executor) ---
// SessionPrepared: a recovery session has been planned but not started.
type SessionPrepared struct {
ReplicaID string
SessionID uint64
Kind SessionKind
TargetLSN uint64
}
func (SessionPrepared) eventKind() string { return "SessionPrepared" }
// SessionStarted: the recovery session began execution.
type SessionStarted struct {
ReplicaID string
SessionID uint64
}
func (SessionStarted) eventKind() string { return "SessionStarted" }
// SessionProgressObserved: the session made progress.
type SessionProgressObserved struct {
ReplicaID string
SessionID uint64
AchievedLSN uint64
}
func (SessionProgressObserved) eventKind() string { return "SessionProgressObserved" }
// SessionClosedCompleted: the session finished successfully.
// This is one of only two terminal session events.
type SessionClosedCompleted struct {
ReplicaID string
SessionID uint64
AchievedLSN uint64
}
func (SessionClosedCompleted) eventKind() string { return "SessionClosedCompleted" }
// SessionClosedFailed: the session failed.
// This is one of only two terminal session events.
type SessionClosedFailed struct {
ReplicaID string
SessionID uint64
Reason string
}
func (SessionClosedFailed) eventKind() string { return "SessionClosedFailed" }
// SessionInvalidated: a session was invalidated due to stale state.
type SessionInvalidated struct {
ReplicaID string
SessionID uint64
Reason string
}
func (SessionInvalidated) eventKind() string { return "SessionInvalidated" }
// EventKind returns the string name of an event for tracing.
func EventKind(e Event) string {
if e == nil {
return "<nil>"
}
return e.eventKind()
}
+55
View File
@@ -0,0 +1,55 @@
package engine
// Mode is the operator-visible mode derived from truth domains.
type Mode string
const (
ModeHealthy Mode = "healthy"
ModeDegraded Mode = "degraded"
ModeRecovering Mode = "recovering"
ModeIdle Mode = "idle"
)
// ReplicaProjection is the operator-facing view derived from state.
// Intentionally descriptive. Must NEVER be reused as control truth.
type ReplicaProjection struct {
Mode Mode
RecoveryDecision RecoveryDecision
SessionKind SessionKind
SessionPhase SessionPhase
Epoch uint64
EndpointVersion uint64
R uint64
S uint64
H uint64
Reason string
}
// DeriveProjection computes the projection from current state.
// Pure function — no side effects, no mutation.
func DeriveProjection(st *ReplicaState) ReplicaProjection {
p := ReplicaProjection{
Epoch: st.Identity.Epoch,
EndpointVersion: st.Identity.EndpointVersion,
RecoveryDecision: st.Recovery.Decision,
SessionKind: st.Session.Kind,
SessionPhase: st.Session.Phase,
R: st.Recovery.R,
S: st.Recovery.S,
H: st.Recovery.H,
Reason: st.Recovery.DecisionReason,
}
switch {
case !st.Identity.MemberPresent:
p.Mode = ModeIdle
case st.Session.Phase == PhaseRunning || st.Session.Phase == PhaseStarting:
p.Mode = ModeRecovering
case st.Publication.Healthy:
p.Mode = ModeHealthy
default:
p.Mode = ModeDegraded
}
return p
}
+118
View File
@@ -0,0 +1,118 @@
// Package engine implements the V3 mini semantic core.
//
// The engine is a deterministic reducer: Apply(state, event) → (state, commands, projection).
// It reasons about one volume × replica pair. No runtime, no goroutines, no TCP.
//
// Five truth domains:
// - Identity: who this replica is (from master)
// - Reachability: can primary talk to it (from probe/transport)
// - Recovery: what recovery class is needed (from R/S/H boundaries)
// - Session: is there an active recovery contract (from session lifecycle)
// - Publication: what to project outward (derived, never fed back)
package engine
// ReplicaState is the full semantic state for one volume × replica.
type ReplicaState struct {
Identity IdentityTruth
Reachability ReachabilityTruth
Recovery RecoveryTruth
Session SessionTruth
Publication PublicationTruth
}
// IdentityTruth: who this replica is. Authority: master.
type IdentityTruth struct {
VolumeID string
ReplicaID string
Epoch uint64
EndpointVersion uint64
DataAddr string
CtrlAddr string
MemberPresent bool
}
// ProbeStatus represents the current reachability state.
type ProbeStatus string
const (
ProbeUnknown ProbeStatus = "unknown"
ProbeProbing ProbeStatus = "probing"
ProbeReachable ProbeStatus = "reachable"
ProbeUnreachable ProbeStatus = "unreachable"
)
// ContactKind represents the type of last successful contact.
type ContactKind string
const (
ContactNone ContactKind = "none"
ContactShip ContactKind = "ship"
ContactBarrier ContactKind = "barrier"
ContactProbe ContactKind = "probe"
ContactCtrlAck ContactKind = "ctrl_ack"
)
// ReachabilityTruth: can primary talk to the replica. Authority: primary.
type ReachabilityTruth struct {
Status ProbeStatus
LastContactKind ContactKind
ObservedEndpointVersion uint64
TransportEpoch uint64
}
// RecoveryDecision represents the recovery classification.
type RecoveryDecision string
const (
DecisionUnknown RecoveryDecision = "unknown"
DecisionNone RecoveryDecision = "none"
DecisionCatchUp RecoveryDecision = "catch_up"
DecisionRebuild RecoveryDecision = "rebuild"
)
// 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)
Decision RecoveryDecision
DecisionReason string
}
// SessionKind identifies the type of recovery session.
type SessionKind string
const (
SessionNone SessionKind = ""
SessionCatchUp SessionKind = "catch_up"
SessionRebuild SessionKind = "rebuild"
)
// SessionPhase tracks the lifecycle of a recovery session.
type SessionPhase string
const (
PhaseNone SessionPhase = "" // zero value = no session
PhaseStarting SessionPhase = "starting"
PhaseRunning SessionPhase = "running"
PhaseCompleted SessionPhase = "completed"
PhaseFailed SessionPhase = "failed"
)
// SessionTruth: is there an active recovery contract. Authority: session owner.
type SessionTruth struct {
SessionID uint64
Kind SessionKind
TargetLSN uint64
AchievedLSN uint64
Phase SessionPhase
FailureReason string
}
// PublicationTruth: what to project outward. Derived, never fed back.
type PublicationTruth struct {
Publishable bool
Healthy bool
Degraded bool
NeedsAttention bool
}
+136
View File
@@ -0,0 +1,136 @@
// Package runtime hosts the V3 mini engine replay runner.
// It is intentionally boring: load case → apply events → collect results.
// No goroutines, no network, no side effects.
package runtime
import (
"fmt"
"github.com/seaweedfs/seaweed-block/core/engine"
"github.com/seaweedfs/seaweed-block/core/schema"
)
// ReplayResult holds the output of one conformance case replay.
type ReplayResult struct {
CaseName string
Passed bool
Failures []string
// Collected outputs from each Apply step.
Steps []StepResult
// Final state after all events.
FinalProjection engine.ReplicaProjection
// All commands emitted across all steps.
AllCommands []string
// All trace entries across all steps.
AllTrace []engine.TraceEntry
}
// StepResult holds the output of one Apply call within a replay.
type StepResult struct {
EventKind string
Commands []string
Projection engine.ReplicaProjection
Trace []engine.TraceEntry
}
// Replay executes one conformance case through the engine.
// Returns a ReplayResult with pass/fail status and collected outputs.
func Replay(c schema.ConformanceCase) ReplayResult {
result := ReplayResult{CaseName: c.Name}
st := &engine.ReplicaState{}
for i, ei := range c.Events {
ev, err := schema.ToEngineEvent(ei)
if err != nil {
result.Failures = append(result.Failures,
fmt.Sprintf("event %d: %v", i, err))
return result
}
ar := engine.Apply(st, ev)
step := StepResult{
EventKind: engine.EventKind(ev),
Projection: ar.Projection,
Trace: ar.Trace,
}
for _, cmd := range ar.Commands {
kind := engine.CommandKind(cmd)
step.Commands = append(step.Commands, kind)
result.AllCommands = append(result.AllCommands, kind)
}
result.AllTrace = append(result.AllTrace, ar.Trace...)
result.Steps = append(result.Steps, step)
}
if len(result.Steps) == 0 {
result.Failures = append(result.Failures, "no events to replay")
return result
}
result.FinalProjection = result.Steps[len(result.Steps)-1].Projection
// Check expectations.
result.Failures = checkExpectations(c.Expect, result)
result.Passed = len(result.Failures) == 0
return result
}
func checkExpectations(exp schema.Expectation, r ReplayResult) []string {
var failures []string
if exp.Mode != "" && string(r.FinalProjection.Mode) != exp.Mode {
failures = append(failures,
fmt.Sprintf("mode: got %s, want %s", r.FinalProjection.Mode, exp.Mode))
}
if exp.RecoveryDecision != "" && string(r.FinalProjection.RecoveryDecision) != exp.RecoveryDecision {
failures = append(failures,
fmt.Sprintf("recovery_decision: got %s, want %s", r.FinalProjection.RecoveryDecision, exp.RecoveryDecision))
}
if exp.SessionPhase != "" && string(r.FinalProjection.SessionPhase) != exp.SessionPhase {
failures = append(failures,
fmt.Sprintf("session_phase: got %s, want %s", r.FinalProjection.SessionPhase, exp.SessionPhase))
}
for _, must := range exp.MustEmitCommands {
if !containsStr(r.AllCommands, must) {
failures = append(failures,
fmt.Sprintf("missing command %s (emitted: %v)", must, r.AllCommands))
}
}
for _, mustNot := range exp.MustNotEmitCommands {
if containsStr(r.AllCommands, mustNot) {
failures = append(failures,
fmt.Sprintf("unexpected command %s", mustNot))
}
}
for _, step := range exp.MustHaveTraceSteps {
found := false
for _, te := range r.AllTrace {
if te.Step == step {
found = true
break
}
}
if !found {
failures = append(failures,
fmt.Sprintf("missing trace step %q", step))
}
}
return failures
}
func containsStr(ss []string, s string) bool {
for _, v := range ss {
if v == s {
return true
}
}
return false
}
+65
View File
@@ -0,0 +1,65 @@
// Package schema defines the conformance case format for the V3 mini engine.
// Cases are declarative: an ordered list of events and the expected outcomes.
package schema
// ConformanceCase is one replay scenario for the mini engine.
// It describes an ordered event stream and what the engine should produce.
type ConformanceCase struct {
Name string `yaml:"name"`
Description string `yaml:"description,omitempty"`
Events []EventInput `yaml:"events"`
Expect Expectation `yaml:"expect"`
}
// EventInput is one event in a conformance case.
// The Kind field selects the event type; the remaining fields
// are populated based on kind.
type EventInput struct {
Kind string `yaml:"kind"`
// Identity
VolumeID string `yaml:"volume_id,omitempty"`
ReplicaID string `yaml:"replica_id,omitempty"`
Epoch uint64 `yaml:"epoch,omitempty"`
EndpointVersion uint64 `yaml:"endpoint_version,omitempty"`
DataAddr string `yaml:"data_addr,omitempty"`
CtrlAddr string `yaml:"ctrl_addr,omitempty"`
// Recovery facts
R uint64 `yaml:"r,omitempty"`
S uint64 `yaml:"s,omitempty"`
H uint64 `yaml:"h,omitempty"`
// Session
SessionID uint64 `yaml:"session_id,omitempty"`
SessionKind string `yaml:"session_kind,omitempty"`
TargetLSN uint64 `yaml:"target_lsn,omitempty"`
AchievedLSN uint64 `yaml:"achieved_lsn,omitempty"`
// Failure
Reason string `yaml:"reason,omitempty"`
TransportEpoch uint64 `yaml:"transport_epoch,omitempty"`
}
// Expectation defines what the engine should produce after all events.
type Expectation struct {
// Final projection fields.
Mode string `yaml:"mode,omitempty"`
RecoveryDecision string `yaml:"recovery_decision,omitempty"`
SessionPhase string `yaml:"session_phase,omitempty"`
// Commands that must appear (by kind name).
MustEmitCommands []string `yaml:"must_emit_commands,omitempty"`
// Commands that must NOT appear.
MustNotEmitCommands []string `yaml:"must_not_emit_commands,omitempty"`
// Trace steps that must appear.
MustHaveTraceSteps []string `yaml:"must_have_trace_steps,omitempty"`
}
// CaseSuite is a collection of conformance cases.
type CaseSuite struct {
Version string `yaml:"version"`
Cases []ConformanceCase `yaml:"cases"`
}
+102
View File
@@ -0,0 +1,102 @@
package schema
import (
"fmt"
"github.com/seaweedfs/seaweed-block/core/engine"
)
// ToEngineEvent converts a schema EventInput to a typed engine Event.
func ToEngineEvent(ei EventInput) (engine.Event, error) {
switch ei.Kind {
case "AssignmentObserved":
return engine.AssignmentObserved{
VolumeID: ei.VolumeID,
ReplicaID: ei.ReplicaID,
Epoch: ei.Epoch,
EndpointVersion: ei.EndpointVersion,
DataAddr: ei.DataAddr,
CtrlAddr: ei.CtrlAddr,
}, nil
case "EndpointObserved":
return engine.EndpointObserved{
ReplicaID: ei.ReplicaID,
EndpointVersion: ei.EndpointVersion,
DataAddr: ei.DataAddr,
CtrlAddr: ei.CtrlAddr,
}, nil
case "ReplicaRemoved":
return engine.ReplicaRemoved{
ReplicaID: ei.ReplicaID,
Reason: ei.Reason,
}, nil
case "ProbeSucceeded":
return engine.ProbeSucceeded{
ReplicaID: ei.ReplicaID,
EndpointVersion: ei.EndpointVersion,
TransportEpoch: ei.TransportEpoch,
}, nil
case "ProbeFailed":
return engine.ProbeFailed{
ReplicaID: ei.ReplicaID,
Reason: ei.Reason,
}, nil
case "RecoveryFactsObserved":
return engine.RecoveryFactsObserved{
ReplicaID: ei.ReplicaID,
R: ei.R,
S: ei.S,
H: ei.H,
}, nil
case "SessionPrepared":
return engine.SessionPrepared{
ReplicaID: ei.ReplicaID,
SessionID: ei.SessionID,
Kind: engine.SessionKind(ei.SessionKind),
TargetLSN: ei.TargetLSN,
}, nil
case "SessionStarted":
return engine.SessionStarted{
ReplicaID: ei.ReplicaID,
SessionID: ei.SessionID,
}, nil
case "SessionProgressObserved":
return engine.SessionProgressObserved{
ReplicaID: ei.ReplicaID,
SessionID: ei.SessionID,
AchievedLSN: ei.AchievedLSN,
}, nil
case "SessionClosedCompleted":
return engine.SessionClosedCompleted{
ReplicaID: ei.ReplicaID,
SessionID: ei.SessionID,
AchievedLSN: ei.AchievedLSN,
}, nil
case "SessionClosedFailed":
return engine.SessionClosedFailed{
ReplicaID: ei.ReplicaID,
SessionID: ei.SessionID,
Reason: ei.Reason,
}, nil
case "SessionInvalidated":
return engine.SessionInvalidated{
ReplicaID: ei.ReplicaID,
SessionID: ei.SessionID,
Reason: ei.Reason,
}, nil
default:
return nil, fmt.Errorf("schema: unknown event kind %q", ei.Kind)
}
}
+57
View File
@@ -0,0 +1,57 @@
package schema
import (
"bytes"
"fmt"
"os"
"gopkg.in/yaml.v3"
)
// LoadCaseSuite loads a conformance case suite from a YAML file.
func LoadCaseSuite(path string) (*CaseSuite, error) {
data, err := os.ReadFile(path)
if err != nil {
return nil, fmt.Errorf("schema: read %s: %w", path, err)
}
return ParseCaseSuite(data)
}
// ParseCaseSuite parses a conformance case suite from YAML bytes.
// Uses strict decoding: unknown fields are rejected to prevent typos
// from silently weakening conformance expectations.
func ParseCaseSuite(data []byte) (*CaseSuite, error) {
var suite CaseSuite
dec := yaml.NewDecoder(bytes.NewReader(data))
dec.KnownFields(true) // reject unknown fields
if err := dec.Decode(&suite); err != nil {
return nil, fmt.Errorf("schema: parse: %w", err)
}
if err := validateSuite(&suite); err != nil {
return nil, err
}
return &suite, nil
}
func validateSuite(suite *CaseSuite) error {
if suite.Version == "" {
return fmt.Errorf("schema: missing version")
}
if len(suite.Cases) == 0 {
return fmt.Errorf("schema: no cases defined")
}
for i, c := range suite.Cases {
if c.Name == "" {
return fmt.Errorf("schema: case %d missing name", i)
}
if len(c.Events) == 0 {
return fmt.Errorf("schema: case %q has no events", c.Name)
}
for j, ev := range c.Events {
if ev.Kind == "" {
return fmt.Errorf("schema: case %q event %d missing kind", c.Name, j)
}
}
}
return nil
}
+178
View File
@@ -0,0 +1,178 @@
// Package storage provides a minimal block store for the V3 sparrow.
// It stores blocks in memory with LSN tracking. No persistence —
// the sparrow is a proof-of-route, not a production storage engine.
//
// For production, this would be replaced by LogicalStorage (ClassicWAL
// or SmartWAL) from the seaweedfs repo.
package storage
import (
"fmt"
"sync"
)
const DefaultBlockSize = 4096
// BlockStore is a minimal in-memory block store with LSN tracking.
type BlockStore struct {
mu sync.RWMutex
blocks map[uint32][]byte // LBA → data
blockSize int
numBlocks uint32
nextLSN uint64
syncedLSN uint64 // last synced frontier
// WAL boundary tracking for recovery classification.
walTail uint64 // oldest retained LSN (S)
walHead uint64 // newest written LSN (H)
}
// NewBlockStore creates an empty block store.
func NewBlockStore(numBlocks uint32, blockSize int) *BlockStore {
if blockSize == 0 {
blockSize = DefaultBlockSize
}
return &BlockStore{
blocks: make(map[uint32][]byte),
blockSize: blockSize,
numBlocks: numBlocks,
nextLSN: 1,
}
}
// Write stores a block and advances the LSN.
func (s *BlockStore) Write(lba uint32, data []byte) (lsn uint64, err error) {
if lba >= s.numBlocks {
return 0, fmt.Errorf("storage: LBA %d out of range (max %d)", lba, s.numBlocks-1)
}
if len(data) != s.blockSize {
return 0, fmt.Errorf("storage: data size %d != block size %d", len(data), s.blockSize)
}
s.mu.Lock()
defer s.mu.Unlock()
cp := make([]byte, s.blockSize)
copy(cp, data)
s.blocks[lba] = cp
lsn = s.nextLSN
s.nextLSN++
s.walHead = lsn
if s.walTail == 0 {
s.walTail = lsn
}
return lsn, nil
}
// Read retrieves a block. Returns zeros if never written.
func (s *BlockStore) Read(lba uint32) ([]byte, error) {
if lba >= s.numBlocks {
return nil, fmt.Errorf("storage: LBA %d out of range", lba)
}
s.mu.RLock()
defer s.mu.RUnlock()
if data, ok := s.blocks[lba]; ok {
cp := make([]byte, s.blockSize)
copy(cp, data)
return cp, nil
}
return make([]byte, s.blockSize), nil
}
// Sync marks all current writes as durable. Returns the synced frontier.
func (s *BlockStore) Sync() uint64 {
s.mu.Lock()
defer s.mu.Unlock()
if s.nextLSN > 1 {
s.syncedLSN = s.nextLSN - 1
}
return s.syncedLSN
}
// Boundaries returns the current R/S/H recovery boundaries.
// - R (syncedLSN): what's durable on this node
// - S (walTail): oldest retained LSN
// - H (walHead): newest written LSN
func (s *BlockStore) Boundaries() (R, S, H uint64) {
s.mu.RLock()
defer s.mu.RUnlock()
return s.syncedLSN, s.walTail, s.walHead
}
// NextLSN returns the next LSN to be assigned.
func (s *BlockStore) NextLSN() uint64 {
s.mu.RLock()
defer s.mu.RUnlock()
return s.nextLSN
}
// NumBlocks returns the block count.
func (s *BlockStore) NumBlocks() uint32 {
return s.numBlocks
}
// BlockSize returns the block size.
func (s *BlockStore) BlockSize() int {
return s.blockSize
}
// AdvanceFrontier advances nextLSN and walHead metadata without writing
// any block data. Used after rebuild to set the replica's frontier to
// match the primary's head without corrupting user blocks.
func (s *BlockStore) AdvanceFrontier(lsn uint64) {
s.mu.Lock()
defer s.mu.Unlock()
if lsn >= s.nextLSN {
s.nextLSN = lsn + 1
}
if lsn > s.walHead {
s.walHead = lsn
}
}
// AdvanceWALTail moves the WAL tail forward, simulating WAL recycling.
// After this, entries before newTail are no longer available for catch-up.
func (s *BlockStore) AdvanceWALTail(newTail uint64) {
s.mu.Lock()
defer s.mu.Unlock()
if newTail > s.walTail {
s.walTail = newTail
}
}
// ApplyEntry applies a replicated entry from the primary.
func (s *BlockStore) ApplyEntry(lba uint32, data []byte, lsn uint64) error {
if lba >= s.numBlocks {
return fmt.Errorf("storage: apply LBA %d out of range", lba)
}
if len(data) != s.blockSize {
return fmt.Errorf("storage: apply data size %d != block size %d", len(data), s.blockSize)
}
s.mu.Lock()
defer s.mu.Unlock()
cp := make([]byte, s.blockSize)
copy(cp, data)
s.blocks[lba] = cp
if lsn >= s.nextLSN {
s.nextLSN = lsn + 1
}
s.walHead = lsn
return nil
}
// AllBlocks returns all written LBAs and their data (for rebuild serving).
func (s *BlockStore) AllBlocks() map[uint32][]byte {
s.mu.RLock()
defer s.mu.RUnlock()
result := make(map[uint32][]byte, len(s.blocks))
for lba, data := range s.blocks {
cp := make([]byte, len(data))
copy(cp, data)
result[lba] = cp
}
return result
}
+224
View File
@@ -0,0 +1,224 @@
package transport
import (
"encoding/binary"
"fmt"
"log"
"net"
"time"
"github.com/seaweedfs/seaweed-block/core/adapter"
"github.com/seaweedfs/seaweed-block/core/storage"
)
// BlockExecutor implements adapter.CommandExecutor using real TCP
// transport and in-memory storage. It is the "muscle" layer — it
// executes commands but never decides policy.
type BlockExecutor struct {
primaryStore *storage.BlockStore
replicaAddr string // replica's TCP address
endpointVersion uint64 // must match the assignment's endpoint version
onSessionClose adapter.OnSessionClose
}
// NewBlockExecutor creates an executor for one primary → replica pair.
// endpointVersion must match the assignment's endpoint version so probes
// are not rejected as stale by the engine.
func NewBlockExecutor(primaryStore *storage.BlockStore, replicaAddr string, endpointVersion uint64) *BlockExecutor {
return &BlockExecutor{
primaryStore: primaryStore,
replicaAddr: replicaAddr,
endpointVersion: endpointVersion,
}
}
func (e *BlockExecutor) SetOnSessionClose(fn adapter.OnSessionClose) {
e.onSessionClose = fn
}
// Probe dials the replica, sends a probe request, and returns the
// replica's R/S/H boundaries. Returns facts only — never decides policy.
func (e *BlockExecutor) Probe(replicaID, dataAddr, ctrlAddr string) adapter.ProbeResult {
addr := e.replicaAddr
if dataAddr != "" {
addr = dataAddr
}
conn, err := net.DialTimeout("tcp", addr, 2*time.Second)
if err != nil {
return adapter.ProbeResult{
ReplicaID: replicaID,
Success: false,
FailReason: fmt.Sprintf("dial: %v", err),
}
}
defer conn.Close()
conn.SetDeadline(time.Now().Add(3 * time.Second))
if err := WriteMsg(conn, MsgProbeReq, nil); err != nil {
return adapter.ProbeResult{
ReplicaID: replicaID,
Success: false,
FailReason: fmt.Sprintf("send probe: %v", err),
}
}
msgType, payload, err := ReadMsg(conn)
if err != nil || msgType != MsgProbeResp {
return adapter.ProbeResult{
ReplicaID: replicaID,
Success: false,
FailReason: fmt.Sprintf("read probe resp: %v", err),
}
}
resp, err := DecodeProbeResp(payload)
if err != nil {
return adapter.ProbeResult{
ReplicaID: replicaID,
Success: false,
FailReason: fmt.Sprintf("decode probe: %v", err),
}
}
// Get primary's boundaries for R/S/H.
_, primaryS, primaryH := e.primaryStore.Boundaries()
log.Printf("executor: probe %s success R=%d S=%d H=%d",
replicaID, resp.SyncedLSN, primaryS, primaryH)
return adapter.ProbeResult{
ReplicaID: replicaID,
Success: true,
EndpointVersion: e.endpointVersion, // must match assignment
TransportEpoch: e.endpointVersion,
ReplicaFlushedLSN: resp.SyncedLSN, // R
PrimaryTailLSN: primaryS, // S
PrimaryHeadLSN: primaryH, // H
}
}
// StartCatchUp ships WAL entries from the primary to the replica.
// Runs asynchronously — calls OnSessionClose when done.
func (e *BlockExecutor) StartCatchUp(replicaID string, sessionID uint64, targetLSN uint64) error {
go func() {
achieved, err := e.doCatchUp(targetLSN)
if e.onSessionClose != nil {
if err != nil {
e.onSessionClose(adapter.SessionCloseResult{
ReplicaID: replicaID,
SessionID: sessionID,
Success: false,
FailReason: err.Error(),
})
} else {
e.onSessionClose(adapter.SessionCloseResult{
ReplicaID: replicaID,
SessionID: sessionID,
Success: true,
AchievedLSN: achieved,
})
}
}
}()
return nil
}
func (e *BlockExecutor) doCatchUp(targetLSN uint64) (uint64, error) {
conn, err := net.DialTimeout("tcp", e.replicaAddr, 2*time.Second)
if err != nil {
return 0, fmt.Errorf("catch-up dial: %w", err)
}
defer conn.Close()
// Ship all blocks from primary store with the target LSN so the
// replica's store advances its boundaries correctly.
blocks := e.primaryStore.AllBlocks()
for lba, data := range blocks {
entry := EncodeShipEntry(ShipEntry{LBA: lba, LSN: targetLSN, Data: data})
if err := WriteMsg(conn, MsgShipEntry, entry); err != nil {
return 0, fmt.Errorf("catch-up ship LBA %d: %w", lba, err)
}
}
// Send barrier to confirm durability. The barrier response carries
// the replica's actual synced frontier — use THAT as achievedLSN,
// not the intent target.
if err := WriteMsg(conn, MsgBarrierReq, nil); err != nil {
return 0, fmt.Errorf("catch-up barrier: %w", err)
}
msgType, payload, err := ReadMsg(conn)
if err != nil || msgType != MsgBarrierResp {
return 0, fmt.Errorf("catch-up barrier resp: %v", err)
}
achievedLSN := binary.BigEndian.Uint64(payload)
log.Printf("executor: catch-up complete, replica synced to %d", achievedLSN)
return achievedLSN, nil
}
// StartRebuild streams all base blocks from primary to replica.
// Runs asynchronously — calls OnSessionClose when done.
func (e *BlockExecutor) StartRebuild(replicaID string, sessionID uint64, targetLSN uint64) error {
go func() {
achieved, err := e.doRebuild(targetLSN)
if e.onSessionClose != nil {
if err != nil {
e.onSessionClose(adapter.SessionCloseResult{
ReplicaID: replicaID,
SessionID: sessionID,
Success: false,
FailReason: err.Error(),
})
} else {
e.onSessionClose(adapter.SessionCloseResult{
ReplicaID: replicaID,
SessionID: sessionID,
Success: true,
AchievedLSN: achieved,
})
}
}
}()
return nil
}
func (e *BlockExecutor) doRebuild(targetLSN uint64) (uint64, error) {
conn, err := net.DialTimeout("tcp", e.replicaAddr, 2*time.Second)
if err != nil {
return 0, fmt.Errorf("rebuild dial: %w", err)
}
defer conn.Close()
// Send all blocks. The target is the engine's frozen targetLSN,
// not the primary's current head. The executor must not silently
// upgrade the target — that would violate the engine's contract.
blocks := e.primaryStore.AllBlocks()
for lba, data := range blocks {
payload := EncodeRebuildBlock(lba, data)
if err := WriteMsg(conn, MsgRebuildBlock, payload); err != nil {
return 0, fmt.Errorf("rebuild block LBA %d: %w", lba, err)
}
}
// Send done with the engine's frozen targetLSN.
doneBuf := make([]byte, 8)
binary.BigEndian.PutUint64(doneBuf, targetLSN)
if err := WriteMsg(conn, MsgRebuildDone, doneBuf); err != nil {
return 0, fmt.Errorf("rebuild done: %w", err)
}
log.Printf("executor: rebuild complete, sent %d blocks (targetLSN=%d)", len(blocks), targetLSN)
return targetLSN, nil
}
func (e *BlockExecutor) InvalidateSession(replicaID string, sessionID uint64, reason string) {
log.Printf("executor: invalidate session %d for %s: %s", sessionID, replicaID, reason)
}
func (e *BlockExecutor) PublishHealthy(replicaID string) {
log.Printf("executor: publish healthy for %s", replicaID)
}
func (e *BlockExecutor) PublishDegraded(replicaID string, reason string) {
log.Printf("executor: publish degraded for %s: %s", replicaID, reason)
}
+141
View File
@@ -0,0 +1,141 @@
// Package transport provides minimal TCP block replication for the sparrow.
// Three operations: Ship (WAL entry), Probe (handshake with R/S/H), Rebuild (full base copy).
//
// Wire format is intentionally simple — no framing library needed.
// Each message: [1B type][4B length][payload...]
package transport
import (
"encoding/binary"
"fmt"
"io"
"net"
)
// Message types
const (
MsgShipEntry byte = 0x01 // primary → replica: one block write
MsgProbeReq byte = 0x02 // primary → replica: request boundaries
MsgProbeResp byte = 0x03 // replica → primary: R/S/H response
MsgRebuildBlock byte = 0x04 // primary → replica: one base block
MsgRebuildDone byte = 0x05 // primary → replica: rebuild complete
MsgBarrierReq byte = 0x06 // primary → replica: sync request
MsgBarrierResp byte = 0x07 // replica → primary: sync response
)
// ShipEntry is one replicated block write.
type ShipEntry struct {
LBA uint32
LSN uint64
Data []byte
}
// ProbeResponse carries the replica's recovery boundaries.
type ProbeResponse struct {
SyncedLSN uint64 // R: replica's durable frontier
WalTail uint64 // S: oldest retained
WalHead uint64 // H: newest written
}
// --- Wire helpers ---
// WriteMsg sends a typed message on the connection.
func WriteMsg(conn net.Conn, msgType byte, payload []byte) error {
header := make([]byte, 5)
header[0] = msgType
binary.BigEndian.PutUint32(header[1:5], uint32(len(payload)))
if _, err := conn.Write(header); err != nil {
return err
}
if len(payload) > 0 {
if _, err := conn.Write(payload); err != nil {
return err
}
}
return nil
}
// MaxPayloadSize is the upper bound for incoming message payloads.
// Prevents memory exhaustion from malicious or buggy senders.
const MaxPayloadSize = 16 * 1024 * 1024 // 16MB
// ReadMsg reads a typed message from the connection.
func ReadMsg(conn net.Conn) (msgType byte, payload []byte, err error) {
header := make([]byte, 5)
if _, err := io.ReadFull(conn, header); err != nil {
return 0, nil, err
}
msgType = header[0]
length := binary.BigEndian.Uint32(header[1:5])
if length > MaxPayloadSize {
return 0, nil, fmt.Errorf("transport: payload too large: %d > %d", length, MaxPayloadSize)
}
if length > 0 {
payload = make([]byte, length)
if _, err := io.ReadFull(conn, payload); err != nil {
return 0, nil, err
}
}
return msgType, payload, nil
}
// EncodeShipEntry serializes a ship entry.
// Wire: [4B LBA][8B LSN][data...]
func EncodeShipEntry(e ShipEntry) []byte {
buf := make([]byte, 12+len(e.Data))
binary.BigEndian.PutUint32(buf[0:4], e.LBA)
binary.BigEndian.PutUint64(buf[4:12], e.LSN)
copy(buf[12:], e.Data)
return buf
}
// DecodeShipEntry deserializes a ship entry.
func DecodeShipEntry(buf []byte) (ShipEntry, error) {
if len(buf) < 12 {
return ShipEntry{}, fmt.Errorf("transport: short ship entry")
}
return ShipEntry{
LBA: binary.BigEndian.Uint32(buf[0:4]),
LSN: binary.BigEndian.Uint64(buf[4:12]),
Data: buf[12:],
}, nil
}
// EncodeProbeResp serializes a probe response.
// Wire: [8B syncedLSN][8B walTail][8B walHead]
func EncodeProbeResp(p ProbeResponse) []byte {
buf := make([]byte, 24)
binary.BigEndian.PutUint64(buf[0:8], p.SyncedLSN)
binary.BigEndian.PutUint64(buf[8:16], p.WalTail)
binary.BigEndian.PutUint64(buf[16:24], p.WalHead)
return buf
}
// DecodeProbeResp deserializes a probe response.
func DecodeProbeResp(buf []byte) (ProbeResponse, error) {
if len(buf) < 24 {
return ProbeResponse{}, fmt.Errorf("transport: short probe response")
}
return ProbeResponse{
SyncedLSN: binary.BigEndian.Uint64(buf[0:8]),
WalTail: binary.BigEndian.Uint64(buf[8:16]),
WalHead: binary.BigEndian.Uint64(buf[16:24]),
}, nil
}
// EncodeRebuildBlock serializes one rebuild block.
// Wire: [4B LBA][data...]
func EncodeRebuildBlock(lba uint32, data []byte) []byte {
buf := make([]byte, 4+len(data))
binary.BigEndian.PutUint32(buf[0:4], lba)
copy(buf[4:], data)
return buf
}
// DecodeRebuildBlock deserializes one rebuild block.
func DecodeRebuildBlock(buf []byte) (lba uint32, data []byte, err error) {
if len(buf) < 4 {
return 0, nil, fmt.Errorf("transport: short rebuild block")
}
return binary.BigEndian.Uint32(buf[0:4]), buf[4:], nil
}
+146
View File
@@ -0,0 +1,146 @@
package transport
import (
"encoding/binary"
"log"
"net"
"sync"
"github.com/seaweedfs/seaweed-block/core/storage"
)
// ReplicaListener accepts connections from the primary and handles
// WAL shipping, probe requests, and rebuild streams.
type ReplicaListener struct {
store *storage.BlockStore
listener net.Listener
stopCh chan struct{}
wg sync.WaitGroup
}
// NewReplicaListener creates a listener on the given address.
func NewReplicaListener(addr string, store *storage.BlockStore) (*ReplicaListener, error) {
ln, err := net.Listen("tcp", addr)
if err != nil {
return nil, err
}
return &ReplicaListener{
store: store,
listener: ln,
stopCh: make(chan struct{}),
}, nil
}
// Addr returns the listener's address.
func (r *ReplicaListener) Addr() string {
return r.listener.Addr().String()
}
// Serve starts accepting connections.
func (r *ReplicaListener) Serve() {
r.wg.Add(1)
go r.acceptLoop()
}
// Stop shuts down the listener. Safe to call multiple times.
func (r *ReplicaListener) Stop() {
select {
case <-r.stopCh:
return // already stopped
default:
}
close(r.stopCh)
r.listener.Close()
r.wg.Wait()
}
func (r *ReplicaListener) acceptLoop() {
defer r.wg.Done()
for {
conn, err := r.listener.Accept()
if err != nil {
select {
case <-r.stopCh:
return
default:
log.Printf("replica: accept error: %v", err)
return
}
}
r.wg.Add(1)
go func() {
defer r.wg.Done()
r.handleConn(conn)
}()
}
}
func (r *ReplicaListener) handleConn(conn net.Conn) {
defer conn.Close()
for {
msgType, payload, err := ReadMsg(conn)
if err != nil {
return // connection closed
}
switch msgType {
case MsgShipEntry:
entry, err := DecodeShipEntry(payload)
if err != nil {
log.Printf("replica: decode ship entry: %v", err)
return
}
if err := r.store.ApplyEntry(entry.LBA, entry.Data, entry.LSN); err != nil {
log.Printf("replica: apply entry: %v", err)
}
case MsgProbeReq:
R, S, H := r.store.Boundaries()
resp := EncodeProbeResp(ProbeResponse{
SyncedLSN: R,
WalTail: S,
WalHead: H,
})
if err := WriteMsg(conn, MsgProbeResp, resp); err != nil {
return
}
case MsgRebuildBlock:
lba, data, err := DecodeRebuildBlock(payload)
if err != nil {
log.Printf("replica: decode rebuild block: %v", err)
return
}
// Apply with LSN=1 as placeholder; the real LSN comes in
// MsgRebuildDone to advance the frontier correctly.
if err := r.store.ApplyEntry(lba, data, 1); err != nil {
log.Printf("replica: apply rebuild block: %v", err)
}
case MsgRebuildDone:
// The done message carries the primary's head LSN.
// Advance the replica's frontier metadata without touching
// any block data — AdvanceFrontier only updates nextLSN/walHead.
if len(payload) >= 8 {
achievedLSN := binary.BigEndian.Uint64(payload)
r.store.AdvanceFrontier(achievedLSN)
}
r.store.Sync()
return
case MsgBarrierReq:
frontier := r.store.Sync()
resp := make([]byte, 8)
binary.BigEndian.PutUint64(resp, frontier)
if err := WriteMsg(conn, MsgBarrierResp, resp); err != nil {
log.Printf("replica: write barrier response: %v", err)
return
}
default:
log.Printf("replica: unknown message type 0x%02x", msgType)
return
}
}
}
@@ -0,0 +1,189 @@
package transport
import (
"bytes"
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/adapter"
"github.com/seaweedfs/seaweed-block/core/storage"
)
func setupPrimaryReplica(t *testing.T) (*storage.BlockStore, *storage.BlockStore, *ReplicaListener) {
t.Helper()
primary := storage.NewBlockStore(64, 4096)
replica := storage.NewBlockStore(64, 4096)
listener, err := NewReplicaListener("127.0.0.1:0", replica)
if err != nil {
t.Fatal(err)
}
listener.Serve()
t.Cleanup(func() { listener.Stop() })
return primary, replica, listener
}
func writeTestBlocks(store *storage.BlockStore, count uint32) {
for i := uint32(0); i < count; i++ {
data := make([]byte, 4096)
data[0] = byte(i + 1)
data[1] = byte(i + 0xA0)
store.Write(i, data)
}
store.Sync()
}
func assertDataMatch(t *testing.T, label string, primary, replica *storage.BlockStore, count uint32) {
t.Helper()
for i := uint32(0); i < count; i++ {
pd, _ := primary.Read(i)
rd, _ := replica.Read(i)
if !bytes.Equal(pd, rd) {
t.Fatalf("%s: LBA %d data mismatch (primary[0]=%d replica[0]=%d)",
label, i, pd[0], rd[0])
}
}
}
// --- Healthy: probe shows R >= H, data matches ---
func TestTransport_Healthy_ProbeShowsCaughtUp(t *testing.T) {
primary, replica, listener := setupPrimaryReplica(t)
// Write same data on both.
for i := uint32(0); i < 5; i++ {
data := make([]byte, 4096)
data[0] = byte(i + 1)
lsn, _ := primary.Write(i, data)
replica.ApplyEntry(i, data, lsn)
}
primary.Sync()
replica.Sync()
exec := NewBlockExecutor(primary, listener.Addr(), 1)
result := exec.Probe("r1", listener.Addr(), listener.Addr())
if !result.Success {
t.Fatalf("probe failed: %s", result.FailReason)
}
_, _, pH := primary.Boundaries()
if result.ReplicaFlushedLSN != pH {
t.Fatalf("R=%d != H=%d — should be exactly caught up",
result.ReplicaFlushedLSN, pH)
}
assertDataMatch(t, "healthy", primary, replica, 5)
}
// --- Catch-up: ships blocks, barrier confirms actual frontier, data matches ---
func TestTransport_CatchUp_ShipsAndBarrierConfirms(t *testing.T) {
primary, replica, listener := setupPrimaryReplica(t)
writeTestBlocks(primary, 10)
exec := NewBlockExecutor(primary, listener.Addr(), 1)
closeCh := make(chan adapter.SessionCloseResult, 1)
exec.SetOnSessionClose(func(r adapter.SessionCloseResult) { closeCh <- r })
_, _, pH := primary.Boundaries()
if err := exec.StartCatchUp("r1", 1, pH); err != nil {
t.Fatal(err)
}
select {
case result := <-closeCh:
if !result.Success {
t.Fatalf("catch-up failed: %s", result.FailReason)
}
// AchievedLSN must equal the primary head — actual frontier, not intent.
if result.AchievedLSN != pH {
t.Fatalf("achievedLSN=%d != primaryH=%d", result.AchievedLSN, pH)
}
case <-time.After(5 * time.Second):
t.Fatal("timeout")
}
// Replica frontier must match.
rR, _, _ := replica.Boundaries()
if rR != pH {
t.Fatalf("replica frontier R=%d != primaryH=%d", rR, pH)
}
// Data integrity.
assertDataMatch(t, "catch-up", primary, replica, 10)
}
// --- Rebuild: streams all blocks, frontier matches, data intact ---
func TestTransport_Rebuild_StreamsAndAdvancesFrontier(t *testing.T) {
primary, replica, listener := setupPrimaryReplica(t)
writeTestBlocks(primary, 10)
exec := NewBlockExecutor(primary, listener.Addr(), 1)
closeCh := make(chan adapter.SessionCloseResult, 1)
exec.SetOnSessionClose(func(r adapter.SessionCloseResult) { closeCh <- r })
_, _, pH := primary.Boundaries()
if err := exec.StartRebuild("r1", 1, pH); err != nil {
t.Fatal(err)
}
select {
case result := <-closeCh:
if !result.Success {
t.Fatalf("rebuild failed: %s", result.FailReason)
}
if result.AchievedLSN != pH {
t.Fatalf("achievedLSN=%d != primaryH=%d", result.AchievedLSN, pH)
}
case <-time.After(5 * time.Second):
t.Fatal("timeout")
}
// Small delay for replica handler to finish Sync after MsgRebuildDone.
time.Sleep(50 * time.Millisecond)
// Replica frontier must match primary.
rR, _, _ := replica.Boundaries()
if rR != pH {
t.Fatalf("replica frontier R=%d != primaryH=%d after rebuild", rR, pH)
}
// Data integrity — this is the critical check that catches the
// old bug where rebuild corrupted LBA 0 with zeros.
assertDataMatch(t, "rebuild", primary, replica, 10)
}
// --- Rebuild does not corrupt LBA 0 (regression test) ---
func TestTransport_Rebuild_DoesNotCorruptLBA0(t *testing.T) {
primary, replica, listener := setupPrimaryReplica(t)
// Write a known pattern at LBA 0.
data0 := make([]byte, 4096)
data0[0] = 0xDE
data0[1] = 0xAD
primary.Write(0, data0)
primary.Sync()
exec := NewBlockExecutor(primary, listener.Addr(), 1)
closeCh := make(chan adapter.SessionCloseResult, 1)
exec.SetOnSessionClose(func(r adapter.SessionCloseResult) { closeCh <- r })
_, _, pH := primary.Boundaries()
exec.StartRebuild("r1", 1, pH)
select {
case r := <-closeCh:
if !r.Success {
t.Fatal(r.FailReason)
}
case <-time.After(5 * time.Second):
t.Fatal("timeout")
}
// LBA 0 must have the original data, NOT zeros.
rd, _ := replica.Read(0)
if rd[0] != 0xDE || rd[1] != 0xAD {
t.Fatalf("LBA 0 corrupted: got [%02x %02x], want [DE AD]", rd[0], rd[1])
}
}
+5
View File
@@ -0,0 +1,5 @@
module github.com/seaweedfs/seaweed-block
go 1.23
require gopkg.in/yaml.v3 v3.0.1
+4
View File
@@ -0,0 +1,4 @@
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=