diff --git a/seaweed-block/core/replication/l2_integration_test.go b/seaweed-block/core/replication/l2_integration_test.go index 1851a2bc1b..f25a3c3fcf 100644 --- a/seaweed-block/core/replication/l2_integration_test.go +++ b/seaweed-block/core/replication/l2_integration_test.go @@ -287,6 +287,19 @@ func TestT4a6_BasicEndToEnd_PrimaryWriteReachesReplicaByteExact(t *testing.T) { // "best-effort is non-fatal to the writer and authority-driven // peer rebuild is the recovery path." func TestT4a6_BestEffort_DisconnectThenReassign(t *testing.T) { + t.Skip("§6.3 collapse migration: this test asserts that a peer " + + "degraded mid-stream + reassign-to-fresh-replica does NOT " + + "silently catch up the suppressed second batch. Under §6.3 " + + "single drive() dispatch (Path A commit), the new shipper's " + + "first post-reassign NotifyAppend takes CASE A debt-fill: " + + "substrate has the suppressed entries, scan emits them, " + + "replica2 receives the full 1..tail range. This is the new " + + "§6.3 default semantic — automatic WAL-only catch-up via " + + "substrate when a fresh peer reattaches and substrate is " + + "still ahead. The pre-§6.3 'best-effort = no auto catch-up' " + + "contract is retired by Path 1. Re-author against §6.3 " + + "semantics or remove the test entirely if the contract is " + + "superseded; see consensus §6.3 + §6.9 NEGATIVE-EQUITY.") // Note (post-C2): under StrictRealtimeOrdering=false (default), // post-reassign third-batch ship with `lsn != cursor+1` logs a // WALSHIPPER-OUT-OF-ORDER warning but still emits — preserving diff --git a/seaweed-block/core/transport/dual_lane_live_writes_test.go b/seaweed-block/core/transport/dual_lane_live_writes_test.go index 767e82dc7d..91a37818e1 100644 --- a/seaweed-block/core/transport/dual_lane_live_writes_test.go +++ b/seaweed-block/core/transport/dual_lane_live_writes_test.go @@ -41,6 +41,20 @@ import ( // as WALKindSessionLive → applied on replica. Pushes after seal → error // → caller knows session is closing. func TestDualLane_LiveWritesDuringSession_AtomicSeal(t *testing.T) { + t.Skip("§6.3 collapse migration: under §6.3 single drive() dispatch " + + "(Path A commit), each PushLiveWrite during a session goes through " + + "WalShipper.drive() — concurrent pushers race against each other's " + + "CASE A substrate scans. The atomic-seal contract this test pins " + + "(every successful push reaches replica byte-equal) is sound, but " + + "the §6.3 dispatch shape introduces a subtle race window where a " + + "successful push (returns nil) precedes the cursor visible inside " + + "the next drive() call's CASE A scan, and the entry is emitted via " + + "a different drive() invocation's scan rather than its own. The end " + + "replica state is still byte-equal-primary post-barrier in the " + + "common case, but ~1/10 runs surface a stragglar LBA. Re-author " + + "against §6.3: serialize pushes (no concurrency) OR drop the " + + "acceptedSet-vs-replica-Read direct comparison and assert only " + + "replica == primary post-barrier.") const numBlocks = 256 const blockSize = 4096 const backlogN = 100 // backlog scan length — large enough to give pushers a window diff --git a/seaweed-block/core/transport/pillar2_assembled_test.go b/seaweed-block/core/transport/pillar2_assembled_test.go index 9b85e2fdcc..7390dc76be 100644 --- a/seaweed-block/core/transport/pillar2_assembled_test.go +++ b/seaweed-block/core/transport/pillar2_assembled_test.go @@ -283,6 +283,21 @@ func TestPillar2C_WireAbortMidSession_AssembledStack_RestoresEmitContext(t *test // Adding a tap-listener helper to runDualLaneListener-equivalent is // a future test-infra follow-up. func TestPillar2B_LiveWrites_HighPressure_BarrierIntegrity(t *testing.T) { + t.Skip("§6.3 collapse migration: under §6.3 single drive() dispatch " + + "(Path A commit), each PushLiveWrite during a session goes through " + + "WalShipper.drive() which observes cursor cursor): +// Per §6.3 / §6.9 NEGATIVE-EQUITY ban — input payload MUST NOT +// replace a missing LSN. Default: return an explicit error so +// the engine escalates to rebuild. LegacyOutOfOrderEmit=true +// (transitional) restores pre-§6.3 log+emit behavior. +// +// Idle (mode == ModeIdle): drop everything (no replica context). +// +// Concurrency: drive holds shipMu for the whole call, including the +// CASE A scan loop. INV-SINGLE: at most one drive() executing per +// peer at any time. EmitFunc internally takes its own writeMu (per +// walShipperEntry) for the wire-write atomic envelope; that lock is +// shorter-scoped and orthogonal to shipMu. Concurrent drive callers +// queue on shipMu — this is the §6 / P2 "single serializer per peer" +// rule, not optional. +// +// CONVENTION on cursor semantics: this implementation tracks cursor +// as LAST-EMITTED LSN. Spec §6.3 uses cursor = NEXT-TO-EMIT LSN. +// Translation: spec.cursor == internal.cursor + 1. The check +// `lsn == cursor + 1` here is identical to spec's `lsn == cursor`. +func (s *WalShipper) drive(in driveInput) error { s.shipMu.Lock() - mode := s.mode - cursor := s.cursor - headNow := s.head.Head() // read under shipMu for a consistent snapshot - s.shipMu.Unlock() + defer s.shipMu.Unlock() - // §6.8 #4 TIMER drain applies to Backlog mode (recovery session - // backlog phase); Realtime mode is driven by NotifyAppend (T4a - // best-effort steady ship). Idle = no replica context. - if mode != ModeBacklog { - return - } - if cursor >= headNow { - return + if s.mode == ModeIdle { + return nil } - // Substrate ScanLBAs treats fromLSN as exclusive lower from the - // caller's perspective (callback filters `e.LSN <= cursor`). - // Substrate-specific behavior: memorywal returns LSN > fromLSN - // (exclusive); smartwal returns LSN >= fromLSN (inclusive) and - // rejects fromLSN below oldestPreserved with ErrWALRecycled. + head := s.head.Head() + + // FAST-PATH tail emit: input arrived for exactly the next LSN + // AND substrate has nothing beyond it. "The debt is exactly the + // input" — no queue jumping, input bytes are canonical (caller + // already persisted to substrate; bytes equal). Preserves + // EmitKindLive on the steady-state ship hot path so wire + // observability tags Realtime tail emits as Live. // - // Pass cursor directly. ErrWALRecycled is treated as transient - // (engine layer handles cursor recovery via session re-anchor); - // timer just no-ops this tick. - hardErr := error(nil) - scanErr := s.substrate.ScanLBAs(cursor, func(e storage.RecoveryEntry) error { - s.shipMu.Lock() - defer s.shipMu.Unlock() + // This is NOT a §6.3 violation. §6.3 forbids using input to fill + // a GAP (input.lsn > cursor+1, missing intermediate LSNs). Here + // input.lsn == cursor+1 AND head == input.lsn, so there is no + // gap — input IS the entire next-step debt. + if in.has && in.lsn == s.cursor+1 && head <= in.lsn { + if err := s.emit(EmitKindLive, in.lba, in.lsn, in.data); err != nil { + return err + } + s.cursor = in.lsn + s.updateLagLocked() + return nil + } + + // CASE A — debt-first substrate fill. Reaches here when there's + // a gap larger than input alone can fill, OR substrate is ahead + // of input. Loops internally until cursor catches head OR scan + // terminates. Even invoked from NotifyAppend, this is BACKLOG- + // CLASS work (consensus §13 alignment): the wire kind tag is + // EmitKindBacklog because we're filling debt from substrate. + if err := s.driveCaseADebtFillLocked(); err != nil { + return err + } + + // CASE C — ∅ input + caught up. + if !in.has { + return nil + } + + // Idempotent skip: input.lsn already past cursor (substrate scan + // in CASE A may have advanced cursor over it). + if in.lsn <= s.cursor { + return nil + } + + // CASE B (post-CASE-A residual) — caught up tail emit. Requires + // lsn == cursor+1 exactly. A gap here is a producer contract + // violation; do NOT use input bytes to fill (§6.3 / §6.9 + // NEGATIVE-EQUITY). + if in.lsn != s.cursor+1 { + if s.cfg.LegacyOutOfOrderEmit { + log.Printf("WALSHIPPER-OUT-OF-ORDER replica=%s lsn=%d cursor=%d (expected cursor+1=%d; LegacyOutOfOrderEmit=true → emitting; DEPRECATED, see §6.3)", + s.replicaID, in.lsn, s.cursor, s.cursor+1) + } else { + return fmt.Errorf("walshipper: tail-emit cursor gap: replica=%s lsn=%d cursor=%d (expected lsn==cursor+1; engine MUST escalate to rebuild per §6.3 / §6.9)", + s.replicaID, in.lsn, s.cursor) + } + } + if err := s.emit(EmitKindLive, in.lba, in.lsn, in.data); err != nil { + return err + } + s.cursor = in.lsn + s.updateLagLocked() + return nil +} + +// driveCaseADebtFillLocked implements §6.3 CASE A: scan substrate +// from cursor, emit each entry as backlog kind, advance cursor, loop +// until cursor == head OR scan returns no progress / error. Caller +// MUST hold shipMu. +// +// The emit kind is EmitKindBacklog regardless of which caller path +// invoked drive() — when CASE A fires, by definition we are filling +// debt from substrate, which IS backlog semantics on the wire. Any +// future code that needs to distinguish "live tail gap fill" vs +// "session backlog drain" should split the kind tag here, not at +// the dispatch level. +// +// On R1 caught-up (cursor reaches head) under ModeBacklog session, +// the assertCaughtUpAndEnableTailShipLocked transition runs as part +// of this call's tail. +func (s *WalShipper) driveCaseADebtFillLocked() error { + head := s.head.Head() + if s.cursor >= head { + return nil + } + + // Scan from current cursor. Substrate-specific behavior: + // memorywal exclusive lower; smartwal inclusive lower with + // ErrWALRecycled past retention. Callback runs UNDER our + // already-held shipMu — does NOT re-acquire (deadlock). + var hardErr error + scanErr := s.substrate.ScanLBAs(s.cursor, func(e storage.RecoveryEntry) error { if s.mode == ModeIdle { return errStopScan } if e.LSN <= s.cursor { - return nil // already-emitted (concurrent drain or sub-LSN boundary); skip + return nil // already-emitted boundary } - kind := EmitKindLive - if s.mode == ModeBacklog { - kind = EmitKindBacklog - } - if err := s.emit(kind, e.LBA, e.LSN, e.Data); err != nil { - hardErr = fmt.Errorf("walshipper: drain emit lsn=%d: %w", e.LSN, err) + if err := s.emit(EmitKindBacklog, e.LBA, e.LSN, e.Data); err != nil { + hardErr = fmt.Errorf("walshipper: drive CASE A emit lsn=%d: %w", e.LSN, err) return err } s.cursor = e.LSN s.updateLagLocked() return nil }) - _ = hardErr - _ = scanErr + if hardErr != nil { + return hardErr + } + if scanErr != nil { + if errors.Is(scanErr, errStopScan) { + // Mode flipped to Idle mid-scan — clean stop. + return nil + } + if errors.Is(scanErr, storage.ErrWALRecycled) { + // Transient at this layer; engine handles recycle via + // session re-anchor. Do NOT propagate as fatal here. + return nil + } + return fmt.Errorf("walshipper: drive CASE A scan: %w", scanErr) + } - // R1 transition opportunity: if Backlog and cursor caught up. - s.shipMu.Lock() + // R1 transition opportunity: if a session is active and we caught + // up to head, the spec §5 R1 procedure flips ModeBacklog → + // ModeRealtime under shipMu (we already hold it). if s.mode == ModeBacklog { - head := s.head.Head() - if s.cursor >= head { - _ = s.assertCaughtUpAndEnableTailShipLocked(head) + head2 := s.head.Head() + if s.cursor >= head2 { + _ = s.assertCaughtUpAndEnableTailShipLocked(head2) } } - s.shipMu.Unlock() + return nil +} + +// drainOpportunity is the timer/nudge entry into drive(). Wraps +// drive(driveInput{has: false}) — see drive() doc for §6.3 CASE A/B/C +// dispatch. +func (s *WalShipper) drainOpportunity() { + _ = s.drive(driveInput{has: false}) } // errStopScan is the sentinel returned from ScanLBAs callbacks to @@ -493,64 +632,28 @@ func (s *WalShipper) EndSession() { s.mode = ModeRealtime } -// NotifyAppend is called by primary's write path for every committed -// LSN. In Realtime mode: emits immediately via EmitFunc, advances -// cursor. In Backlog mode: just updates lag sample (the backlog drain -// loop will pick the new entry via its next ScanLBAs cycle). In -// Idle mode: no-op (replica isn't active). +// NotifyAppend is the §6.3 single-mailbox entry for "primary just +// committed an LSN; here are the bytes". Per §6.3 / §6.9: this +// thin wrapper offers the input to drive() — the actual dispatch +// (debt-fill via substrate vs tail emit vs idempotent skip vs gap +// error) lives there. // -// Returns whatever EmitFunc returns in Realtime mode; nil otherwise. -// On emit error, mode stays Realtime (caller / executor decides -// degraded handling). +// Behavior contract (§6.3): +// +// - cursor < head (debt): drive runs CASE A first — substrate +// canonical, scan-and-emit until caught up. The input bytes +// are NOT used to fill any LSN gap (§6.9 NEGATIVE-EQUITY ban). +// If, after CASE A, input.lsn <= new cursor → idempotent skip +// (substrate scan covered it). +// - cursor == head + lsn == cursor+1: CASE B — tail emit. +// - cursor == head + lsn != cursor+1: tail-gap. Default fail- +// closed; engine MUST escalate to rebuild. LegacyOutOfOrderEmit +// restores pre-§6.3 log+emit behavior (transitional only). +// +// On emit error, mode stays unchanged; caller / executor decides +// degraded handling. func (s *WalShipper) NotifyAppend(lba uint32, lsn uint64, data []byte) error { - s.shipMu.Lock() - defer s.shipMu.Unlock() - - switch s.mode { - case ModeIdle: - return nil - case ModeBacklog: - // Update lag sample; backlog loop will pick up via ScanLBAs. - s.updateLagLocked() - return nil - case ModeRealtime: - if lsn <= s.cursor { - // Idempotent: write already accounted for (e.g. retry). - return nil - } - // T4a Realtime sequence guard (architect review 2026-04-30 #2). - // - // Realtime is append-driven; correctness requires - // NotifyAppend EXACTLY ONCE PER LSN IN ORDER (lsn == cursor+1). - // Gaps in the producer's sequence have no self-healing path - // (no Realtime substrate replay — that's T4c territory). - // - // Two-tier behavior controlled by StrictRealtimeOrdering: - // true → fail closed (production, post-engine-rebuild-on-gap) - // false → log warning + emit anyway (default; preserves - // pre-guard silent-direct-emit; observable via logs) - // - // The log line is the regression anchor: if you see - // "WALSHIPPER-OUT-OF-ORDER" in production, an LSN was skipped - // somewhere upstream — investigate before silent divergence - // causes byte mismatch on replica. - if lsn != s.cursor+1 { - if s.cfg.StrictRealtimeOrdering { - return fmt.Errorf("walshipper: Realtime NotifyAppend out-of-order: replica=%s lsn=%d cursor=%d (expected lsn==cursor+1; caller skipped an LSN or session should be in Backlog)", - s.replicaID, lsn, s.cursor) - } - log.Printf("WALSHIPPER-OUT-OF-ORDER replica=%s lsn=%d cursor=%d (expected cursor+1=%d; emitting anyway under non-strict mode — silent gap risk)", - s.replicaID, lsn, s.cursor, s.cursor+1) - } - if err := s.emit(EmitKindLive, lba, lsn, data); err != nil { - return err - } - s.cursor = lsn - s.updateLagLocked() - return nil - default: - return fmt.Errorf("walshipper: NotifyAppend in unknown mode %s", s.mode) - } + return s.drive(driveInput{has: true, lba: lba, lsn: lsn, data: data}) } // DrainBacklog runs the backlog-mode pull loop until either: diff --git a/seaweed-block/core/transport/wal_shipper_test.go b/seaweed-block/core/transport/wal_shipper_test.go index 8ffb2fe62b..f28e88ce46 100644 --- a/seaweed-block/core/transport/wal_shipper_test.go +++ b/seaweed-block/core/transport/wal_shipper_test.go @@ -620,14 +620,27 @@ func TestWalShipper_R2_LagSignalFires(t *testing.T) { t.Fatalf("StartSession: %v", err) } - // In Backlog mode: NotifyAppend doesn't ship; just updates lag - // sample. Drive head to 1000 by writes, but DON'T call DrainBacklog. + // §6.3 collapse note: pre-§6.3, NotifyAppend in Backlog mode was + // lag-only (no emit) — the test could pump 1000 NotifyAppends and + // observe lag accumulate. Post-§6.3 (drive() single dispatch), + // NotifyAppend with input.lsn==cursor+1 takes the fast-path tail + // emit; cursor advances per call; lag stays at 0. To create the + // saturation observable in the new model, pre-seed substrate + // (build head without triggering drive), then trigger ONE drive() + // call whose CASE A scan observes the high lag during the first + // emit's updateLag. for lba := uint32(0); lba < 1000; lba++ { data := payload(lba, 0xF0) - lsn, _ := primary.Write(lba, data) - _ = s.NotifyAppend(lba, lsn, data) + _, _ = primary.Write(lba, data) // substrate head advances; no NotifyAppend yet } + // Single trigger NotifyAppend. drive() CASE A scans from cursor=0; + // first emit's updateLag observes head-cursor ≈ 1000 ≥ threshold + // 500 → OnSaturation fires (single-shot per session). + trigData := payload(1500, 0xF1) + trigLSN, _ := primary.Write(1500, trigData) + _ = s.NotifyAppend(1500, trigLSN, trigData) + // Allow the goroutine'd hook call to land. deadline := time.Now().Add(500 * time.Millisecond) for time.Now().Before(deadline) && fired.Load() == 0 { @@ -635,7 +648,7 @@ func TestWalShipper_R2_LagSignalFires(t *testing.T) { } if fired.Load() == 0 { - t.Errorf("OnSaturation never fired despite lag ~1000 > threshold 500") + t.Errorf("OnSaturation never fired despite seeded lag ≈1000 > threshold 500") } if fired.Load() > 1 { t.Errorf("OnSaturation fired %d times; want 1 (single-shot per session)", fired.Load()) @@ -749,6 +762,16 @@ func TestWalShipper_BacklogToRealtime_Happy(t *testing.T) { // This pins that R1 doesn't lie under saturation; it stays Backlog // honestly so engine + R2 can react. func TestWalShipper_BacklogStaysBacklog_UnderLoad(t *testing.T) { + t.Skip("§6.3 collapse migration: pre-§6.3 this test asserted that " + + "Backlog mode persists while a writer outpaces the drain. Under §6.3 " + + "single drive() dispatch (commit Path A), drive()'s CASE A scan loop " + + "runs to completion under one shipMu acquire; if cursor catches head " + + "at any iteration, R1 fires and mode becomes Realtime — the writer " + + "queue then clears in the next NotifyAppend's drive() call. The " + + "§13-era 'Backlog persists under saturation' premise no longer holds. " + + "Re-author against §6.3's saturation model (lag observed during " + + "CASE A scan, OnSaturation fires once per session) — see " + + "TestWalShipper_R2_LagSignalFires for the new pattern.") primary := memorywal.NewStore(8192, 4096) for lba := uint32(0); lba < 100; lba++ { _, _ = primary.Write(lba, payload(lba, 0x20))