Files
seaweedfs/seaweed-block/core/recovery/bitmap.go
T
Ping QiuandClaude Opus 4.7 107ef82c43 G7-redo POC: dual-lane recovery package + memorywal substrate + pin-floor wire design (#11)
* G7-redo POC: dual-lane recovery package — mechanism + e2e

Self-contained package at core/recovery/ implementing the dual-lane
rebuild/recover algorithm per v3-recovery-live-line-backlog-spec.md.
Independent of core/transport (no integration yet — that lands as a
separate PR per architect ruling: "parallel + flag, don't replace
existing path until one happy path runs green alongside").

Layer 1 (receiver-side mechanism):
- bitmap.go: RebuildBitmap, per-LBA WAL-wins-base flag.
  INV-DUAL-LANE-WAL-WINS-BASE; no internal lock (V2-faithful).
- rebuild_session.go: RebuildSession with ApplyBaseBlock /
  ApplyWALEntry(kind, ...) / MarkBaseComplete / TryComplete.
  TryComplete = baseDone ∧ walApplied ≥ targetLSN
  (INV-SESSION-COMPLETE-ON-CONJUNCTION-LAYER1).

Layer 2 (primary-side orchestration):
- peer_ship_coordinator.go: PeerShipCoordinator with phase enum
  (Idle / DrainingHistorical / SteadyLiveAllowed), pin_floor
  management, and RouteLocalWrite. Per architect ruling on
  CHK-NO-FAKE-LIVE-DURING-BACKLOG: while session is non-Idle,
  RouteLocalWrite returns SessionLane regardless of phase.
  SteadyLiveAllowed is publication-permission, not a routing gate.

Wire (core/recovery/wire.go):
- 6 frame types (SessionStart, BaseBlock, BaseDone, WALEntry,
  BarrierReq, BarrierResp).
- WALEntry carries a Kind byte (Backlog / SessionLive) for
  observability; explicitly NOT a convergence proof.

Sender / Receiver (core/recovery/sender.go, receiver.go):
- Sender takes context.Context; defer always sets sealed=true and
  calls coord.EndSession (closes architect-flagged "receiver fails
  early; does sender still seal" question).
- Sender flow: SessionStart → base lane → BaseDone → backlog scan
  → wait Close() | ctx.Done() → drainAndSeal → TryAdvance →
  barrier.
- POC: SEQUENTIAL phases — backlog completes before live writes
  drain. Spec §3.2 #3 (single ordered queue with LSN-real-time
  interleave) is the next milestone, NOT satisfied by this POC.
  Documented in doc.go.

Tests (e2e_test.go + per-file unit tests):
- Happy path, live writes during session, atomic seal under push
  vs Close race, kind-count pinning across backlog/live split.
- 21/21 PASS. Race tests need Linux for -race; Windows host
  cannot enable race detector under cross-compile.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* G7-redo POC: Layer 3 failure taxonomy + integration stub

Wraps every error path in sender / receiver / bridge with a typed
*Failure carrying {Kind, Phase, Underlying}. Engine integration code
(later) inspects via errors.As / AsFailure to drive retry budget.

failure.go:
- FailureKind enum (8 values): Wire, Substrate, Contract are
  retryable; Protocol, Cancelled, SingleFlight, WALRecycled,
  Unknown are not. Matrix pinned by failure_test.go.
- Phase enum (13 values) tags where in the session lifecycle the
  failure surfaced. Diagnostic only — not part of the retry
  decision.
- AsFailure(err) helper for callers; nil-safe Error()/Retryable().

integration_stub.go:
- PrimaryBridge / ReplicaBridge demonstrate the CommandExecutor-
  shaped surface (StartRebuildSession / PushLiveWrite /
  FinishLiveWrites / OnSessionStart / OnSessionClose) WITHOUT
  touching core/transport. Architect priority #1: "出一条薄链路
  早一点发现 lifecycle/回调不匹配".
- StartRebuildSession synchronously calls coord.StartSession
  before spawning the goroutine, so callers reading
  coord.RouteLocalWrite immediately after it returns
  deterministically observe a non-Idle phase.

Tests:
- TestFailure_RetryableMatrix pins all 8 kinds.
- TestIntegrationStub_FailureTypedOnReceiverDown — peer closes
  conn before any frame → typed Failure(Wire, SendStart|BaseLane),
  Retryable=true.
- TestIntegrationStub_FailureTypedOnCancellation — ctx cancel
  during AwaitClose → Failure(Cancelled, AwaitClose),
  Retryable=false.
- 33/33 PASS total across the package.

Out of scope (next milestones):
- BaseBatchAck → pin_floor incremental advancement (architect #3).
- Single-queue LSN real-time interleave (architect #2 / spec §3.2 #3).
- Integration with core/transport (parallel-flag PR).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* core/storage/memorywal: V2-faithful in-memory WAL substrate

memorywal.Store is the third LogicalStorage implementation alongside
BlockStore (current-state map) and WALStore (on-disk WAL+extent).
Like BlockStore it has zero on-disk dependency, but unlike BlockStore
it uses an append-only record log so per-LSN replay semantics are
preserved:

  - Each Write captures its contemporaneous LSN; the record is
    never rewritten in place.
  - ScanLBAs(fromLSN, fn) emits each record's REAL write-time LSN
    (RecoveryModeWALReplay, V2-faithful).
  - 3 writes to the same LBA produce 3 ScanLBAs entries, NOT 1
    deduped entry — matches walstore, not BlockStore.
  - AdvanceWALTail(newTail) trims records and sets an explicit
    `recycleFloor`; subsequent ScanLBAs(fromLSN < recycleFloor)
    returns storage.RecoveryFailure(Kind=WALRecycled), and
    errors.Is(err, ErrWALRecycled) holds via Unwrap.
  - AppliedLSNs returns a real per-LBA highest-LSN map (BlockStore
    returns ErrAppliedLSNsNotTracked).

The recycleFloor / retainStart split avoids a spurious-recycled
trap: ApplyEntry installing a record at a high LSN (e.g. lsn=100)
without prior writes does NOT make ScanLBAs(0) think recovery is
impossible — recycledFloor is bumped only by AdvanceWALTail.

Conformance: added to the existing core/storage contract test
table. All 12 TestContract_* tests now run against three impls:
BlockStore-mem / WALStore / MemoryWAL — same assertions, all green.

Refactor required: contract_test.go moved from package `storage`
to package `storage_test` (external) so it can import memorywal
without a cycle. The shared `makeBlock` helper used by other
internal _test files (flusher_test, walstore_test) moved to a
new `testhelpers_test.go` package `storage` to keep them building.

Production placement note: this lives next to BlockStore + WALStore
in the existing substrate tree (no `core/storage/` reshuffling).
Use it from any test/component that needs WAL-replay semantics
without on-disk overhead — recovery package POC + future
component-level rebuild scenarios.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* docs: recovery INV ↔ test mapping (G7-redo POC)

Per architect closure on g7-redo/dual-lane-recovery-poc: maps every
declared INV (Layer 1 mechanism / Layer 2 orchestration / Layer 3
taxonomy / substrate contract conformance) to its pinning test
function + file:line at branch HEAD.

Sections:
- Layer 1 — receiver-side mechanism (3 INVs, all pinned).
- Layer 2 — primary-side orchestration (9 INVs; 7 pinned, 2 forward
  pending #3 BaseBatchAck → pin_floor).
- Spec CHK-* — phase / barrier / no-fake-live (3 checks, all pinned).
- Substrate contract — 12 LogicalStorage contract tests run across
  BlockStore / WALStore / MemoryWAL (3 impls) + 5 MemoryWAL-specific
  semantics not satisfiable by BlockStore.
- Layer 3 failure taxonomy — 6 INVs, all pinned (matrix + nil-safety
  + extraction + wire/cancel surface + always-seal-on-error).
- Forward-direction — 6 INVs declared but deliberately untested with
  target milestones (pin/recycle wiring, sparse base, overlap-history
  bitmap-as-claim, single-queue interleave, ship-phase observability).

Test sweep summary: 83 test results across the package; race-detector
status flagged for Linux CI.

Includes how-to-keep-current procedure for follow-up PRs.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* docs: pin_floor / BaseBatchAck wire design (#3 architect priority)

Single source of truth for the next milestone — receiver→primary
ack cadence, SetPinFloor semantics, retention inequality, and the
proposed FailurePinUnderRetention kind. Design only; implementation
lands on a follow-up branch.

Closes the two forward-direction INVs in the inv-test-map's
Layer-2 section once impl lands:
  - INV-PIN-ADVANCES-ONLY-ON-REPLICA-ACK
  - INV-PIN-COMPATIBLE-WITH-RETENTION

Cross-references added:
  - core/recovery/doc.go: pin INV section now points at the design
    doc sections (§3 cadence, §4 semantics, §5 retention inequality).
  - docs/recovery-inv-test-map.md: forward rows updated from
    "_Pending #3_" to "design landed; impl pending #3" with
    explicit pointer to the design doc.

Open questions for architect (in §11 of the design doc):
  1. New FailurePinUnderRetention kind vs reuse FailureWALRecycled
     with a Phase discriminator. Recommend new kind.
  2. SetPinFloor signature: parameter for primary's S boundary vs
     coordinator-held callback. Recommend parameter.
  3. Wire compat at production wiring time: keep new frame or fold
     into MsgShipEntry with a flag. Recommend keeping new frame.

Out of scope (explicit, §10):
  - §3.2 #3 single-queue real-time interleave (architect priority #2).
  - Wiring into core/transport.
  - WAL recycle path consuming MinPinAcrossActiveSessions.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* docs: pin-floor wire design — architect ACK on §11 (2026-04-29)

All three open questions resolved per architect ratification:
1. FailurePinUnderRetention = new FailureKind (not reused).
2. SetPinFloor takes explicit parameter (not callback).
3. Independent frame 0x07 (not piggyback).

Implementation gates the next branch g7-redo/pin-floor.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-29 16:19:50 -07:00

74 lines
2.5 KiB
Go

package recovery
// RebuildBitmap is the per-LBA "WAL lane has won base lane" flag for one
// rebuild session. It carries no internal locking — the owning
// RebuildSession serializes all access via its own mutex
// (INV-BITMAP-NO-INDEPENDENT-LOCK; V2-faithful).
//
// Semantics (INV-DUAL-LANE-WAL-WINS-BASE):
//
// WAL lane apply ApplyWALEntry → bitmap.MarkApplied(lba)
// Base lane query ApplyBaseBlock → if bitmap.IsApplied(lba): skip
//
// "Mark on apply, not on receive" — the bit is set after the WAL
// entry is durably written to the substrate, so a race where base
// arrives between WAL receive and WAL apply still has base lose
// (because base's apply path takes the same session mutex and sees
// the bit already set, OR loses the lock race and writes first then
// gets overwritten by the WAL apply that follows).
type RebuildBitmap struct {
bits []uint64 // bit per LBA; idx = lba/64, mask = 1 << (lba%64)
n uint32 // number of addressable LBAs
}
// NewRebuildBitmap allocates a bitmap covering [0, numBlocks).
func NewRebuildBitmap(numBlocks uint32) *RebuildBitmap {
words := (numBlocks + 63) / 64
return &RebuildBitmap{
bits: make([]uint64, words),
n: numBlocks,
}
}
// MarkApplied records that the WAL lane has applied this LBA.
// Subsequent ApplyBaseBlock for the same LBA must be skipped.
// Caller MUST hold the session mutex.
func (b *RebuildBitmap) MarkApplied(lba uint32) {
if lba >= b.n {
return
}
b.bits[lba/64] |= 1 << (lba % 64)
}
// IsApplied reports whether MarkApplied has been called for this LBA.
// Caller MUST hold the session mutex.
func (b *RebuildBitmap) IsApplied(lba uint32) bool {
if lba >= b.n {
return false
}
return b.bits[lba/64]&(1<<(lba%64)) != 0
}
// ShouldApplyBase is the inverted query base lane uses: returns true
// when the base block at this LBA still needs to be installed.
// Caller MUST hold the session mutex.
func (b *RebuildBitmap) ShouldApplyBase(lba uint32) bool {
return !b.IsApplied(lba)
}
// AppliedCount returns the number of LBAs that have been marked
// (diagnostic only).
func (b *RebuildBitmap) AppliedCount() int {
n := 0
for _, w := range b.bits {
// popcount; Go 1.9+ math/bits.OnesCount64 is fine but we keep
// it inline to avoid the import for one diagnostic.
v := w
v = v - ((v >> 1) & 0x5555555555555555)
v = (v & 0x3333333333333333) + ((v >> 2) & 0x3333333333333333)
v = (v + (v >> 4)) & 0x0f0f0f0f0f0f0f0f
n += int((v * 0x0101010101010101) >> 56)
}
return n
}