Commit Graph
15 Commits
Author SHA1 Message Date
pingqiu ec5f91ddf9 transport: name recovery command band as frontier hint 2026-05-02 01:33:30 -07:00
pingqiu bd6f475b9b transport: advance live ship cursor after recovery 2026-05-01 23:53:34 -07:00
pingqiu 8c4aa52392 transport: refresh live ship session after recovery 2026-05-01 22:27:21 -07:00
pingqiu ca04592639 G5-5C #7: per-peer adapter wiring (production fix for hardware-revealed gap)
Per architect ruling 2026-04-27 (Option B: absorb fix in G5-5C as
Batch #7), this batch fixes the host wiring gap revealed by
hardware run 3:

ROOT CAUSE: cmd/blockvolume constructs ONE *VolumeReplicaAdapter
for the host's own slot (Identity.ReplicaID = primary's-own-slot).
G5-5C ProductionProbeFn forwarded peer probe results into that
adapter. Engine apply.go:117-128 checkReplicaID correctly drops
events targeted at peer (replicaID != Identity.ReplicaID) as
wrong_replica. Result: probe success on wire, but no StartCatchUp
ever dispatched.

FIX: per-peer adapter, each tracking its peer's identity, each
wired to dispatch engine commands to that peer's transport executor.

NEW FILES:
- core/host/volume/peer_command_executor.go (~140 LOC)
  PeerCommandExecutor adapts peer's transport.BlockExecutor to
  satisfy adapter.CommandExecutor. Most methods delegate verbatim
  (Probe, StartCatchUp, StartRebuild, StartRecoverySession,
  InvalidateSession, Fence). Two value-adds:
    1. SetOnSessionStart/Close intercept inner callbacks to drive
       peer.SetState (Degraded → CatchingUp on start; CatchingUp →
       Healthy on Success). Without this, peer state stays Degraded
       after successful catch-up and probe loop keeps polling.
    2. PublishHealthy/Degraded translate engine verdicts to
       peer.SetState/peer.Invalidate. Inner executor's
       Publish* are log-only; runtime peer state machine is what
       gates Ship + ProbeIfDegraded.

- core/host/volume/peer_adapter_registry.go (~140 LOC)
  PeerAdapterRegistry maps ReplicaID → *VolumeReplicaAdapter.
  OnPeerAdded constructs PeerCommandExecutor + adapter, primes
  with AssignmentObserved for the peer's identity. OnPeerRemoved
  drops the adapter. AdapterFor lookups for the router probeFn.
  Self-replicaID guard refuses host-own-slot registration.
  Idempotent double-add. Lineage-bump produces fresh adapter.
  Close drops everything.

UPDATED FILES:
- core/replication/volume.go: ConfigurePeerLifecycleHook (onAdded,
  onRemoved). Hook fired from UpdateReplicaSet add/remove/lineage-
  bump teardown paths under v.mu. Configure-once contract; replays
  current peer set on configure (so registry catches up to peers
  added before hook).
- core/host/volume/probe_loop_wiring.go: AdapterRouter signature
  type added. ProductionProbeFn now takes router instead of single
  adapter; routes per-peer; nil-router and missing-peer paths
  fail-closed.
- cmd/blockvolume/main.go: construct PeerAdapterRegistry; wire
  ConfigurePeerLifecycleHook; pass registry.AdapterFor to
  ProductionProbeFn. Failure paths cleaned up the same way as
  prior wire steps.
- core/host/volume/boundary_guard_test.go: PCDD-STUFFING-001 fence
  now allows TWO sites for adapter.AssignmentInfo composite
  literals: decodeAssignmentFact (master decode boundary) AND
  OnPeerAdded (per-peer engine identity priming, G5-5C Batch #7).
  Other sites still fail.
- core/replication/component/g5_5c_restart_catchup_test.go:
  configureProbeLoopOnCluster now uses AdapterRouter signature
  (closure over c.primary.adapters[0]).

NEW TESTS (15 total, all PASS):
- peer_adapter_registry_test.go (7): RegisterAndPrimes,
  DropsAdapter, SelfReplicaIDRefused, DoubleAddIdempotent,
  LineageBumpTeardown, CloseDropsAll, NilSafe.
- peer_command_executor_test.go (5): PublishHealthy → SetState,
  PublishDegraded → Invalidate, SessionStart → CatchingUp,
  SessionClose → Healthy, DelegatesProbe.
- probe_loop_wiring_test.go (3 updated + 2 new):
  NilRouter_ReturnsErrAndDoesNotPanic,
  RouterReturnsNil_ReturnsErr,
  RouterPicksByReplicaID (new — pins per-peer routing contract).

Test results: full ./... regression PASS at 17:58. No behavioral
regression on G5-4 / earlier T4 paths. Component test #6
(restart-catch-up convergence) still PASSES via new router signature.

NEW INV (replaces previously-deferred G5-5D INV):
- INV-G5-5C-PER-PEER-ADAPTER-PER-PEER-ENGINE — production binary
  constructs *VolumeReplicaAdapter per (volume × admitted peer).
  Engine.checkReplicaID correctness preserved.

Next: m01 hardware re-run #4. Expected GREEN within 30s deadline.
2026-04-27 18:09:00 -07:00
pingqiu 59d63f8274 G5-5C #5: cmd/blockvolume flag wiring + production probeFn
Closes the wire between batch 1-4's runtime/engine plumbing and
operator/CLI control. Per architect Batch #5 review 2026-04-27,
each of the 4 self-check items is addressed:

#1 --degraded-probe-interval=0 = OFF
   Default value 0 keeps the loop disabled — preserves G5-4
   behavior. Help text states this explicitly. main.go's
   "if f.degradedProbeInterval > 0" guard means we NEVER call
   ConfigureProbeLoop with a 0 interval (which the loop itself
   would reject anyway via NewProbeLoop). Two layers of defense.

#2 cooldown-base/cap normalization
   ProbeLoopConfig defaults (5s base, 60s cap) match
   PeerProbeCooldown defaults exactly. NewProbeLoop normalizes
   <=0 to defaults; Cap < Base bumps Cap up to Base. CLI flag
   defaults are 5s/60s — matches batch 1/2 contract.

#3 production probeFn
   New file core/host/volume/probe_loop_wiring.go::ProductionProbeFn
   - peer.mu released before executor.Probe (loop discipline; the
     probeFn never touches peer.mu — only Target() which is
     immutable post-construction).
   - transport failure (result.Success == false) → returns non-nil
     err so DefaultProbeResultFn calls OnProbeAttempt(false) and
     backoff advances. Wire-success returns nil so cooldown resets
     to Base regardless of engine's semantic verdict.
   - adapter.OnProbeResult is fed BOTH success and failure facts
     (NormalizeProbe distinguishes). Engine async result NOT mixed
     into transport return value — separation per architect
     guidance.
   - SessionID minted via replication.MintProbeSessionID (new
     atomic counter; distinct from peerSessionIDCounter and
     adapter's own probe sessionID counter — three contexts, three
     counters, no overlap).
   - Defensive guards: nil adapter → fail-closed shim probeFn;
     nil executor → return err; zero lineage → return err;
     ctx.Err() pre-check.

#4 Configure → Start ordering at admit time
   main.go calls ConfigureProbeLoop + StartProbeLoop in sequence
   immediately after replVolume + h.SetReplicationVolume; peers may
   or may not exist yet (master assignment arrives async). Empty
   peer set is safely no-op (covered by Batch 3
   TestVolume_ConfigureProbeLoop_HappyPath); production is just
   the same path with a real adapter.

Replication layer additions:
- ReplicaPeer.Executor() accessor for the probeFn (read-only,
  caller never closes — BUG-005 discipline).
- replication.MintProbeSessionID() — atomic counter for
  runtime-driven probes.

CLI flags (default OFF):
- --degraded-probe-interval (default 0; recommended 5s for prod)
- --degraded-probe-cooldown-base (default 5s)
- --degraded-probe-cooldown-cap (default 60s)
Help text explicitly distinguishes loop interval vs per-peer
cooldown so operators don't conflate the two 5s defaults.

Tests (3 wiring + 1 skip = 4/4 PASS as written):
- TestProductionProbeFn_NilAdapter_ReturnsErrAndDoesNotPanic
- TestProductionProbeFn_TransportFailure_ReturnsErr — dial to
  127.0.0.1:1 (reserved/closed) → result.Success=false → non-nil
  err returned + adapter received the failure fact.
- TestProductionProbeFn_ContextCancelled_ReturnsErr
- TestProductionProbeFn_ZeroLineage_ReturnsErr — skipped (defensive
  guard verified by compile-time path; zero-lineage construction
  requires package-private peer access, deferred to integration).

Full ./... regression: PASS (every package, including host 2-min
suite, frontend/iscsi 31s suite, frontend/nvme 61s suite). No
behavioral regression on G5-4 / earlier T4 paths.

Next batch (G5-5C #6): component restart-catch-up test exercising
the full primary→engine→catch-up loop without iscsi/iptables
harness. After that: m01 hardware re-run.
2026-04-27 16:56:48 -07:00
pingqiu 5187083fc6 G5-5 logging: INFO line on UpdateReplicaSet success + adopted-as-primary
QA round 6 finding: primary log silent on replication; can't
disambiguate 'peers=0 delivered' (timing gap) from 'peers=N delivered
but ship failed' (TCP/network). Pre-existing log discipline only
emits on the FAILURE branches:
  - line 488: recording supersede (when fact.ReplicaID != self)
  - line 502: UpdateReplicaSet failed

Add INFO logs on the success path so operators / hardware-test
harness can see what's actually being installed without -v / debug
flags:

  blockvolume: volume v1 replication UpdateReplicaSet ok (gen=N,
    peers=K): [r2@192.168.1.184:9221 ...]
  blockvolume: volume v1 adopted as PRIMARY at r1@1 (EV=1)

Small log footprint (one line per fact emission, fact emissions
are rare). Production-acceptable verbosity. No behavior change.

Tests: cmd/blockvolume integration test still PASS (16.4s);
core/host/volume green.

Refs: QA round 6 — primary-fail.log silence.
2026-04-27 00:39:42 -07:00
pingqiuandClaude Opus 4.7 702c661f87 G5-5 implementation: instrumentation + verifier + m01 orchestration
Per architect-ratified mini-plan v0.3 §1 file map. Three additions
(no engine/adapter behavior changes per architect §6 binding):

1. /status/recovery endpoint (opt-in, loopback-only, default off)
   - core/host/volume/status_server.go: handler + EnableRecoveryEndpoint()
   - core/host/volume/projection_bridge.go: AdapterProjectionView.EngineProjection()
     accessor returns the underlying engine.ReplicaProjection (Mode/R/S/H/
     RecoveryDecision/Reason). Surfaces existing engine state via HTTP;
     no engine code change.
   - cmd/blockvolume/main.go: --status-recovery CLI flag (default off);
     calls status.EnableRecoveryEndpoint() when set
   - core/host/volume/status_server_test.go: 3 new tests
     (Disabled→404, Enabled→200+fields, WrongVolume→404)

2. core/storage.OpenReadOnly + WALStoreReader
   - Read-only walstore opener for hardware byte-equal verification.
     Opens O_RDONLY, runs Recover() to populate dirty map, exposes
     Read(lba) only (no Write/Sync surface). Caller must ensure no
     concurrent writer.
   - core/storage/walstore_readonly.go + walstore_readonly_test.go
     (round-trip write→close→OpenReadOnly→Read passes; missing-file
     fence)

3. cmd/m01verify standalone helper (build-tag m01verify)
   - Separate cmd subpackage so it doesn't collide with blockvolume's
     main(). Builds only with `go build -tags m01verify`.
   - Opens replica's walstore via storage.OpenReadOnly, calls Read(lba)
     per LBA in target range, SHA-256 vs --expected-pattern (single hex
     byte) or --expected-file (binary payload). Prints OK / MISMATCH +
     exit 0/1.
   - Architect REVISE round 51: NO raw .extent peek; storage abstraction
     is the only authoritative read path.

4. scripts/iterate-m01-replicated-write.sh — full G5-5 orchestration
   - Replaces v0.1 skeleton's TODO scenario bodies with real verify
     steps matching mini-plan v0.3 §2 acceptance criteria #1-#6.
   - 6 verify functions: cluster_ready, byte_equal (kernel iSCSI write
     + m01verify storage-aware compare), network_catchup (iptables
     drop + /status/recovery R/H polling), restart_catchup (SIGTERM
     replica + restart same --durable-root + R/H polling), race_stress
     (TestG54_BinaryWiring x10 -race on m01), full_suite (go test ./...).
   - Build phase compiles all 3 binaries on m01 (master + volume + verify)
     and scp blockvolume + m01verify to M02. SMB share path used in
     prior smoke is replaced by direct scp for simpler dependency.

Acceptance gates per mini-plan v0.3 §2:
  #1-#6 covered by script verify steps; m01 hardware run is QA's
  responsibility per `v3-batch-process.md §14` (sw drafts, QA verifies).
  #7 (v3-dev-roadmap.md update at gate-close) deferred to §close.

Full V3 regression: 23/23 packages green from local Windows run
(includes G5-4 binary integration test still passing at 16.4s; new
status_server tests pass; new walstore_readonly tests pass; m01verify
builds clean under -tags m01verify).

Hard binding preserved: zero engine/adapter behavior changes. The
/status/recovery endpoint surfaces an already-computed projection;
walstore.OpenReadOnly is a new read-only wrapper around existing Recover
+ Read; no semantic changes to either.

Refs: sw-block/design/v3-phase-15-g5-5-mini-plan.md v0.3

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-26 21:44:17 -07:00
pingqiuandClaude Opus 4.7 be9823b872 G5-4: bind T4 replication stack into cmd/blockvolume
Mirror T4d-4 part B's WithEngineDrivenRecovery() (component framework
binding at core/replication/component/cluster.go:357-369) into the
production binary. Constructs ReplicationVolume + ReplicaListener
per volume and wires both into the host lifecycle, so replicas can
accept incoming WAL traffic and primaries can fan out writes.

Architect bindings (mini-plan v0.4 §7.1 round 50):

  Replica readiness — frontend.Projection.Healthy is reused with
  role-aware semantics: primary reaches Healthy=true via the existing
  caught-up + fence-acked path (engine.ModeHealthy); replica role
  (assigned to SUPPORTING; engine apply skips OnAssignment via
  recordOtherLine) keeps Healthy=false indefinitely. Frontend bind
  (--iscsi-listen / --nvme-listen) is operator-controlled per role:
  not passed for replicas. G5-4.5 integration test uses precise
  assertion names (replica MUST NOT report Healthy=true).

  --ctrl-addr reuse REJECTED — verified ReplicaListener should bind
  on --data-addr instead. transport executor's Probe + Ship paths
  dial peer.DataAddr (executor.go:303); listener must bind on the
  address master mints into AssignmentFact.peers[*].DataAddr — i.e.,
  --data-addr. --ctrl-addr stays reserved for future control-plane
  split (no current binder; verified no conflict with NVMe / iSCSI
  / status: each has its own dedicated --*-listen / --status-addr
  flag). Mini-plan v0.4 said "reuse --ctrl-addr"; correct answer
  found during code is --data-addr. PR description carries this
  finding for ratification.

Files changed:
  - core/host/volume/host.go: SetReplicationVolume(rv) + RWMutex
    around h.replication so binary can wire post-New (storage opens
    after host construction).
  - core/frontend/durable/provider.go: EnsureStorage(volumeID) opens
    LogicalStorage role-agnostically (without waiting for Healthy);
    Backend(volumeID) accessor returns the same StorageBackend
    instance dp.Open returns later. Both used by binary main.go.
  - cmd/blockvolume/main.go: after EnsureStorage + RecoverVolume,
    construct ReplicationVolume(volumeID, store) + h.SetReplicationVolume,
    SetWriteObserver on the backend for fan-out, ReplicaListener on
    --data-addr + Serve. Cleanup chain (LIFO): listener.Stop +
    rv.Close BEFORE durableProv.Close (storage borrowed by both).
  - cmd/blockvolume/g5_4_l2_replication_test.go: NEW. L2 subprocess
    integration test — real cmd/blockmaster + 2× cmd/blockvolume over
    TCP with --expected-slots-per-volume 2; asserts primary reaches
    Healthy=true, replica does NOT (role split per architect
    binding), replica's --data-addr accepts TCP (listener bound).

Acceptance criteria status (mini-plan v0.4 §4):
  #1 binary constructs ReplicationVolume   ✅ verified by code review
  #2 in-process role-appropriate ready     ✅ G5-4.5 PASS
  #3 byte-equal primary→replica            ⏸ deferred to G5-5 m01
     (in-process test would need iSCSI/NVMe Go client to drive
     frontend writes; subprocess pin for wiring + role split is in;
     m01 hardware has the kernel iSCSI client tooling)
  #4 stop-restart catch-up convergence     ⏸ deferred to G5-5 m01
     (depends on #3 frontend write driver)
  #5 no regressions                        ✅ full V3 suite green
  #6 10x -race stress                      ⏳ pending m01 verification
  #7 invariant ledger inscription          ✅ 5 INV-BIN-WIRING-* in
     v3-invariant-ledger.md (companion commit in seaweedfs repo)

Refs: sw-block/design/v3-phase-15-g5-4-mini-plan.md v0.4

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-26 17:03:42 -07:00
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
pingqiuandClaude Opus 4.7 71e2e082c0 T4c-1: ProbeReq + ProbeResponse symmetric full-lineage wire + validation
Per architect round-26 Item C.3 (symmetric pair) + round-21 uniform rule
(every authority-bearing wire surface carries full RecoveryLineage).
Probe lineage source per architect Option D (post-QA-sign clarification):
adapter mints transient probe sessionID; executor reads primaryStore
boundary for TargetLSN; engine stays pure semantic reducer; probe
lineage NOT registered in executor.sessions; no SessionPrepared /
Started / Closed lifecycle for probe.

Wire (T4c-1):
- ProbeReq:  32B body — [SessionID][Epoch][EndpointVersion][TargetLSN]
- ProbeResp: 56B body — [32B echoed lineage][8B R][8B S][8B H]
- Both directions: strict decode (short / zeroed lineage / field-order
  drift rejected) mirrored from BarrierResp (T4b-1)

Replica side (replica.go MsgProbeReq):
- decodes lineage; validates via new validateProbeLineage (rejects
  zeros + strictly older epoch/endpointVersion); does NOT advance
  activeLineage (probe is non-mutating; advancing would race ahead of
  in-flight catch-up/rebuild sessionIDs and stale-reject their frames)
- echoes lineage in 32B prefix of response

Primary side (executor.go BlockExecutor.Probe):
- new sessionID parameter (adapter-minted); reads primaryStore.Boundaries()
  for TargetLSN floor (max(1, primaryH)); builds full RecoveryLineage
- sends EncodeProbeReq; validates echoed lineage on response;
  ErrProbeLineageMismatch surfaces in FailReason on mismatch (mirrors
  T4b-2 ErrBarrierLineageMismatch)

Adapter (adapter.go):
- prepareQueuedCommands mints transient probe sessionID for ProbeReplica
  (parallel to FenceAtEpoch); executeCommand passes sessionID through
- CommandExecutor.Probe interface gains sessionID parameter; all test
  executor stubs updated (mockExecutor, closureExecutor, policyClosure,
  restartExecutor, HealthyPath, noop, ops nopExecutor)

INV-REPL-LINEAGE-BORNE-ON-PROBE-PAIR inscribed at catalogue §3.3 close
(both directions carry full lineage; both fail-closed on
short/zeroed/malformed; primary-side filters by full-lineage match).

Tests (21 new across 3 files):
- core/transport/probe_wire_test.go (12 wire pins)
- core/transport/probe_validation_test.go (7 replica + primary contract)
- core/adapter/probe_session_test.go (2 transient sessionID)

Existing test fix:
- TestFailClosed_ProbeDuringRebuild_DoesNotDisturbActiveLineage rewritten
  as TestFailClosed_StaleProbeDuringRebuild_RejectedAndRebuildContinues —
  pre-T4c-1 premise ("probe is observation only, no lineage") is
  invalidated; new contract: stale probe rejected without echo,
  fresh probe authority-bearing
- protocol_test envelope round-trip uses new probe shapes
- transport_test.go probe call passes sessionID

go test ./... -count=1 → all 21 packages green.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-25 02:32:52 -07:00
pingqiuandClaude Opus 4.7 eadc113697 T4c-pre-B: unified StartRecovery command + per-kind runtime policy
Per design memo §7a (architect rounds 29-30): introduce semantic
unification at the command boundary — one StartRecovery covers
catch-up / rebuild / partial-LBA — without unifying runtime
behavior. RecoveryRuntimePolicy carries per-content-kind envelope
(timeout / progress cadence / cancellation mode); engine populates
via DefaultRuntimePolicyFor at emit time.

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

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

go test ./... -count=1 → all 21 packages green.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-25 01:54:52 -07:00
wzcheng99 f6ae66254f T4a-6 follow-up: four QA spot-check fixes (install-or-refuse,
uint32 assertions, host-level tests, matrix honesty)

QA round-21 spot-check flagged four issues in the T4a-6 landing.
All four confirmed correct; this commit addresses them as one
reviewable unit per QA's recommended batch.

Finding #1 (HIGH) — install-or-refuse ordering in Host.streamOnce.
  Previous order was OnAssignment → UpdateReplicaSet, creating a
  window where the adapter's projection flipped Healthy before the
  peer set was installed. StorageBackend.lineageCheck would then
  pass and admit local-only writes with zero fan-out. V2 atomically
  set replicas before admitting writes; V3 had drifted. Fix:

    - Extract applyFact(fact) from streamOnce's inner loop so the
      handler logic is testable in isolation.
    - Invert order: if h.replication != nil, call UpdateReplicaSet
      FIRST. On failure, LOG and RETURN without calling OnAssignment.
      Adapter projection stays at its prior (not-Healthy until a
      fact fully installs) state; StorageBackend keeps writes
      blocked; master's stream replay redelivers the fact and
      natural convergence resumes on the next cycle.
    - Introduce narrow collaborator interfaces (assignmentConsumer,
      replicaSetUpdater) on Host so test doubles can drive applyFact
      without spinning up a real adapter + transport listener. The
      concrete adapter reference is retained as realAdpt for the
      existing Adapter() accessor.

Finding #2 (MEDIUM) — generation aliasing at the uint32 boundary.
  `(epoch << 32) | uint32(ev)` silently aliased distinct authority
  lines whenever either field exceeded 2^32. Fix:

    - Extract generationFitsUint32(epoch, ev) as a named package-
      level function with a descriptive reason string.
    - SubscribeAssignments calls generationFitsUint32 before minting
      the fact; on rejection, logs a structured diagnostic + skips
      the fact (master keeps running — this is a fail-fast on an
      invariant violation upstream, not a master-side error).
    - Pin with two adversarial tests: TestGenerationFitsUint32_
      MaxValidAccepted (epoch = 2^32-1, ev = 2^32-1 passes) and
      _OverflowRejected (epoch = 2^32 and ev = 2^32 each reject
      with reasons naming the offending field).

Finding #3 (MEDIUM) — T4a-5 host wire was uncovered by T4a-6. The
  L2 integration test bypassed Host.streamOnce entirely, so the
  "all T4a commits compose correctly" claim in commit 420a5a1 was
  stronger than what the test proved. Fix:

    - New apply_fact_test.go in core/host/volume with five pins:
      * TestHost_ApplyFact_Self_InstallsReplicaSetBeforeAssignment
        (ordering recorder proves UpdateReplicaSet before
        OnAssignment in the happy path).
      * TestHost_ApplyFact_Self_UpdateReplicaSetFailure_SkipsOnAssignment
        (fail-closed pin for finding #1).
      * TestHost_ApplyFact_Supersede_NeverCallsAdapterOrReplication
        (the supersede branch is unaffected by the reordering).
      * TestHost_ApplyFact_ObserverOnly_NoReplicationCallsOnAssignment
        (nil replication seam still flows to OnAssignment as before).
      * TestDecodeReplicaTargets_FieldCopy (auxiliary; catches
        decoder drift).
    - The commit message and batch-close story now honestly reflect
      that host ordering is covered. Full master → gRPC → host
      subprocess L2 integration deferred to T4b/T4c where the
      durability/recovery path makes it materially more valuable
      (per QA round-21 guidance).

Finding #4 (LOW) — matrix 'non-gating' fiction removed.
  The earlier runMatrix harness had walstore_nongating that
  claimed to demote subtest failures. Go's testing has no clean
  demote-subtest-failure API; the defer-based logic didn't
  actually demote. Replaced with honest naming: walstore is a
  second gating row (passes today under T4a best-effort paths;
  if it ever regresses under BUG-007 the test fails honestly
  and we invest in a real demotion harness then). File header
  comment updated to match.

Verification: full 21-package repo suite green including
core/host (122s integration run) and the 5 new host tests. No
regressions.
2026-04-23 17:30:53 -07:00
wzcheng99 db3be2e58c T4a-5: wire Host authority-callback to ReplicationVolume (P-refined)
Completes the T4a-5.0 §8C.3 Discovery Bridge resolution (Option
P-refined, landed per architect + QA round-19). Extends the
AssignmentFact wire with master-minted peer set + monotonic
generation, adds a separate host-only decode path that does NOT
touch AssignmentInfo (preserves the TestNoOtherAssignment
InfoConstruction AST fence), and wires Host.streamOnce to drive
ReplicationVolume.UpdateReplicaSet after every self-replica
AssignmentFact.

Guardrails (all four from round-19) honored:
  1. decodeAssignmentFact unchanged; AST fence stays green.
  2. decodeReplicaTargets is SEPARATE and produces replication.
     ReplicaTarget + generation, never AssignmentInfo. Adapter +
     engine packages: zero changes.
  3. Peer set is master-minted only. Host does NOT accumulate or
     derive from other-replica facts (option R rejected).
  4. peer_set_generation mandatory on the wire; monotonic guard in
     ReplicationVolume.UpdateReplicaSet.

Changes:

  core/rpc/proto/control.proto
    NEW message ReplicaDescriptor{replica_id, epoch, endpoint_
    version, data_addr, ctrl_addr}. AssignmentFact gains
    `repeated ReplicaDescriptor peers = 7` (excludes self) and
    `uint64 peer_set_generation = 8` (monotonic, master-minted).

  core/rpc/control/control.pb.go + control_grpc.pb.go
    Regenerated via scripts/genproto.sh.

  core/host/master/services.go
    SubscribeAssignments fills fact.Peers via new collectPeers
    helper (reads Publisher.LastPublished for each non-self slot
    in the volume's accepted topology). Generation derived as
    `(info.Epoch << 32) | info.EndpointVersion` — monotonic
    because publisher's lex-dedupe upstream guarantees strictly-
    increasing (Epoch, EV) pairs and Epoch/EV are durable authority
    facts (survives master restart).

  core/host/volume/subscribe.go
    NEW decodeReplicaTargets(fact) ([]replication.ReplicaTarget,
    uint64) — strict field-copy, same discipline as decode
    AssignmentFact. Produces a different output type so the
    AST fence TestNoOtherAssignmentInfoConstruction continues to
    pass.

  core/host/volume/host.go
    Config gains `ReplicationVolume *replication.ReplicationVolume`
    (nil = T0/observer-only; non-nil = T4a-5 production wire).
    streamOnce self-replica branch calls UpdateReplicaSet(gen,
    targets) AFTER adapter.OnAssignment. Non-blocking log on
    error (best-effort; failure does not stop the assignment
    stream).

  core/replication/volume.go
    UpdateReplicaSet signature break (QA option (a), no shim):
      Before: UpdateReplicaSet(targets []ReplicaTarget) error
      After:  UpdateReplicaSet(generation uint64, targets []ReplicaTarget) error

    Three-way generation rule (T4a-5.0 §9.4, QA corrected sw's
    original MaxUint64 sentinel which would have one-way-poisoned
    the monotonic guard):
      - gen == 0: unversioned apply; peer map mutated;
        lastAppliedGeneration NOT advanced. Test/fake-master only.
      - gen > 0 && gen > lastApplied: apply + advance.
      - gen > 0 && gen <= lastApplied: stale; peer map NOT mutated;
        replayedGens counter increments; debug log emits peer-ID-
        set delta (Q2 binding — IDs only, not full target structs).
        Returns nil (idempotent replay is success).

    Empty peer set (N → 0) flows through the same teardown path as
    any N → M-1 removal. No special branch (Q3 binding).

    New state: lastAppliedGeneration uint64 (mu-guarded);
    replayedGens atomic.Uint64 (stats counter, private; public
    Stats() deferred to T4-end observability pass).

    New helpers (internal): peerIDSet, targetIDSet,
    stringSetEqual, formatIDSet (deterministic brace-form
    rendering of peer-ID sets for log diffs).

  core/replication/volume_test.go
    All 8 existing tests migrated to new signature with gen=0
    (unversioned apply preserves previous functional semantics).
    3 new tests (Q1/Q2/Q3 pins):
      9.  UpdateReplicaSet_Generation_MonotonicGuard — advance
          through gens 1, 2, 3; stale replays at gen=2 and gen=3
          (equal is stale); verify replayedGens counter; forward
          progress at gen=4 works. Exercises Q2 differing-peers
          path via the gen=2 replay with original r1+r2 set.
      10. UpdateReplicaSet_GenerationZero_DoesNotAdvanceGuard —
          gen=5 applied, gen=0 applied (peers mutated, last
          Applied stays at 5), gen=3 rejected as stale. Pins the
          correctness of the gen=0 rule vs. the original
          MaxUint64 sentinel which would have failed this test.
      11. UpdateReplicaSet_EmptyPeerSet_AppliesWithTeardown — Q3
          binding three assertions: PeerCount=0 after empty
          apply, all former peers' executor sessions invalidated,
          next OnLocalWrite succeeds as zero-fanout no-op.

Verification: full 20-package repo suite green (core/host: 124s
including supersede_integration_test; core/host/volume: 31ms
confirming AST fence TestNoOtherAssignmentInfoConstruction still
passes; core/replication: all 17 tests green). G-2 tri-line godoc
on every new public surface.

Closes T4a-5.0 §8C.3 Discovery Bridge. Next: T4a-6 L2 subprocess
integration test.
2026-04-23 16:50:01 -07:00
wzcheng99 f5c557074d T1 product closure: readiness bridge + supersede fence + L2 authority move
Addresses three architect review rounds on T1 frontend contract:

Round 1 (L0/L1 only) → Round 2 (real adapter path + product loop):
  - AdapterProjectionView reads engine.ReplicaProjection.Mode
    (engine.ModeHealthy is the real readiness source, not
    manufactured AssignmentInfo receipt)
  - HealthyPathExecutor drives engine through Probe + Fence +
    PublishHealthy so Mode actually reaches ModeHealthy
  - cmd/blockvolume: --t1-readiness + --status-addr flags;
    volume.StatusServer exposes frontend.Projection over HTTP
  - memback negative offset: returns ErrInvalidOffset, no panic
  - Boundary guard: full AST parse + alias resolution

Round 3 (cross-replica supersede + real authority move in L2):
  - SupersedeProbe seam on AdapterProjectionView; Host.IsSuperseded
    compares lastOther (replicaId, epoch, ev) vs self-lineage →
    Healthy=false when another replica holds newer authority
  - L2 now drives a product-route authority move: r1 restarts
    with new data/ctrl addrs → master mints IntentRefreshEndpoint
    → EndpointVersion advances → old backend ErrStalePrimary →
    fresh Open captures new lineage
  - StatusServer restricted to loopback (bind + client check)

Round 4 (proof coverage + robustness):
  - Real Host.recordOtherLine → IsSuperseded → View integration
    test (no more stubProbe-only coverage for supersede claim)
  - L2 closure claim sharpened: PROVES IntentRefreshEndpoint
    stale reject; DOES NOT PROVE cross-replica primary change
    (deferred to T6/G8)
  - Reserve loopback port via :0 instead of hardcoded 7165
  - Boundary guard: forbid dot-import of core/adapter and
    core/authority (bare-literal bypass closed)

Tests (all green):
  core/frontend L0: 7 + negative-offset regression + 3 meta
  core/frontend L1: 1 (real adapter + AdapterProjectionView)
  core/frontend L2: 1 (product route + authority move + stale
    reject + new open, 17-21s)
  core/host/volume: 4 AdapterProjectionView + 3 supersede
    integration + 5 StatusServer loopback

Closure: INV-FRONTEND-001 / INV-FRONTEND-002 Unit+Component+
Integration; PCDD-STUFFING-001 Unit with dot-import guard.
Cross-replica primary-change facet explicitly remains
Unit/Component only (routed to G8/T6 for L2 promotion).
2026-04-21 15:53:14 -07:00
wzcheng99 55793d49bc T0 closure: blockmaster/blockvolume hosting + D1-D5 tests
Product binaries (cmd/blockmaster, cmd/blockvolume) and
core/host wiring for volume-scoped assignment delivery,
durable authority with Windows rename retry, and the T0
closure test set (D1 L2 subprocess, D2 G1 adversarial,
D3 concurrent write-reload regression, D4 hosting-smoke
scenario + Go-native replay, D5 --topology flag).

Diagnostic surfaces: ObservationStore.SupersededCount
(PCDD-DELAYED-HB-001 evidence, not authority input) and
SetNowForTest clock seam on Store/Host, guarded by grep
test ensuring the identifier stays out of production files.
2026-04-21 02:02:52 -07:00