Files
seaweedfs/seaweed-block/core/ops/server_test.go
T
pingqiuandClaude Opus 4.7 3351a66ff2 T4d-3: R+1 threading + import-discipline fence (G-1 v0.2 PORT items 1-5; CARRY-T4D-LANE-CONTEXT-001 Option B)
Per T4d mini-plan v0.3 §2.3 + G-1 v0.2 (architect+QA-signed
2026-04-25). Refs G-1 sign: pending hash (G-1 doc lives in
seaweedfs sw-block/design/v3-phase-15-t4d-3-g1-v2-read.md v0.2);
QA approval round-46 cleared T4d-3 start.

PORT items landed (G-1 v0.2 §3, items 1-5):

Item 1 — start boundary: engine.StartCatchUp gains FromLSN field;
engine emits Recovery.R + 1 (decide path + retry-loop re-emit).
Pinned by INV-REPL-CATCHUP-FROMLSN-IS-REPLICA-FLUSHED-PLUS-1 +
INV-REPL-CATCHUP-FROMLSN-FROM-ENGINE-STATE-NOT-PROBE.

Item 2 — per-call deadline: preserved unchanged (T4c-2 INV-REPL-
CATCHUP-DEADLINE-PER-CALL-SCOPE forward-carries).

Item 3 — last-sent monotonic + completion: preserved unchanged
(T4c-2 invariants forward-carry; barrier ack remains completion
truth).

Item 4 — retry budget: engine retry-loop reuses ORIGINAL Recovery.R
+ 1 on re-emit per G-1 §6.2 architect Option A (no inter-attempt
re-probe; apply gate handles over-ship). Pinned by
TestT4d3_CatchUp_RetryReusesOriginalRPlus1.

Item 5 — retention-miss escalation: T4d-1 typed-kind contract
already in place; engine branches on FailureKind. Forward-carry.

V3-NATIVE items (no V2 source per G-1 v0.2 §4):
- Engine-owned retry loop (Q1) — already in place at T4c-3
- Unified recovery command model — T4c-pre-B
- Lane-aware apply gate integration — T4d-2
- BarrierResponse.AchievedLSN as completion truth — T4c-2
- Package-boundary discipline — pinned by new
  TestT4d3_Catchup_TransportNeverImportsSubstrateInternals
  (parses transport .go files via go/parser; fails if any
  substrate-internal package import surfaces)

Signature ripple (10 files):
- engine.StartCatchUp{FromLSN uint64} added (no removals)
- adapter.CommandExecutor.StartCatchUp interface +1 param
- transport.BlockExecutor.StartCatchUp + doCatchUp +1 param
- 4 test executor stubs (mockExecutor, closureExecutor,
  policyClosureExecutor, restartExecutor) + production
  HealthyPathExecutor + noopExecutor + ops nopExecutor
- transport.recovery_session.go bridge passes fromLSN=1 (legacy
  StartRecoverySession path; forward-carry to T4e for explicit
  fromLSN field on StartRecovery)
- adapter.adapter_test.go bridge passes fromLSN=1
- 5 transport test call sites + 3 component integration test sites
- component framework CatchUpReplica helper passes fromLSN=1
  (transitional shim; tests needing explicit R+1 use direct
  executor invocation per G-1 §7)

NEW TESTS (G-1 §7 test parity matrix):
- core/engine/t4d3_rplus1_test.go (3 tests):
  - TestT4d3_CatchUp_Engine_RPlus1_FromOwnState_NotProbeDirectly
    (pins INV-REPL-CATCHUP-FROMLSN-FROM-ENGINE-STATE-NOT-PROBE)
  - TestT4d3_CatchUp_RetryReusesOriginalRPlus1 (G-1 §6.2 Option A)
  - TestT4d3_StartCatchUpStruct_HasFromLSNField (compile fence)
- core/transport/t4d3_rplus1_test.go (3 tests):
  - TestT4d3_CatchUp_ScansFromReplicaR_NotGenesis (substrate
    receives caller-supplied fromLSN; sender does NOT add +1)
  - TestT4d3_CatchUp_StartCatchUpSignature_FromLSNRequired
  - TestT4d3_CatchUp_NonEmptyReplica_BlockStoreOverShipsExpected
    (round-46 ADDITION 2 substrate-bound naming — opposing-
    assertion regression fence per §9 caveat)
- core/transport/import_discipline_test.go (1 test):
  - TestT4d3_Catchup_TransportNeverImportsSubstrateInternals
    (Q3 INV-REPL-TRANSPORT-STORAGE-CONTRACT-ONLY; parses transport
    sources, fails on substrate-internal imports)
- core/replication/component/t4d3_scenarios_test.go (4 tests):
  - TestT4d3_CatchUp_NonEmptyReplica_ShortGap_BandwidthBounded_
    Walstore (substrate-bound bandwidth observation)
  - TestT4d3_CatchUp_NonEmptyReplica_ShortGap_BandwidthBounded_
    Smartwal (mirror)
  - TestT4d3_RetryAfterReplicaAdvanced_OverScansHandledByApplyGate
    (round-46 ADDITION 1 — pins §6.2 Option A safety claim:
    over-scan + apply gate per-LBA stale-skip; assertions cover
    byte-exact convergence + no per-LBA regression + coverage
    union completeness)
  - TestT4d3_RecoveryTargetLSN1_KnownGap (CARRY-T4D-LANE-CONTEXT-
    001 Option B close — SKIPPED with explicit forward-binding
    for the T4e or beyond fix; gate API itself is already
    lane-pure, only caller's signal source needs upgrading)

CARRY-T4D-LANE-CONTEXT-001 close (round-46 architect HARD CLOSE
CONDITION): Option B chosen (NOT Option A) because true handler/
session-context lane signal is a much larger refactor (separate
listener ports OR per-connection lane tag via session-registration
handshake OR new MessageType — all wire/transport-architectural
changes). Architect listed Option B as acceptable. The skip-marked
test documents the H=1 known gap; godoc cites
CARRY-T4D-LANE-CONTEXT-001 explicitly for catalogue cross-reference.

NOT in T4d-3 scope (deferred):
- Engine-driven recovery wiring through ReplicationVolume↔adapter
  (G-1 §4 Item A integration scope) — engine retry-loop is
  unit-tested; full ReplicationVolume↔adapter binding is a
  follow-up task. Rationale: this commit is large enough; landing
  the R+1 threading + import discipline as one piece + adding
  end-to-end engine-driven recovery wiring as another keeps
  reviewability tractable. T4d-4 owns the lifecycle integration;
  the engine-driven-recovery wiring fits naturally there OR as a
  T4d-3-followup.

Forward-carry status:
- T4d-1 typed-kind contract: forward-carries unchanged
- T4d-2 lane-pure apply gate: forward-carries; round-46 lane
  discipline still honored (gate doesn't sniff lineage)
- All round-43/44 stale-skip invariants: forward-carry green
- T4c-2 6 catch-up invariants: forward-carry under R+1 threading
  (verified via T4c muscle tests still passing)
- 22 packages green; 0 failures

Tests added: 11 (per G-1 §7 matrix).

Refs: T4d mini-plan v0.3 §2.3 (architect-ratified); G-1 v0.2
QA-signed (CARRY-T4D-LANE-CONTEXT-001 close condition Option B);
round-46 architect ruling (lane-pure gate); kickoff §9 (Q1/Q2/Q3).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-25 22:10:44 -07:00

216 lines
6.5 KiB
Go

package ops
import (
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/seaweedfs/seaweed-block/core/adapter"
"github.com/seaweedfs/seaweed-block/core/engine"
)
// newTestServer builds a live httptest.Server wrapping the ops handlers.
// Returns the server URL and a cleanup func.
func newTestServer(t *testing.T, state *State) (string, func()) {
t.Helper()
h := &handlers{
version: "0.5.0-test",
scope: "test scope\n",
state: state,
}
mux := http.NewServeMux()
mux.Handle("/status", withReadOnly(http.HandlerFunc(h.status)))
mux.Handle("/projection", withReadOnly(http.HandlerFunc(h.projection)))
mux.Handle("/trace", withReadOnly(http.HandlerFunc(h.trace)))
mux.Handle("/watchdog", withReadOnly(http.HandlerFunc(h.watchdog)))
mux.Handle("/diagnose", withReadOnly(http.HandlerFunc(h.diagnose)))
mux.Handle("/", withReadOnly(http.HandlerFunc(h.index)))
srv := httptest.NewServer(mux)
return srv.URL, srv.Close
}
func TestStatus_ReturnsVersionAndScope(t *testing.T) {
url, cleanup := newTestServer(t, NewState())
defer cleanup()
resp, err := http.Get(url + "/status")
if err != nil {
t.Fatal(err)
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
t.Fatalf("status: got %d, want 200", resp.StatusCode)
}
var body statusBody
if err := json.NewDecoder(resp.Body).Decode(&body); err != nil {
t.Fatal(err)
}
if body.Version != "0.5.0-test" {
t.Fatalf("version: got %q, want 0.5.0-test", body.Version)
}
if body.Scope == "" {
t.Fatal("scope: empty")
}
}
func TestProjection_EmptyWhenNoDemo(t *testing.T) {
url, cleanup := newTestServer(t, NewState())
defer cleanup()
resp, err := http.Get(url + "/projection")
if err != nil {
t.Fatal(err)
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
t.Fatalf("projection: got %d, want 200", resp.StatusCode)
}
body, _ := io.ReadAll(resp.Body)
// Empty projection has zero values — just verify it's valid JSON
// and does not error.
var anyMap map[string]any
if err := json.Unmarshal(body, &anyMap); err != nil {
t.Fatalf("projection: not valid JSON: %v body=%s", err, body)
}
}
func TestTrace_EmptyArrayWhenNoDemo(t *testing.T) {
url, cleanup := newTestServer(t, NewState())
defer cleanup()
resp, err := http.Get(url + "/trace")
if err != nil {
t.Fatal(err)
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
// Must be a JSON array, not null.
trimmed := strings.TrimSpace(string(body))
if !strings.HasPrefix(trimmed, "[") || !strings.HasSuffix(trimmed, "]") {
t.Fatalf("trace: not a JSON array: %q", trimmed)
}
}
func TestWatchdog_EmptyArrayWhenNoDemo(t *testing.T) {
url, cleanup := newTestServer(t, NewState())
defer cleanup()
resp, err := http.Get(url + "/watchdog")
if err != nil {
t.Fatal(err)
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
trimmed := strings.TrimSpace(string(body))
if !strings.HasPrefix(trimmed, "[") || !strings.HasSuffix(trimmed, "]") {
t.Fatalf("watchdog: not a JSON array: %q", trimmed)
}
}
// mutationMethods are every non-read verb that must return 501.
var mutationMethods = []string{"POST", "PUT", "PATCH", "DELETE"}
func TestMutations_Return501OnEveryPath(t *testing.T) {
url, cleanup := newTestServer(t, NewState())
defer cleanup()
paths := []string{"/", "/status", "/projection", "/trace", "/watchdog", "/diagnose", "/does-not-exist"}
for _, p := range paths {
for _, m := range mutationMethods {
t.Run(m+" "+p, func(t *testing.T) {
req, err := http.NewRequest(m, url+p, strings.NewReader(`{"x":1}`))
if err != nil {
t.Fatal(err)
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
t.Fatal(err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusNotImplemented {
t.Fatalf("got %d, want 501 (Not Implemented)", resp.StatusCode)
}
allow := resp.Header.Get("Allow")
if !strings.Contains(allow, "GET") {
t.Fatalf("Allow header %q should list GET", allow)
}
body, _ := io.ReadAll(resp.Body)
var decoded map[string]string
if err := json.Unmarshal(body, &decoded); err != nil {
t.Fatalf("body not JSON: %v body=%s", err, body)
}
if !strings.Contains(decoded["error"], "read-only ops surface") {
t.Fatalf("error message missing read-only text: %q", decoded["error"])
}
})
}
}
}
func TestUnknownPath_Returns404(t *testing.T) {
url, cleanup := newTestServer(t, NewState())
defer cleanup()
resp, err := http.Get(url + "/unknown-thing")
if err != nil {
t.Fatal(err)
}
defer resp.Body.Close()
if resp.StatusCode != 404 {
t.Fatalf("got %d, want 404", resp.StatusCode)
}
}
func TestState_UpdateReflectsInSnapshot(t *testing.T) {
st := NewState()
demo, _, tr, wd := st.Snapshot()
if demo != "" {
t.Fatalf("fresh state demo=%q, want empty", demo)
}
if tr != nil {
t.Fatalf("fresh state trace=%v, want nil", tr)
}
if wd != nil {
t.Fatalf("fresh state watchdog=%v, want nil", wd)
}
// Use a live adapter so Snapshot() has something to read.
exec := &nopExecutor{}
a := adapter.NewVolumeReplicaAdapter(exec)
st.Update("healthy", a)
demo, _, _, _ = st.Snapshot()
if demo != "healthy" {
t.Fatalf("after Update: demo=%q, want healthy", demo)
}
}
// nopExecutor is the minimum executor interface for State tests.
// It does nothing — the adapter is only used for its Projection()
// and Trace() accessors, not for real transport.
type nopExecutor struct {
onStart adapter.OnSessionStart
onClose adapter.OnSessionClose
onFence adapter.OnFenceComplete
}
func (e *nopExecutor) SetOnSessionStart(fn adapter.OnSessionStart) { e.onStart = fn }
func (e *nopExecutor) SetOnSessionClose(fn adapter.OnSessionClose) { e.onClose = fn }
func (e *nopExecutor) SetOnFenceComplete(fn adapter.OnFenceComplete) { e.onFence = fn }
func (e *nopExecutor) Probe(string, string, string, uint64, uint64, uint64) adapter.ProbeResult {
return adapter.ProbeResult{Success: false, FailReason: "nop"}
}
func (e *nopExecutor) StartCatchUp(string, uint64, uint64, uint64, uint64, uint64) error { return nil }
func (e *nopExecutor) StartRebuild(string, uint64, uint64, uint64, uint64) error { return nil }
func (e *nopExecutor) StartRecoverySession(string, uint64, uint64, uint64, uint64, engine.RecoveryContentKind, engine.RecoveryRuntimePolicy) error {
return nil
}
func (e *nopExecutor) Fence(string, uint64, uint64, uint64) error { return nil }
func (e *nopExecutor) InvalidateSession(string, uint64, string) {}
func (e *nopExecutor) PublishHealthy(string) {}
func (e *nopExecutor) PublishDegraded(string, string) {}