mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-05 18:47:20 +01:00
71e2e082c0f610d0a40066c63cc92ce04a4ddfdb
74
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
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>
|
||
|
|
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> |
||
|
|
9ffc149293 |
T4c-pre-A POC walstore — wal_replay tier-1 mode validation (round 34)
Confirmatory POC for walstore substrate per memo §12 + §13.0a +
§5.1. Validates V2-faithful per-LSN tier-1 mode (`wal_replay`)
in contrast to smartwal's `state_convergence` mode.
Code (POC, NOT production):
core/storage/walstore_recovery_poc.go (~240 LOC)
New types:
- RecoveryEntry{LSN, LBA, Flags, Data} — sibling to smartwal's
type; same shape, different package; T4c-3 muscle port will
unify behind LogicalStorage.ScanLBAs
- ErrWALRecycled (sentinel; mirrors V2 walstore semantics)
New methods on *WALStore:
- ScanFrom(fromLSN, fn) error — walks WAL physical region
between logicalTail and logicalHead, decodes each record,
filters LSN >= fromLSN && < headLSN, emits in LSN-ascending
order. Per-LSN, NOT deduped. Returns ErrWALRecycled if
fromLSN <= checkpointLSN.
- WALCapacityBytes() — POC retention characterization
- CheckpointLSNForPOC() — sibling for retention boundary tests
core/storage/walstore_recovery_poc_test.go (~440 LOC)
8 POC tests, all pass:
#1 — TestPOC_Walstore_ScanFrom_BasicRange
#1 — TestPOC_Walstore_ScanFrom_FromHeadOrAbove_Empty (3 sub)
#1 KEY PIN —
TestPOC_Walstore_ScanFrom_PerLSNNotDeduped: 3 writes to
LBA=0 → 3 entries with markers 0xA1/0xA2/0xA3. Pins
V2-faithful per-LSN semantic and confirms
INV-REPL-RECOVERY-STREAM-LBA-DEDUP is NOT applicable to
walstore (smartwal-mode-scoped per memo §13.6 round-34).
#1+#4 — TestPOC_Walstore_ScanFrom_ErrWALRecycled: boundary
fires at fromLSN <= checkpointLSN
#2 — TestPOC_Walstore_AllBlocks_DeterministicOrdering
#3 — TestPOC_Walstore_ScanFrom_ConcurrentLiveWrite_Safe:
no deadlock, no torn reads; emitted Data contemporaneous
with emitted LSN (data-staleness from smartwal §3.2 does
NOT apply to walstore — append-only WAL slots are
immutable once written)
#4 — TestPOC_Walstore_RetentionBoundary_Characterized:
deterministic boundary at checkpointLSN
sanity — TestPOC_Walstore_Sanity_ExistingAPIsUnchanged
Findings (per POC report §3.b):
- V2-faithful per-LSN tier-1: walstore preserves entry data IN
the WAL (LBA + LSN + Data), so 3 writes to same LBA produce
3 emitted RecoveryEntry, each with the data that LSN actually
wrote. Contrast with smartwal which emits 1 entry with current
extent data.
- ErrWALRecycled boundary: dynamic, advances with flusher
activity. Contrast with smartwal's fixed walSlots window.
- Concurrent live-write: walstore's append-only WAL records are
immutable; concurrent live-write doesn't rewrite slots. Per-
LSN data preservation makes data-staleness a non-issue. POC
finds no torn reads, no deadlock, contemporaneous data
labeling.
- BUG-007 not exercised (Windows/dev-loop only); deferred to
T4c-5 L3 m01 integration matrix per memo §5.
POC report (sw-block/design/v3-phase-15-t4c-pre-poc-report.md)
extended:
- §1 executive summary expanded to 8-case 2-substrate matrix
- New §3.b walstore findings section
- §5 substrate-specific concerns: walstore concerns now ✅
addressed (ring-buffer recycling consistency verified)
- §6 acceptance: clean on both substrates
- §7 next steps: T4c-pre-B in flight; T4c mini-plan follows
- §8 sign + §9 change log entries for round-34 walstore POC
Verification: full 21-package repo suite green. POC code isolated
to walstore + smartwal POC files; no impact on production paths.
T4c-pre-A POC closed. T4c-pre-B engine command model upgrade
proceeds next.
|
||
|
|
9d894c4ecf |
T4c-pre-A POC: smartwal recovery scan capability validation
Per design memo §12 (`v3-phase-15-t4c-recovery-protocol-design.md`):
substrate-level POC validating that smartwal can support the four
operations the unified recovery protocol requires. Discovers + pins
a critical semantic question that gates T4c-1 wire coding.
Code (POC, NOT production — file names + godoc mark POC):
core/storage/smartwal/recovery_poc.go (~220 LOC)
New types:
- RecoveryEntry{LSN, LBA, Flags, Data}
- ErrWALRecycled (sentinel; mirrors V2 walstore semantics)
New methods on *Store:
- ScanFrom(fromLSN, fn) error — emits per-LBA last-writer-wins
within LSN range; returns ErrWALRecycled if fromLSN below
retention boundary; mid-scan recycle re-checked
- RingCapacity() uint64 — exposes slot count for retention
characterization tests
core/storage/smartwal/recovery_poc_test.go (~450 LOC)
8 POC tests, all pass:
#1 — TestPOC_ScanFrom_BasicRange (capability #1)
#1 — TestPOC_ScanFrom_FromHeadOrAbove_Empty (3 sub)
§3.1 finding pin —
TestPOC_ScanFrom_LastWriterWinsPerLBA: 3 writes to same
LBA in range emit 1 entry (not 3) — pins smartwal-specific
semantic that V2 wire-parity-strict cannot be delivered
#1+#4 — TestPOC_ScanFrom_ErrWALRecycled
#2 — TestPOC_AllBlocks_DeterministicOrdering
#3 — TestPOC_ScanFrom_ConcurrentLiveWrite_DataStaleness:
no deadlock, no torn reads; documents the data-staleness
semantic where emitted LSN labels reflect slot-record at
scan-time but emitted Data may belong to a newer LSN
(cross-lane bitmap reconciliation handles this)
#4 — TestPOC_RetentionBoundary_Characterized: 8/16/64
slot characterization; ErrWALRecycled fires precisely at
head-walSlots
sanity — TestPOC_Sanity_ExistingAPIsUnchanged
POC report at sw-block/design/v3-phase-15-t4c-pre-poc-report.md
documents:
§3.1 Critical finding — architect decision required:
smartwal's WAL stores metadata only; extent holds only the
latest data per LBA. Tier-1 recovery cannot deliver every-LSN-
entry-in-range (V2 strict-parity); CAN deliver last-writer-
wins per LBA in range (state-convergence-equivalent). Two
options surfaced; sw recommends Option A (state-convergence)
because: (a) replica state convergence identical, (b) bitmap
mask rule keyed on LBA so cross-lane reconciliation
unaffected, (c) keeps smartwal as sign-bearing substrate
without architectural change, (d) bandwidth-efficient.
§3.2 Concurrent live-write data staleness:
Within recovery-stream lane, emitted LSN may not match
emitted Data. Bitmap mask rule (memo §2.2) handles this
correctly at the replica because it's keyed on LBA. Recovery
handler at T4c-2 must NOT rely on per-entry LSN-vs-data
consistency.
§3.3 Retention characterization:
Deterministic — `walSlots` slots = `walSlots` LSNs of
retention. ErrWALRecycled fires precisely when
fromLSN < head - walSlots.
Walstore POC deferred per §4 of report — pending architect
decision on §3.1. If Option A: walstore POC is straightforward
mirror of smartwal scope (1 day). If Option B: walstore is
primary path and smartwal requires substrate work first.
Verification: full 21-package repo suite green. POC code is
isolated to smartwal package; no impact on production paths.
T4c-pre-A POC complete pending architect §3.1 decision. Standing
by for architect ruling, then walstore POC, then T4c-pre-B engine
command model upgrade, then T4c-1 wire.
|
||
|
|
bb390a9a97 |
T4b-6: L2 subprocess integration matrix — T4b batch close gate
Closes the T4b batch with end-to-end matrix coverage of all three
DurabilityMode semantics + a wire-shape scope-leak fence. Each
scenario drives the full StorageBackend.Sync → observer.Sync →
DurabilityCoordinator → peer.Barrier → real ReplicaListener path
on real TCP between in-process pairs.
Mirrors T4a-6 harness shape (matrix runner, primaryRig +
replicaRig pattern, LIFO cleanup discipline). Both backends
(smartwal + walstore) are gating in the L2 harness — round-22
honesty correction inherited.
Scenarios (4 × 2 backends = 8 matrix rows):
TestT4b6_SyncAll_TwoPeers_AllHealthy
sync_all happy path. 20 LBAs through StorageBackend.Write +
Observe + ship to both replicas; Sync delegates to observer
which runs local fsync + 2 peer barriers in parallel via
DurabilityCoordinator. Sync returns nil; both peers stay
Healthy; replica byte-exact via primary.store vs r1/r2.store
(forward-carry: T4a-6 BasicEndToEnd byte-exact invariant
continues to hold).
TestT4b6_SyncAll_OnePeer_FailsOnBarrierError
sync_all rejects ANY peer failure. 1 healthy + 1 unreachable
peer; Sync returns ErrDurabilityBarrierFailed. Dead peer is
Degraded (peer.Barrier translation,
INV-REPL-BARRIER-FAILURE-DEGRADES-PEER). Healthy peer's
state stays Healthy — its individual barrier succeeded; the
failure is mode-driven, not transport-driven.
TestT4b6_SyncQuorum_RF3_TolerantOfOneFailure
sync_quorum tolerates 1/2 peer failure when quorum is 2.
Primary(1) + healthy peer(1) = 2 durable >= 2 quorum → Sync
nil. Sanity sub-case: with BOTH peers dead, sync_quorum
returns ErrDurabilityQuorumLost (1/3 durable < 2/3 quorum).
Pins V2 dist_group_commit.go quorum arithmetic end-to-end
through the V3 wire.
TestT4b6_BestEffort_AllPeersFail_StillSucceeds
best_effort silences all-peers-failed. 2 unreachable peers;
Sync returns nil. Both peers Degraded via peer.Barrier
Invalidate. Primary's local fsync ran (walHead reflects the
writes). Pins V2's "best_effort returns nil even on full
replication failure" semantic.
TestT4b6_BarrierWire_FullLineageEcho_StillEnforced
Wire-shape scope-leak fence (architect round-22 pattern).
Asserts EncodeBarrierResp output is exactly 40 bytes (32B
lineage + 8B AchievedLSN). Asserts round-trip preserves
every lineage field byte-exact. Asserts 39B truncation is
rejected at decode (T4b-1 fail-closed contract). Catches
any future refactor that silently weakens to epoch-only
or short form, independent of whether the matrix scenarios
above also fail.
Forward-carry verification (matrix run + standalone):
- All T4a-6 tests (BasicEndToEnd_PrimaryWriteReachesReplicaByteExact
+ BestEffort_DisconnectThenReassign) continue to pass.
- T4a-4 adversarial pin
(TestReplicationVolume_OnLocalWrite_ConcurrentLSNs_OrderedAtReplica)
continues to pass — INV-REPL-LSN-ORDER-FANOUT-001 not
regressed by Sync code path.
- T4b-3 wrapper tests + T4b-4 coordinator tests + T4b-5 Sync
tests all green.
Verification: full 21-package repo suite green. core/replication
test time 0.6s including all 8 matrix rows. G-2 tri-line godoc on
test helpers (setReplicaSet, writePrimaryBlocks, reservedDeadAddr).
G-3 cumulative.
Sixth and final task in T4b batch. T4b mechanically closed: 6/6
tasks landed, all gates green, all invariants pinned. Awaiting QA
single-sign per §8C.2 for batch close.
|
||
|
|
44f87603fd |
T4b-5: ReplicationVolume.Sync + WriteObserver.Sync seam
Wires DurabilityCoordinator (T4b-4) into the per-volume Sync path.
Host-side FLUSH / SYNCHRONIZE_CACHE now drives the full local fsync
+ per-peer barrier closure in parallel with mode-dependent arithmetic.
Changes:
core/frontend/durable/storage_adapter.go
WriteObserver interface extended: Sync(ctx, targetLSN) joins the
existing Observe(ctx, lba, lsn, data) method. Contract documented
inline — observer.Sync OWNS the full sync job (both local
fsync and peer barriers) when installed; StorageBackend delegates
rather than calling storage.Sync locally.
StorageBackend.Sync branches: observer==nil preserves the
pre-T4b behavior (local storage.Sync only); observer!=nil reads
walHead from LogicalStorage.Boundaries() and calls observer.Sync
with that as targetLSN. The observer (ReplicationVolume) then
invokes DurabilityCoordinator.SyncLocalAndReplicas which runs
local + barriers in parallel inside its own goroutines.
core/replication/volume.go
ReplicationVolume gains:
- coord field set to NewDurabilityCoordinator at construction
- durabilityMode field, SetDurabilityMode setter +
DurabilityMode accessor. Default BestEffort (zero value).
Per mini-plan §5, T4b does not support per-Sync-call mode
override — mode is a per-volume setting.
- Sync(ctx, targetLSN) method — snapshots peers under v.mu,
builds a localSync closure around v.store.Sync, delegates
to coord.SyncLocalAndReplicas, returns error verbatim.
Lock scope: v.mu held across the FULL Sync call. Matches the
T4a-4 round-15 Condition A discipline — concurrent Sync +
OnLocalWrite calls are serialized on v.mu, preserving the V2
shipMu semantics extended from ship-only into ship+barrier.
Accepted correctness-first trade-off: a slow peer barrier stalls
other writers on the same volume; async-queue optimization
(Option Z) is deferred post-T4.
Tests (2 required per mini-plan §2 T4b-5):
- TestReplicationVolume_Sync_BestEffort_E2E — full end-to-end
smoke: StorageBackend.Write 10 LBAs → Observe → ship → replica
applies. StorageBackend.Sync → observer.Sync →
DurabilityCoordinator → local fsync + peer barrier in parallel.
Replica's R-boundary (durable frontier) must reach primary's
H (walHead) after Sync returns. Peer stays Healthy throughout.
- TestReplicationVolume_Sync_PreservesLSNOrderUnderConcurrency —
forward-carry fence for INV-REPL-LSN-ORDER-FANOUT-001 under
the new Sync code path. 40 goroutines, caller-side serialized
LSN allocation + OnLocalWrite, periodic Sync calls interleaved
every 4th iteration. LBA ordering is inverted from LSN order so
any reorder is byte-detectable. All 40 LBAs must settle to the
correct LSN marker at the replica.
Forward-carry verification: T4a-4's
TestReplicationVolume_OnLocalWrite_ConcurrentLSNs_OrderedAtReplica
continues to pass — the existing ordering invariant is not regressed
by the new Sync code path that shares v.mu.
Verification: full 21-package repo suite green including the
extended WriteObserver interface not breaking core/frontend/durable
tests. G-2 tri-line godoc on SetDurabilityMode, DurabilityMode
accessor, Sync method, extended WriteObserver.Sync contract. G-3
cumulative.
Fifth task in T4b batch. Next: T4b-6 L2 subprocess integration
matrix closes the batch.
|
||
|
|
e79ec9e952 |
T4b-4: DurabilityCoordinator (muscle port, G-1 signed)
Ports V2 MakeDistributedSync (weed/storage/blockvol/dist_group_commit.go,
~45 LOC muscle) into V3 DurabilityCoordinator at core/replication/
durability.go. Gate G-1 pre-signed by QA at round 24 per revised
artifact sw-block/design/v3-phase-15-t4b-4-g1-v2-read.md.
Core surface:
- DurabilityMode enum (BestEffort / SyncQuorum / SyncAll) with
String() + zero-safe BestEffort default, mirroring V2
- DurabilityResult struct with DurableNodes, Quorum, FailedPeers,
Err fields for caller diagnostics
- ErrDurabilityBarrierFailed / ErrDurabilityQuorumLost sentinels
mirroring V2 blockerr.ErrDurability*
- NewDurabilityCoordinator() stateless constructor
- SyncLocalAndReplicas(ctx, mode, targetLSN, localSync, peers) —
parallel fan-out + mode arithmetic
- EvaluateBarrierAcks(mode, rf, localSyncSucceeded, perPeerErrors)
— pure arithmetic helper exposed for unit testing
Hidden invariants pinned (from G-1 §4.2):
#7 Local-fsync short-circuits mode arithmetic. If localSync
errors, DurableNodes=0, mode arithmetic skipped. Pinned by
TestDurabilityCoordinator_LocalSyncFails_AllModesError across
all three modes.
#8 Peer-state mutation on barrier failure. DurabilityCoordinator
does NOT call peer.Invalidate — that translation lives inside
peer.Barrier (T4b-3 wrapper) per §0-B locality. Coordinator
sees only the error vector; failed peers are logged with
peer ID + lsn + err at the coordinator layer for operator
visibility. Pinned by TestDurabilityCoordinator_BestEffort_
Silences_Failures + TestDurabilityCoordinator_StaleLineageAck_
NotCounted (both assert peer.State() == ReplicaDegraded after
coordinator returns).
#9 Zero-peers fast-path. len(peers)==0 skips parallel machinery
entirely — localSync runs in the caller's goroutine. Pinned
by TestDurabilityCoordinator_ZeroPeers_StandaloneFastPath
across all three modes via runtime.Stack() goroutine-ID
check (sameGoroutine must be true).
#10 Target LSN derivation responsibility shift. Caller owns
targetLSN; coordinator passes it through to peer.Barrier.
Documented in SyncLocalAndReplicas godoc.
#11 Flat wg.Add(1 + len(peers)) layout (not V2's wg.Add(2) +
nested BarrierAll). Semantically equivalent. Pinned by
TestDurabilityCoordinator_ParallelExecution (elapsed ~100ms
for localDelay=100ms + 2 peers; sequential would be 100ms+).
Uniform round-21 rule: peer.Barrier owns lineage validation at the
executor seam; stale-lineage acks surface as ErrBarrierLineageMismatch
→ coordinator sees it as a failed peer → NOT counted toward durability.
Pinned by TestDurabilityCoordinator_StaleLineageAck_NotCounted with
a custom replica sending valid-decode responses carrying the wrong
lineage.
Metrics (V2 concern #6) DEFERRED to T4-end observability pass per
G-1 §7 decision. core/replication has no metrics surface yet;
adding one is scope creep.
Tests (9 per mini-plan §2 T4b-4 + 2 sanity):
1. _Quorum_RF3_AllHealthy — RF=3, 2 peers healthy → 3/3 durable
2. _Quorum_RF3_OneReplicaFailed — 2/3 durable, quorum met
(sync_quorum), sync_all fails
3. _Quorum_RF3_BothReplicasFailed — 1/3 durable,
ErrDurabilityQuorumLost
4. _SyncAll_AnyFailure_Fails — no silent swallow
5. _BestEffort_Silences_Failures — peers Degraded, Err=nil
6. _StaleLineageAck_NotCounted — H5 LOCK pin via
wrong-lineage replica
7. _LocalSyncFails_AllModesError — V2 line 46-48 short-circuit
across all modes
8. _ParallelExecution — elapsed ≤ 150ms for 100ms localSync + 2
peers
9. _ZeroPeers_StandaloneFastPath — rf=1, same-goroutine,
INV-REPL-ZERO-PEER-NO-SPAWN
Plus sanity: _Constructor and DurabilityMode_String.
Verification: full 21-package repo suite green. G-2 tri-line godoc
on every public symbol (DurabilityMode + stringer, DurabilityResult,
DurabilityCoordinator, NewDurabilityCoordinator, SyncLocalAndReplicas,
EvaluateBarrierAcks, error sentinels). G-3 cumulative.
Fourth task in T4b batch. Next: T4b-5 ReplicationVolume.Sync wires
DurabilityCoordinator into the volume Sync path + extends
WriteObserver interface.
|
||
|
|
1c6dc56107 |
T4b-3: ReplicaPeer.Barrier + Fence wrappers (peer-level seam)
New leaf task introduced by QA round-23 §0-B review. T4b-3 originally
planned for ReplicaPeer.Fence-only; QA's peer-state-mutation locality
check surfaced that DurabilityCoordinator must consume peer.Barrier
(not peer.executor.Barrier) so the error → Invalidate translation
lives at the per-peer execution layer — matching V2's WALShipper-
internal markDegraded locality. T4b-3 now ships both Barrier + Fence
wrappers as a leaf before the T4b-4 DurabilityCoordinator muscle port.
Invariant pinned: INV-REPL-BARRIER-FAILURE-DEGRADES-PEER at the V3
per-peer layer, mirroring T4a-3's Ship → Invalidate translation.
Changes:
core/transport/executor.go
Extract FenceSync(replicaID, lineage) error — synchronous fence
exchange returning a descriptive error on any dial / send /
recv / lineage-mismatch failure. Refactored existing async
doFence to wrap FenceSync + adapt the error to the callback-
based FenceResult. Behavior unchanged for existing async
callers (engine recovery path); T4b-3 peer wrapper gets a
clean sync surface.
core/replication/peer.go
New ReplicaPeer.Barrier(ctx, targetLSN):
- Passes peer.lineage UNCHANGED to executor.Barrier — does
NOT override lineage.TargetLSN with the caller's targetLSN.
Replica's acceptMutationLineage rejects same-authority
messages that change TargetLSN, so override would self-
reject. Caller's targetLSN is coordinator-layer-only
(compared against ack.AchievedLSN for mode arithmetic).
- MUST NOT gate on state == Degraded per V2 "always attempt
BarrierAll" invariant (architect §4.3 note in G-1 doc).
Only post-Close gate applies.
- On transport error: p.Invalidate(reason) + state=Degraded
(INV-REPL-BARRIER-FAILURE-DEGRADES-PEER pin).
New ReplicaPeer.Fence(ctx, lineage):
- Takes caller-supplied lineage (not peer-owned) because
fence semantic is "confirm this specific authority tuple"
— coordinator or recovery path chooses which lineage.
- Delegates to executor.FenceSync.
- Same error → Invalidate translation.
Tests (5 required per QA spec):
- TestReplicaPeer_Barrier_Happy — round-trip against real
ReplicaListener; ack.Lineage == peer.lineage byte-exact;
state remains Healthy
- TestReplicaPeer_Barrier_ErrorPropagates_MarksDegraded —
unreachable replica; Barrier returns error; peer transitions
Healthy → Degraded. INV-REPL-BARRIER-FAILURE-DEGRADES-PEER
pin at peer layer.
- TestReplicaPeer_Fence_Happy — fence exchange at peer.lineage
against real replica; state stays Healthy
- TestReplicaPeer_Barrier_AfterClose_Errors — post-Close call
returns 'closed' error; no panic
- TestReplicaPeer_Fence_AfterClose_Errors — post-Close call
returns 'closed' error; no panic
Verification: full 21-package repo suite green. G-2 tri-line godoc
on Barrier, Fence (Called by / Owns / Borrows) + FenceSync on
executor. G-3 cumulative. Existing T4b-2 Fence tests pass after the
doFence → FenceSync refactor (behavior preserved).
Third task in T4b batch. Next: T4b-4 DurabilityCoordinator (muscle
port; G-1 pre-signed by QA in revised artifact at sw-block/design/
v3-phase-15-t4b-4-g1-v2-read.md) against the peer.Barrier surface.
|
||
|
|
4b16a2e759 |
T4b-2: BlockExecutor.Barrier + doFence ack-validation upgrade
Architect round-22 bundle: new BlockExecutor.Barrier public method +
upgrade of existing executor.doFence to respect round-21 uniform
rule (INV-REPL-LINEAGE-BORNE-ON-BARRIER-ACK). Two coupled changes,
same file, same executor-level ownership, one commit — shipping
Barrier with validation while leaving doFence silent-accept would
violate the uniform rule at the first ack-consuming surface.
Changes:
core/transport/barrier.go
New BarrierAck type: {Lineage, AchievedLSN, Success, Reason} —
validated per-peer barrier outcome surfaced to
DurabilityCoordinator (T4b-3).
New ErrBarrierLineageMismatch sentinel: returned by Barrier
when the response lineage does not match the request. Callers
treat it as a failed barrier for quorum arithmetic.
core/transport/executor.go (doFence upgrade)
After recvBarrierResp succeeds, validate that resp.Lineage
matches the lineage we sent. Mismatch → FenceResult with
Success=false + FailReason containing expected=<lineage>
actual=<lineage> tuple. Short/zeroed/malformed decode failures
already surface as recvBarrierResp errors (T4b-1 decode layer);
they now cleanly propagate to OnFenceComplete instead of
silent-accept ("_ = resp" removed).
core/transport/executor.go (new Barrier method)
func (e *BlockExecutor) Barrier(replicaID, lineage, targetLSN)
(BarrierAck, error)
Implementation mirrors Ship (architect round-11 Option B
composite):
1. Session lookup by lineage.SessionID
2. Epoch-== fence (silent drop on stale epoch via error return)
3. Lazy-dial if session.conn == nil, with "first-winner keeps"
race resolution under e.mu
4. sendBarrierReq + recvBarrierResp (existing helpers; both
set conn deadlines, so timeout is bounded by
recoveryConnTimeout=5s)
5. Full-lineage validation — resp.Lineage != lineage returns
ErrBarrierLineageMismatch with diagnostic log format
matching architect round-21 text (peer ID + expected +
actual tuple)
Tests (5 required per mini-plan §2 T4b-2):
- TestExecutor_Barrier_Happy — real ReplicaListener round-trip;
lineage echo byte-exact; Success=true
- TestExecutor_Barrier_TimeoutFires — replica accepts but never
responds; Barrier's recv deadline fires in ~5s (elapsed
between 4s and 15s, must wedge for most of the deadline to
count as deadline-driven rather than fast-error)
- TestExecutor_Barrier_LineageMismatch_Rejected — custom replica
sends a valid-decode BarrierResponse with different lineage;
Barrier returns ErrBarrierLineageMismatch
- TestExecutor_Fence_LineageMismatch_MarksFailure — the round-22
pin; custom replica sends wrong-lineage ack; doFence propagates
Success=false through OnFenceComplete with FailReason carrying
expected= + actual= tuples. This catches "first existing ack
consumer silently accepts" regression class.
- TestExecutor_Fence_ShortOrZeroedLineage_MarksFailure — two
sub-cases (8-byte short payload, 40-byte all-zero lineage);
both propagate through OnFenceComplete as Success=false (the
T4b-1 decode-layer error is faithfully relayed to the callback).
Preserve:
- sendBarrierReq / recvBarrierResp helper signatures unchanged
- Existing catch-up (catchup_sender.go:102-108) and rebuild
(rebuild_sender.go:103) paths continue to decode successfully
with the extended wire; they ignore the lineage field for T4b
scope — their lineage-validation lands at T4c (catch-up) and
T5 (rebuild) respectively
- adapter.OnFenceComplete callback shape unchanged (FenceResult
gains fuller FailReason content but fields untouched)
Verification: full 21-package repo suite green. G-2 tri-line godoc
on Barrier + BarrierAck + ErrBarrierLineageMismatch. G-3 cumulative.
Timeout test elapsed = 5.00s exactly, confirming deadline is the
unblocking mechanism.
Second task in T4b batch. Next: T4b-3 DurabilityCoordinator (muscle
path; G-1 pre-code V2 diff-footprint required before coding).
|
||
|
|
77cf6e2836 |
T4b-1: BarrierResponse full-lineage echo (architect round-21 wire)
Extends BarrierResponse wire from [8B achievedLSN] to
[32B lineage][8B achievedLSN] per architect round-21 decision text
(INV-REPL-LINEAGE-BORNE-ON-BARRIER-ACK). Primary-side consumers can
now fail-closed validate barrier acks against the session they are
awaiting without cached primary-side assumptions — the authority
tuple travels with every ack.
Wire contract (architect verbatim):
- lineage slab [0..32] in strict field order
(SessionID, Epoch, EndpointVersion, TargetLSN)
- achievedLSN at [32..40]
- total payload exactly 40B; MsgBarrierResp type byte
unchanged; envelope preamble unchanged (T4a-1 12B SWRP)
DecodeBarrierResp is strict + fail-closed:
- payloads < 40B → error
- zero-valued SessionID / Epoch / EndpointVersion / TargetLSN
→ error (catches partially-initialized-struct drift)
- field-order drift caught indirectly via the zero-lineage
rule whenever a reordering leaves any slot at zero
Changes:
core/transport/barrier.go
BarrierResponse gains Lineage RecoveryLineage field.
barrierRespSize 8 → 40. Encode/decode updated; decode emits
descriptive errors.
core/transport/replica.go
Two MsgBarrierResp sender sites (MsgBarrierReq handler +
MsgRebuildDone handler) now echo the request's full lineage
via EncodeBarrierResp instead of raw uint64 big-endian. Drops
the encoding/binary import (no longer used).
core/transport/executor.go
Fence lineage.TargetLSN changed from 0 to new
fenceSentinelTargetLSN const (=1, matching liveShipTargetLSN).
Post-T4b-1 any zero-valued lineage field is rejected at
decode; the pre-existing "TargetLSN=0 signals fence" local
convention had to go. Fence TargetLSN is not semantically
meaningful (no TargetLSN-sensitive code on the fence path
reads it); the non-zero sentinel is purely wire-compatibility.
Tests (4 required per mini-plan §2 T4b-1):
- TestBarrierResp_FullLineageEcho_RoundTrip — 3 cases
(typical, largest_valid, mins_all_one). Every field byte-
exact round-trip; length exactly 40.
- TestBarrierResp_ShortPayload_Rejected — loops 0..39, every
truncation rejected with "short barrier response" error.
- TestBarrierResp_ZeroedLineage_Rejected — 5 cases covering
all-zero plus each individual zero field. All reject with
"zero-valued lineage" error.
- TestBarrierResp_MalformedFieldOrder_Rejected — field-order
byte-level fence: crafts payload with Epoch slot zeroed
(simulates reordering bug leaving a slot uninitialized) →
rejected. Plus canonical encode/decode byte-position
assertions so any future encode/decode field-order drift
trips explicitly.
Existing barrier_test.go tests
(TestBarrierResponse_Roundtrip*, _DecodeShort*) removed —
their intent is subsumed by the four new pins which exercise
the stricter T4b-1 contract.
Verification: full 21-package repo suite green. Non-trivial
regression caught during self-test: executor.Fence previously
set TargetLSN=0 which the new strict decode would reject —
calibration + sparrow tests caught it, fix (fenceSentinelTargetLSN)
landed in same commit. Catch-up (catchup_sender.go) and rebuild
(rebuild_sender.go) paths continue to decode successfully via
recvBarrierResp; they ignore the lineage field for T4b scope
per mini-plan §2 T4b-2 preserve-clause (those paths' lineage
validation lands at T4c/T5 respectively).
First task in T4b batch.
|
||
|
|
d37451ea1f |
T4a-6 doc cleanup: retract overclaim + fix matrix wording in header
QA round-22 noted the l2_integration_test.go file header still
claimed the L2 test proves "all T4a landed commits compose
correctly" and that walstore was "non-gating" — both stale after
the
|
||
|
|
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
|
||
|
|
420a5a1c4a |
T4a-6: L2 subprocess integration test — T4a batch close gate
Ships the end-to-end integration test that proves all five T4a
production commits (T4a-1..T4a-5) compose correctly through the
full frontend→storage→replication→transport→replica wire. This
is the T4a batch close gate per mini-plan §4.
In-scope addition flagged by QA round-20 review and confirmed by
sw (not a discovery-bridge trigger — mini-plan always implied this
wire): StorageBackend.Write did NOT invoke
ReplicationVolume.OnLocalWrite. The hook is added here via a
narrow WriteObserver interface seam so core/frontend/durable does
not import core/replication directly.
Changes:
core/frontend/durable/storage_adapter.go
New WriteObserver interface with Observe(ctx, lba, lsn, data)
method. Named Observe (not OnLocalWrite) to avoid a method-
name collision on ReplicationVolume which already has a
differently-typed OnLocalWrite(ctx, LocalWrite). New
SetWriteObserver(obs) installation seam; called only at setup
(not hot-swappable). writeBytes now takes ctx through and
invokes obs.Observe after each successful LogicalStorage.Write,
best-effort (error logged, does NOT fail the Write — matches
V2 fire-and-forget ShipAll).
Ordering: LSN-order fan-out is preserved because the observer
(ReplicationVolume) serializes its own fan-out under v.mu
(Option X, architect-signed at T4a-4 round-15).
core/replication/volume.go
New Observe(ctx, lba, lsn, data) method that wraps into
LocalWrite and delegates to OnLocalWrite. This lets
*ReplicationVolume satisfy durable.WriteObserver without
either package importing the other's public struct type.
core/replication/l2_integration_test.go (NEW, ~450 LOC)
Internal-package test (access to ReplicationVolume.peers +
ReplicaPeer internals needed for transport-kill simulation).
Matrix harness:
- smartwal_gating — sign-bearing row; t.Fatal on failure
- walstore_nongating — reported row; failures logged with
non-gating note per BUG-007 / T3 matrix discipline
Scenarios:
1. BasicEndToEnd_PrimaryWriteReachesReplicaByteExact —
100 LBAs written through StorageBackend.Write,
verified byte-exact on replica's LogicalStorage. Peer
stays Healthy throughout. Both matrix rows pass.
2. BestEffort_DisconnectThenReassign (QA-requested G5
pass-gate shape) — 30 LBAs shipped Healthy; transport
kill via peer.executor.InvalidateSession +
peer.Invalidate (simulates mid-stream conn severed);
30 more LBAs written best-effort (primary persists
locally, peer Degraded, OnLocalWrite returns nil);
fresh replica spun up on new addr; fake-master
UpdateReplicaSet with gen=2 rebuilds peer (INV-REPL-
PEER-REBUILD-ON-AUTHORITY-CHANGE); 10 LBAs shipped
against fresh replica byte-exact.
Pass-gate fence: asserts the second-batch LBAs do
NOT appear on the fresh replica — catch-up is T4c
territory. Catches scope leak if a future refactor
quietly pulls catch-up into T4a.
Cleanup discipline (learned from T4a-4 test hang):
- replica cleanups registered BEFORE primary so LIFO
ordering closes primary's peer sessions first (no
listener.Stop() wedged on open client conns).
- DisconnectThenReassign creates a second replica after
primary, so it explicitly calls primary.repVol.Close()
at scenario end to unblock the non-LIFO cleanup chain.
Verification: full 20-package repo suite green (all pre-existing
tests pass after WriteObserver addition — backward compat
preserved via optional observer pointer). T4a-6 matrix: 4 test
rows all pass (2 scenarios × 2 backends). No -race on Windows
(CGO_ENABLED=1 requirement documented in MEMORY.md).
T4a batch close now mechanically satisfied; awaiting QA sign +
T-end three-sign per §8C.2 cadence.
|
||
|
|
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.
|
||
|
|
3597bc40ca |
T4a-4: ReplicationVolume MVP (Option X LSN-order fan-out)
Introduces ReplicationVolume — the per-volume fan-out owner that
tracks the authoritative replica set and serializes Ship fan-out so
the V2 BlockVol.shipMu LSN-order invariant survives the V3 layer
split.
Architect-approved Option X (G-1 pre-code review,
v3-phase-15-t4a-4-g1-v2-read.md): v.mu.Lock() held across the
entire per-peer fan-out loop (Condition A), not just map snapshot
or "prepare then unlock then ship." The mutex is plain sync.Mutex
(no reader-only API worth preserving RWMutex for).
Contract wording (architect-revised, explicit):
ReplicationVolume.OnLocalWrite serializes fan-out in LSN order
for a given volume. Caller order is NOT trusted as the
correctness mechanism.
System invariant: INV-REPL-LSN-ORDER-FANOUT-001. V2 BlockVol.shipMu
atomically composed "allocate LSN + append WAL + Ship" under one
mutex. V3 splits the three concerns across engine / LogicalStorage /
ReplicationVolume; the LSN-order property is preserved end-to-end
when (a) Backend.Write invokes LogicalStorage.Write + OnLocalWrite
under the caller's own atomicity (natural shape — same goroutine)
and (b) OnLocalWrite's mutex serializes fan-out. Test
TestReplicationVolume_OnLocalWrite_ConcurrentLSNs_OrderedAtReplica
is the adversarial pin: N concurrent callers, caller-side lock
mimics Backend.Write, LBAs interleaved with LSN ordering so any
reorder is byte-detectable at the replica.
Accepted T4a trade-off (mini-plan change log): correctness-first
serialized design. Per-volume fan-out holds v.mu during each
peer's ShipEntry, so a slow peer (lazy dial, 3s write deadline,
degraded state) stalls the writer path. Async queue (Option Z) is
deferred optimization, not forgotten design debt — revisit only
after INV-REPL-LSN-ORDER-FANOUT-001 is proven in production.
Surface (~200 LOC production + 430 LOC tests):
- LocalWrite: {LBA, Data, LSN} — the layer-cross carrier
- ReplicationVolume: peers map + borrowed store + serialization mu
- NewReplicationVolume(volumeID, store): borrow store, never close
- UpdateReplicaSet(targets): add/remove/recreate-on-lineage-bump
under v.mu. Lineage bump = tear-down + recreate (T4a MVP; T4c
may add in-place lineage update)
- OnLocalWrite(ctx, w): LSN-order-serialized fan-out; per-peer
error is best-effort (logged + peer already marked Degraded by
ReplicaPeer.ShipEntry's forward-carry CARRY-1); does NOT fail
the OnLocalWrite call
- Close(): idempotent; releases all peers' sessions; does NOT
close the borrowed store (BUG-005 discipline)
- PeerCount() / newExec field: test seam for executor observation
BlockExecutor gains one test-grade accessor:
- HasSession(id): diagnostic for Opt-3 executor-teardown fence.
Used by TestReplicationVolume_UpdateReplicaSet_RemovePeer_
ExecutorTornDown to assert session removal after peer.Close.
Tri-line godoc contract; not intended for production flow.
Tests (8, all green):
1. UpdateReplicaSet_AddPeer — empty → 1 peer
2. UpdateReplicaSet_RemovePeer_ExecutorTornDown — Opt-3 three-
assertion fence (Close-called, session-removed, re-add-works-
and-ships-byte-exact)
3. UpdateReplicaSet_LineageBump_RecreatesPeer — same ReplicaID
new Epoch → new sessionID, new lineage
4. OnLocalWrite_SinglePeer_BestEffort — 20 LBAs byte-exact,
peer stays Healthy
5. OnLocalWrite_PeerErrorDoesNotFailCaller — dead-addr peer,
OnLocalWrite returns nil, peer Degraded
6. OnLocalWrite_ConcurrentLSNs_OrderedAtReplica — INV-REPL-LSN-
ORDER-FANOUT-001 adversarial pin (40 concurrent goroutines,
LBA/LSN interleaved, replica state byte-detectable)
7. Constructor_DoesNotOwnStore — BUG-005 regression fence; store
usable post-ReplicationVolume.Close
8. OnLocalWrite_Closed_Errors — post-Close call returns error,
no panic
Full core/transport + core/replication + core/adapter suites green.
G-2 three-line godoc contracts on every public symbol (New, Update,
OnLocalWrite, Close, PeerCount) + HasSession on executor. G-3
preserved.
|
||
|
|
debeb55f28 |
T4a-3: ReplicaPeer (leaf) — per-replica runtime handle
Introduces core/replication/ package and ReplicaPeer — the per-remote-
replica runtime handle that bridges ReplicationVolume fan-out (T4a-4)
to the transport layer (T4a-2). T4a-3 is the Opt-4 leaf: ships first,
then ReplicationVolume consumes it.
Surface (~220 LOC production + 230 LOC tests):
- ReplicaTarget: authoritative addressing + lineage from master
assignment (Epoch, EndpointVersion, DataAddr, ControlAddr).
- ReplicaState: Unknown / Healthy / Degraded. T4a scope only;
CatchingUp / Rebuilding / NeedsRebuild arrive at T4c with the
recovery pipeline.
- NewReplicaPeer: registers a live-ship session in the executor
using a fresh peer-local SessionID + target.{Epoch,
EndpointVersion} + constant liveShipTargetLSN = 1. Steady-state
live-ship session; recovery-bound sessions (with engine-frozen
TargetLSNs) arrive at T4c.
- ShipEntry: state-gated fan-out leaf. Healthy → executor.Ship;
Degraded / closed → reject at peer without dialing. On Ship
error: mark Degraded + log reason (forward-carry CARRY-1 from
T4a-2). Caller-supplied lineage is informational for T4a (peer
owns its session); T4b/T4c may tighten when recovery sessions
thread through.
- Invalidate: explicit Healthy → Degraded mutation for authority-
driven peer-down (no-op on closed peer).
- Close: idempotent; invalidates the peer's executor session via
InvalidateSession. Does NOT close the executor — caller owns
executor lifecycle (BUG-005 discipline).
BlockExecutor gets one new public method:
- RegisterLiveShipSession(lineage): thin wrapper around internal
registerSession, needed because ReplicaPeer in core/replication
needs to register its live-ship session from outside
core/transport. Tri-line godoc contract attached.
Gate G-2: every public symbol in both files carries a Called by /
Owns / Borrows tri-line contract. PR-rejectable if any symbol lacks
the three-line contract.
Forward-carry CARRY-1 closed: ShipEntry → Invalidate + Degraded on
transport error. Pin test TestReplicaPeer_ShipEntry_ConnFailure_
MarksDegraded asserts (a) first Ship returns dial/write error, (b)
state transitions Healthy → Degraded, (c) subsequent ShipEntry is
rejected at peer without touching the wire. This closes catalogue
§3.2.1 C4 from PARTIAL to DONE.
Tests (6, all green):
- TestReplicaPeer_ShipEntry_Happy — byte-exact arrival, state
stays Healthy.
- TestReplicaPeer_ShipEntry_ConnFailure_MarksDegraded — CARRY-1
pin.
- TestReplicaPeer_Invalidate_MovesToDegraded — authority-driven
path.
- TestReplicaPeer_Close_Idempotent — double-Close is safe;
post-Close ShipEntry errors with "closed".
- TestReplicaPeer_NewReplicaPeer_RejectsNilExecutor.
- TestReplicaPeer_NewReplicaPeer_RejectsZeroAuthority — fails fast
at construction rather than at first ship when lineage would be
rejected by replica's acceptMutationLineage.
Per T4a-3 context note: tests drive against a real
*transport.BlockExecutor + real *transport.ReplicaListener, not
against a ReplicationVolume caller stub (Opt-4 leaf ordering).
Full core/transport + core/replication + core/adapter suites green.
G-3 preserved.
|
||
|
|
dbe0f57b9c |
T4a-2 follow-up: pin test for 3s write deadline invariant
Adds TestExecutor_Ship_WriteDeadline_Fires — explicit regression fence
for INV-REPL-SHIP-TRANSPORT-MUSCLE-001 component (3). Requested by
QA at T4a-2 validation: three of four composite properties (lazy dial,
silent drop, no-hard-stop) had explicit pin tests; the 3s deadline
had only implicit coverage. Without this pin, a future refactor could
silently drop SetWriteDeadline and the only observable signal would
be primary-write wedge on a slow replica in m01 / production
(~120s TCP retransmission timeout instead of ~3s).
Implementation: net.Pipe() — synchronous in-memory connected pair
with zero internal buffering and SetWriteDeadline support. Bypasses
kernel TCP buffers, which on Windows/Linux loopback can absorb 16+
MiB before blocking and make TCP-based timing tests fundamentally
unreliable. Earlier iterations with 8 MiB TCP payloads + SO_SNDBUF=2K
completed in 2-3 ms on Windows (auto-tuning absorbed everything).
The test asserts:
1. Ship returns an error (not nil)
2. Elapsed >= 2.5s (proof: the write actually wedged for most of
the 3s deadline — if it returned faster, it wasn't the deadline
that unblocked it)
3. Elapsed <= 10s (proof: no hang on TCP retransmit path)
4. Error chain contains Timeout() == true OR "write failed"
Passes in 3.00s exactly on Windows loopback — the deadline IS the
unblocking mechanism.
Required test-list alignment with mini-plan line 390 now complete
(LazyDial_HappyPath ≡ LazyDial_OnRegisteredSessionWithoutConn;
LazyDial_DialFailure_ReturnsError ✓; StaleEpoch_SilentDrop ✓;
WriteDeadline_Fires ✓).
Full core/transport suite: 8 Ship tests + all pre-existing transport
tests green. G-3 preserved.
|
||
|
|
f1fb148989 |
T4a-2 fix: restore lazy dial in Ship (architect-revised Option B)
Follow-up to
|
||
|
|
64758502b8 |
T4a-2: BlockExecutor.Ship — live per-write fan-out send
Adds the steady-state Ship method to BlockExecutor. Sends one WAL entry to a named replica over the session's attached data conn. Fire-and-forget: no per-entry ack at this layer; durability closure is T4b concern. Port discipline (see v3-phase-15-t4a-2-g1-v2-read.md for full G-1 V2 read; 98 LOC V2 → ~30 LOC V3, 31% ratio flag explicitly justified by structural decomposition, not invariant loss). Invariants preserved verbatim from V2 WALShipper.Ship: - L1 §2.1 invariant #2 (epoch-== silent drop, wal_shipper.go:217): stale-epoch entries return nil without touching the wire. Epoch source shifts from epochFn() callback to lineage.Epoch (frame- borne authority, H5-LOCK compliant); semantic identical. - 3s write deadline (wal_shipper.go:240): byte-identical bound on TCP write so a dead replica can't wedge callers on the ~120s TCP retransmission timeout. Ownership shifts (per G-1 §6 QA-approved decisions): - §6.1 no lazy dial in Ship — sessions must be pre-registered via registerSession + attachConn (same lifecycle used by StartCatchUp/StartRebuild). Forward-carry conditions on T4a-3 (ReplicaPeer.ShipEntry marks Degraded on err) and T4a-6 (L2 mid-stream-kill recovery test) prove V3's "degrade+catch-up" is equivalent to V2's transparent-reconnect property. - §6.2 markDegraded moved from executor to caller — Ship returns error; ReplicaPeer.Invalidate (T4a-3) does the state mutation. BlockExecutor does not own ReplicaState in V3. Tests (5): - TestExecutor_Ship_SingleEntry (happy) - TestExecutor_Ship_MultipleEntriesOrdered (LSN/LBA preservation) - TestExecutor_Ship_ConnFailure (error return on write fail) - TestExecutor_Ship_NoSession (error on unknown sessionID) - TestExecutor_Ship_StaleEpoch_SilentDrop (L1 §2.1 inv #2 regression: TCP-proxy-counted 0 bytes on wire with stale-epoch Ship, fresh- epoch Ship on same session still arrives) G-2 three-line godoc contract (Called by / Owns / Borrows) inscribed on Ship per §7.1 Gate G-2. Full core/transport + core/adapter suite remains green. Gate G-1 approved by QA with forward-carry conditions recorded on T4a-3 and T4a-6 task entries. |
||
|
|
2b54fef3f7 |
T4a-1: bump transport envelope to 12B preamble
V3 clean-break replication envelope now carries magic + version + flags/reserved in every frame. Replicas refuse foreign traffic at the first byte; unknown protocol versions are rejected explicitly. Wire layout: [4B magic "SWRP"][1B version=1][1B type][1B flags=0][1B reserved=0] [4B length][payload] All existing message encode/decode bodies are unchanged — only the preamble extends. MsgShipEntry / MsgProbeResp / MsgRebuildBlock / MsgBarrierResp frames all ride the new envelope transparently. Tests: EnvelopeRoundTrip (every message type), MagicRejected_WrongMagic, VersionRejected_UnknownVersion. Existing core/transport/*_test.go continues to pass unchanged (verified). Part of Phase 15 T4a per v3-phase-15-t4a-mini-plan.md §2 T4a-1. Gate G-3 (pre-existing transport tests stay green) satisfied. |
||
|
|
7ee616f94a |
T3-DEF-6 + Matrix F cleanup — cleanup addendum test + ENOSPC robustness
T3-DEF-6 (NVMe session cleanup contract): Add core/frontend/nvme/t3_qa_session_cleanup_addendum_test.go with TestT3_NVMe_Session_CleanupOnClose_NoLeaksAcrossCycles (20 cycles, goroutine leak guard) and TestT3_NVMe_Session_CleanupOnClose_CNTLIDAllocator (monotonic CNTLID across 8 cycles + one post-cycles reconnect). Pins new catalogue row C5-NVME-SESSION-STATE-CLEANUP-ON-CLOSE as smoke + leak-guard (not full state-release introspection; target-registry introspection deferred). Matrix F ENOSPC cleanup robustness (iterate-m01-nvme.sh): SSH cleanup phase was non-zero-exiting when blockvolume crashed on ENOSPC (dead NVMe target hangs sudo nvme disconnect). Switch cleanup block to tolerate all benign non-zero exits, remove set -e, and use pattern-based success detection (grep 'ENOSPC triggered gracefully' in server-side output) as the authoritative Matrix F pass signal. Ownership: QA (L1 addendum + QA-owned script) Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> |
||
|
|
e5ae3312b4 |
scripts/iterate-m01-nvme.sh: pre-cleanup + dmesg clear for reproducible m01 re-verify
QA-owned adaptation to make Path B reconnect matrix runs deterministic
on m01. Enables BUG-005 post-fix m01 re-verification against a clean
slate.
Changes:
- pkill stale blockmaster/blockvolume before start_services
- dmesg --clear before each run so check_dmesg_clean doesn't trip
on entries from a prior cycle
Precondition for BUG-005 (commit
|
||
|
|
1d21b0ff68 |
BUG-005 fix: session layer stops closing the Provider-cached Backend
m01 Path B reconnect matrix cycle 2 exposed: kernel gets
nvme1n1: I/O Cmd(0x2) @ LBA 0, I/O Error (sct 0x3 / sc 0x2)
on the very first Read of a second nvme connect after a clean
disconnect.
SCT=3 SC=2 = ANA Asymmetric Access Inaccessible, mapped from
frontend.ErrBackendClosed via nvme.NewBackendClosed(). NOT a
data-integrity bug — bytes on disk are intact. Pure Backend
lifecycle bookkeeping.
## Root cause
Session-layer code was calling Backend.Close() when a TCP session
ended:
- core/frontend/nvme/target.go handleConn: defer backend.Close()
- core/frontend/iscsi/session.go close(): s.backend.Close()
Fine under memback (Provider.Open creates a fresh backend struct
per call). Broken under DurableProvider which MUST cache one
Backend per volumeID because LogicalStorage is an exclusive
resource. The per-session Close flipped the CACHED backend
closed → next session received the same closed handle → all I/O
returned ErrBackendClosed → NVMe mapped to SCT=3 SC=2.
V2 structurally avoided this: Subsystem.Dev is registered via
AddVolume / unregistered via RemoveVolume (admin-level), and
Controller.shutdown() explicitly does NOT touch the device. See
weed/storage/blockvol/nvme/{server.go,controller.go}.
V3 had the right intent (T3a mini plan §3: "Backend.Close marks
closed but does NOT tear down storage; Provider retains storage
handle") but the interface godoc didn't document WHO is allowed
to call Close. T2 target authors treated Backend.Close as
session-owned by pattern-matching memback's accidental shape.
## Changes
Production:
core/frontend/nvme/target.go -1 line (removed defer)
core/frontend/iscsi/session.go -3 lines (removed conditional close)
core/frontend/types.go +11 lines (Backend godoc —
Provider ownership clause)
Tests:
core/frontend/durable/bug005_session_reuse_test.go new (~120 LOC)
- TestT3_Bug005_ProviderCachedBackend_ReusableAcrossSessions
Matrix both impls. Pins: after session 1's "close", session 2's
Open returns a USABLE Backend (not ErrBackendClosed). Sits at
Provider level — doesn't need a real target session to exercise
the invariant the fix establishes.
- TestT3_Bug005_ExplicitBackendClose_IsAllowed
Counterfactual: explicit Close by a caller who owns the handle
is still legal; subsequent I/O returns ErrBackendClosed. This
documents what Close IS for (Provider.Close path) vs what it is
NOT for (implicit session teardown).
## Why existing tests missed it
All T3a/T3b/T3c in-process tests are:
- single-session (no disconnect-reconnect cycle), OR
- direct-handler (SCSIHandler.HandleCommand / IOHandler.Handle),
bypassing target.handleConn's defer
Only "real target × session 1 disconnect × session 2 open"
exercises cross-session cache poisoning. Same L1-passes-L2-fails
shape as BUG-001.
## Contract going forward
frontend.Backend godoc now states:
"Backend.Close() is OWNED BY THE PROVIDER. Session-layer
consumers MUST NOT call Close on a Backend obtained from
Provider.Open — treat the returned Backend as a BORROWED
reference..."
Backend.Close itself stays legal; explicit-owner Close is still
supported (Provider.Close path, tests). The fix is about NOT
having session/target teardown silently call it.
## Regression
go test ./core/... -count=1 → 17/17 packages ok, 0 FAIL
BUG-005 regression tests: 2 × 2 impls = 4 subtests green
Prior T3 suites: unchanged (no impact)
## Ledger row queued ACTIVE
INV-DURABLE-SESSION-LIFECYCLE-001: Across session disconnect +
reconnect, the Provider-cached Backend remains operational; I/O
on the reconnected session MUST NOT receive ErrBackendClosed
caused by prior session teardown.
## T3-end three-sign impact
- Path A rename still stands (INV-DURABLE-CLEAN-RESTART-001 etc.)
- New row INV-DURABLE-SESSION-LIFECYCLE-001 added to closure
- G4 partial-pass gate updated: "clean restart OK + cross-session
reconnect OK"; real-kill + ENOSPC remain T3-DEF-3/4 inventory
items for post-T3 batch
- m01 re-verification pending QA
## References
sw-block/design/bugs/005_backend_close_cross_session.md (full post-mortem)
V2 reference: weed/storage/blockvol/nvme/{server.go,controller.go}
Memory: feedback_porting_discipline.md updated — new-abstraction
ownership drift citation added (third citation; BUG-001 +
pragmatic-evolution-revert + this one)
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
|
||
|
|
c642e42486 |
T3 pre-sign review fix Phase 1: QA artifacts + doc integrity
PM + architect pre-T3-sign review (2026-04-22) identified 6 blockers + 1 low.
Phase 1 addresses doc-integrity + uncommitted-artifact findings:
- B6 (PM-M1): commit QA artifacts previously uncommitted
- core/frontend/durable/t3b_qa_l1_addendum_test.go (3 L1 tests:
ConcurrentIO_SyncBarrier, RecoverThenServe, LargeSpanningWrite;
all matrix-parameterized walstore + smartwal)
- scripts/iterate-m01-nvme.sh (m01 harness with Matrix A/B/C/D
+ DURABLE_IMPL env var for two-impl coverage per Addendum A #1)
- B7 (PM-L1): perf baseline doc — remove stale "_TBD_ placeholder"
wording since first-light numbers are filled.
Phase 2 (real SIGKILL Matrix E + real ENOSPC Matrix F) follows in a
separate commit.
Review response log lives in
sw-block/design/v3-phase-15-t3-closure-report.md §H.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
|
||
|
|
6fbdf94df5 |
T3c: 4 scenarios × 2 impls + perf baseline + YAML shape docs
Per T3c mini plan §1 — closes T3 delivery except for T3-end three-sign.
Atomic per mini plan §3 inherited stop rules.
## Scope delivered
### 1. Four scenarios (matrix over walstore + smartwal)
core/frontend/durable/scenario_crash_recovery_test.go
TestT3c_Scenario_CrashRecovery_AckedBytesByteExact
→ pins INV-DURABLE-001 (canonical G4 gate)
core/frontend/durable/scenario_wal_replay_test.go
TestT3c_Scenario_WALReplay_NAckedWrites
→ pins INV-DURABLE-WAL-REPLAY-001
core/frontend/durable/scenario_fsync_boundary_test.go
TestT3c_Scenario_FsyncBoundary_AckedSurvivesUnackedMayVanish
→ pins INV-DURABLE-FSYNC-BOUNDARY-001
core/frontend/durable/scenario_disk_fill_test.go
TestT3c_Scenario_DiskFill_OutOfRange_FailsCleanly
→ pins PCDD-DURABLE-DISK-FULL-001
Each scenario:
- Uses the shared logicalStorageFactories() matrix helper from T3a
- Runs as `{smartwal, walstore}` subtests
- Is an in-process L1 test (not subprocess / not YAML replay)
- Simulates "restart" by building a FRESH DurableProvider over
the same StorageRoot (closes + re-opens all state cleanly)
### 2. YAML shape docs
testrunner/scenarios/testdata/t3c-durable-crash-recovery.yaml
testrunner/scenarios/testdata/t3c-durable-wal-replay.yaml
testrunner/scenarios/testdata/t3c-durable-fsync-boundary.yaml
testrunner/scenarios/testdata/t3c-durable-disk-fill.yaml
Documentation of each scenario's shape, variant matrix, and
ledger pin. Authoritative test is the Go replay; YAML mirrors it
for reviewability per mini plan §1.1.
### 3. Perf baseline
testrunner/perf/t3c-durable-baseline.md
Workload spec + first-light numbers (sw dev Windows 11)
core/frontend/durable/perf_baseline_test.go
BenchmarkT3c_DurablePerf — matrix benchmark, both impls
First-light numbers at 8000 iterations, Sync every 64 writes:
- walstore: 197 µs/op, 20.75 MB/s, ~5k ops/s
- smartwal: 303 µs/op, 13.50 MB/s, ~3.3k ops/s
Characterization only, no threshold. Benchmark caps iterations
at 8000 so WAL capacity is not the bottleneck — not a saturation
benchmark. Real sustained numbers deferred to m01 fio run.
### 4. Closure report
sw-block/design/v3-phase-15-t3-closure-report.md
(seaweedfs repo — not in this commit)
§A-§F: batch history, delivery summary, V2 port depth audit,
ledger rows, T3-end three-sign table, change log.
## Acceptance (mini plan §2)
#1 All 4 scenarios × 2 impls (8 subtests) ✅ all green
#2 Frontend continuity — existing T2 tests green ✅ (see #5)
#3 m01 fs-workload smoke ⏸ post-sign (QA-owned)
#4 Perf baseline artifact ✅ numbers filled
#5 Full regression ✅ 17/17 pkgs ok
#6 Boundary guard ✅ durable/ auto-covered
#7 6 new ledger rows queued ✅ (4 T3c + 5 from T3a/T3b already ACTIVE)
#8 16 T2 ACTIVE rows still ACTIVE ✅ (no regression in iscsi/nvme)
#9 Closure report filled end-to-end ✅ (seaweedfs repo)
#10 T3-end three-sign ⏸ pending architect + PM + QA
## Regression
go test ./core/... -count=1 → 17/17 packages ok
- core/frontend/durable: 2.0s (76 subtests; +16 from T3c: 4 scenarios × 2 + 8 from earlier)
- core/frontend/iscsi: 31.5s (no regression)
- core/frontend/nvme: 61.3s (no regression)
- core/host: 127.7s (subprocess tests still memback; no durable wire)
- all others within normal range
## Stop rules honored
#port-model default ✅ (scenarios use public API only; no
storage internals)
#no scope creep T4 ✅ (no replication / failover surface
introduced)
#no new production code beyond T3a+T3b deliverables ✅
(scenarios + perf are test infra only)
## Out of T3c (post-three-sign, not blocking)
- m01 fs-workload verification (iterate-m01-nvme.sh tweak — QA)
- fio sustained numbers replace Go-bench first-light
- 24h m01 soak
## References
sw-block/design/v3-phase-15-t3-port-audit.md
sw-block/design/v3-phase-15-t3a-mini-plan.md (CLOSED
|
||
|
|
e2ae3910c3 |
T3b follow-up: iSCSI + NVMe → durable matrix integration tests
Per "make sure all test works for regular/smart wal" follow-up:
existing T3a/T3b tests exercise the adapter + provider against
both walstore and smartwal, but the iSCSI/NVMe wire tests (added
in
|
||
|
|
29e3d0de0c |
T3b: DurableProvider + Recovery + iSCSI SYNC_CACHE + NVMe Flush + cmd wire
Atomic per T3b mini plan §3 stop rule #1 — all 5 deliverables one commit.
## Scope delivered (mini plan §0)
### 1. DurableProvider (G-int.4)
New core/frontend/durable/provider.go:
- `ImplName` ("smartwal" | "walstore"); production default smartwal
per PM direction
- `ProviderConfig` with StorageRoot + Impl + geometry + OpenTimeout
- `NewDurableProvider` validates selector; mkdir storage root
- `Open(ctx, volumeID)` caches handle per volumeID; opens existing
file (verifying magic vs selector) or creates fresh
- `RecoverVolume(ctx, volumeID)` runs LogicalStorage.Recover on
the cached storage, flips backend operational bit per report
- `Close()` tears down in correct order (backend close → storage
close); idempotent
- ImplKind mismatch detection: peeks 4-byte magic BEFORE storage
Open so the error message names selector vs on-disk kind
(ErrImplKindMismatch). Never silently coerces (Addendum A #2).
- testback.StaticProvider unchanged (audit §11 G-int.4).
### 2. Recovery wrapper (G-int.5)
New core/frontend/durable/recovery.go:
- Pure function `Recover(storage, volumeID) RecoveryReport`
- Report carries VolumeID, RecoveredLSN, Evidence string, Err
- Zero side-effects on backend — Provider (or cmd) flips
SetOperational based on report
- Option 3 from audit §10.5 honored: no local epoch mirror;
per-I/O adapter fence check remains sole authority-drift guard
- §3.2 boundary: no new publication path; readiness surfaces
via existing /status + adapter's SetOperational
### 3. iSCSI SYNC_CACHE wire
core/frontend/iscsi/scsi.go:
- SYNCHRONIZE_CACHE(10) [0x35] + SYNCHRONIZE_CACHE(16) [0x91]
dispatch to backend.Sync(ctx) (formerly no-op Good)
- Sync errors map to CHECK CONDITION / MEDIUM_ERROR /
WRITE_ERROR (SPC-5 §D.2.14). Stop rule §3.6 (error-faithful
Sync wire): swallowing to Good is forbidden.
core/frontend/iscsi/errors.go:
- Added `ASCWriteError = 0x0C` (SPC-5 ASC table)
### 4. NVMe Flush wire
core/frontend/nvme/io.go + session.go:
- `ioFlush` opcode (0x00) handler dispatches to backend.Sync via
IOHandler.Handle
- Session dispatchIO routes Flush through the handler (was:
direct Success enqueue)
- Sync errors map via mapBackendError; ErrStalePrimary → ANA
Transition, generic → Internal Error
### 5. cmd/blockvolume wire
Added flags:
- --durable-root PATH enables DurableProvider; empty = memback
- --durable-impl NAME "smartwal" (default) | "walstore"
- --durable-blocks N first-create geometry
- --durable-blocksize N first-create block size
Startup sequence (when --durable-root is set):
1. Build DurableProvider
2. Open the served volumeID (creates storage if absent)
3. RecoverVolume → flips adapter operational bit per outcome
4. Use the provider for both iSCSI and NVMe target wiring
5. On shutdown, Close the provider (backend + storage) in order
memback path unchanged when --durable-root is empty.
### 6. Adapter lifecycle design note
Backend.Close() does NOT tear down underlying LogicalStorage
(already was the T3a contract). Provider.Close() is the only
teardown path for storage; both are idempotent.
## Acceptance (mini plan §2)
#1 `TestT3b_DurableProvider_ImplementsProvider` ✅ both impls
#2 `TestT3b_DurableProvider_Open_SelectsImpl_Matrix` ✅ (file magic verified on disk)
#3 `TestT3b_DurableProvider_Open_StartsNotOperational` ✅ Read/Write/Sync → ErrNotReady
#4 `TestT3b_DurableProvider_Open_ImplKindMismatch_FailsFast` ✅ ErrImplKindMismatch named
#5 `TestT3b_Recovery_CleanRecover_FlipsOperational` ✅ + `*UnopenedVolume*` + pure-fn tests
#6 `TestT3b_ISCSI_SyncCache_DispatchesToBackend` ✅ SYNC_CACHE(10) + (16)
#7 `TestT3b_NVMe_Flush_DispatchesToBackend` ✅ ioFlush → backend.Sync
#8 `TestT3b_DurableProvider_Lifecycle_*` ✅ close isolation + double-close idempotent
#9 Full regression ✅ 17/17 core packages ok
#10 Boundary guard ✅ core/frontend/durable/ auto-covered
## Regression
go test ./core/... -count=1 → 17/17 packages ok
- core/frontend/durable: 0.5s (16 T3a + 13 T3b subtests all green)
- core/frontend/iscsi: 31.5s
- core/frontend/nvme: 61.3s
- core/host: 122.8s (no regression)
- all others sub-second or unchanged
## Stop rules honored
#1 atomic (5 deliverables one commit) ✅
#2 no OnDegraded reinstated ✅
#3 no local epoch mirror ✅
#4 no new publication path ✅
#5 Provider.Impl is config-driven string; no compile branch ✅
#6 iSCSI + NVMe Sync errors map faithfully ✅
#7 no scenarios / no perf landed in T3b ✅
## Ledger rows queued ACTIVE at T3b close
- INV-DURABLE-PROVIDER-SELECT-001
- INV-DURABLE-RECOVERY-READSIDE-001
- INV-DURABLE-SYNC-WIRED-001
Existing (T3a / T1) rows stay ACTIVE:
- INV-DURABLE-OPGATE-001, INV-DURABLE-IMPL-IDENTITY-001
- INV-FRONTEND-002.{EPOCH,EV,REPLICA,HEALTHY}
## Out of T3b (per mini plan)
- 4 G6 scenarios → T3c
- m01 iSCSI + NVMe fs-workload smoke → T3c
- Perf baseline → T3c
- T3 closure report + T3-end three-sign → T3c
## References
sw-block/design/v3-phase-15-t3a-mini-plan.md (CLOSED
|
||
|
|
10cd117bb4 |
T3a: StorageBackend adapter + Backend interface extension + superblock impl-identity
Atomic per T3a mini plan §3 stop rules #1-#3: - Adapter file atomic (G-int.1 + G-int.2 + G-int.3 one commit) - Interface extension atomic with all consumers - Superblock schema bump one-way with migration discipline ## Scope delivered (mini plan §0) ### 1. core/frontend/durable/storage_adapter.go (NEW) StorageBackend wraps any LogicalStorage and exposes the full frontend.Backend surface. Four responsibilities: - byte↔LBA translation with RMW on partial blocks (G-int.1) - per-I/O fence check preserving INV-FRONTEND-002.* (G-int.2) - operational gate preserving INV-DURABLE-OPGATE-001 (G-int.3) - Sync dispatches to LogicalStorage.Sync (G-int.2 policy) Storage lifecycle NOT owned by backend — Close marks the handle closed but does not tear down LogicalStorage (Provider owns that, lands in T3b). ### 2. Backend interface extension (core/frontend/types.go) Two new methods: Sync(ctx) error + SetOperational(ok, evidence). SetOperational godoc pins the invariant: does NOT touch identity /lineage/epoch — local readiness only; authority publication stays on the master path (PCDD-STUFFING-001). All 6 existing Backend implementations gain trivial impls in the same commit (stop rule #2): - memback.backend (Sync no-op, SetOperational state-flip) - testback.RecordingBackend (SyncCall recording, SyncCount) - testback.StaleRejectingBackend (Sync returns ErrStalePrimary) - iscsi countingBackend (delegates) - nvme countingFaultBackend (delegates) - nvme writeCountingBackend (delegates) ### 3. Superblock impl-identity (Addendum A Addition 2) Both walstore (core/storage/superblock.go) and smartwal (core/storage/smartwal/superblock.go) headers gain ImplKind + ImplVersion fields. superblockVersion/headerVersion bumped 1→2. - newSuperblock rejects ImplKindUnset (0) at create time - readSuperblock + validate reject unknown ImplKind - CreateWALStore passes ImplKindWALStore=1 + WALStoreImplVersion=1 - smartwal.newHeader passes implKindSmartWAL=2 + smartwalImplVersion=1 Stop rule #3 (one-way bump): no compat read path for v1; opening a v1 file with v2 code returns errSuperblockBadVer. No existing on-disk production data expected since T3 hasn't shipped. ### 4. Matrix test infrastructure (Addendum A Addition 1) core/frontend/durable/storage_adapter_test.go uses a single shared logicalStorageFactories() helper returning {walstore, smartwal} factories. Every adapter test iterates over it — adding a new impl later = one edit (stop rule #4). TestT3a_MatrixCoverage is a sanity canary that trips if the factory list drifts. ## Tests landed (mini plan §2 acceptance) #1 TestT3a_StorageBackend_ImplementsBackend ✅ walstore + smartwal #2 TestT3a_StorageBackend_ByteLBATranslation_Matrix ✅ 6 shape subtests × 2 impls #3 TestT3a_StorageBackend_FenceCheck_{Epoch,EV,Replica,Healthy} ✅ 4×2 #4 TestT3a_StorageBackend_OperationalGate_{BeforeOpen,FlipBack,Evidence} ✅ 3×2 #5 TestT3a_StorageBackend_Sync_DispatchesToStorage ✅ 2 impls #6 All tests matrix-parameterized — N×2 execution TestT3a_MatrixCoverage canary pins factory count #7/#8 Superblock schema bump covered by existing core/storage tests: - newSuperblock rejects ImplKindUnset at create - readSuperblock rejects unknown ImplKind at open - CurrentVersion bump is forward-only #9 Full regression green: 17 core packages, incl. prior T0/T1/T2 suites #10 boundary_guard_test.go auto-covers core/frontend/durable/ (TestFrontendCannotMintAuthority_BoundaryGuard walks the whole frontend tree recursively; no explicit extension needed) ## Regression go test ./core/... -count=1 → 17/17 packages ok - core/frontend: 17.7s - core/frontend/durable: 0.3s (22 subtests all green) - core/frontend/iscsi: 31.3s (no regression) - core/frontend/nvme: 61.1s (no regression) - core/storage: 7.2s (schema bump accepted) - core/storage/smartwal: 0.3s - core/host: 122.4s - All others sub-second ## Out of T3a per mini plan - DurableProvider (T3b) - Recovery integration (T3b) - iSCSI SYNCHRONIZE CACHE / NVMe Flush wiring (T3b) - 4 G6 scenarios + perf baseline (T3c) ## Ledger rows queued ACTIVE at T3a close - INV-DURABLE-OPGATE-001 (operational gate preserves INV-FRONTEND-002.*) - INV-DURABLE-IMPL-IDENTITY-001 (superblock self-identifies; mismatch fails fast) ## References sw-block/design/v3-phase-15-t3-port-audit.md (T3.0 LOCKED) sw-block/design/v3-phase-15-t3a-mini-plan.md (this batch spec) feedback_porting_discipline.md (port-model discipline) Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> |
||
|
|
11429ea3fb |
T2 Batch 11c tester deliverables: QA-authored tests + m01 iterate script
QA-owned tests and infra landed during Batch 11c sign-prep. These
files carry `Ownership: QA` headers — sw may not modify without
architect approval via §8B.4 Discovery Bridge.
## Files
### Kernel-realistic rewrites of prior QA tests
core/frontend/nvme/t2_v2port_nvme_pipelined_writes_test.go
core/frontend/nvme/t2_v2port_nvme_pipeline_extended_test.go
Post-BUG-001 revert rewrites to paired R2T+H2CData sequencing
(the pattern Linux kernel actually emits). Replaces the earlier
"send N cmds → read N R2Ts → then send all H2CData" shape which
QA withdrew after BUG-001 §13 post-mortem established that async
R2T emission is spec-legal but not kernel-realistic, and chasing
it broke m01 compatibility.
### B-tier early-landed regression tests
core/frontend/nvme/t2_v2port_nvme_disconnect_mid_r2t_test.go (L1B-4)
Pins server cleanup when host disconnects mid-H2CData-stream.
Ledger row: PCDD-NVME-SESSION-DISCONNECT-MID-R2T-001
core/frontend/nvme/t2_v2port_nvme_reconnect_loop_test.go (L1B-1)
50 attach/detach cycles + goroutine-leak sentinel. Surfaces
resource leaks that single-shot tests would miss.
Ledger row: PCDD-NVME-SESSION-RECONNECT-LOOP-001
### L3-A sign-prep infrastructure
scripts/iterate-m01-nvme.sh
m01 iteration harness for the remaining QA §4 checklist
item #4. Runs against real Linux NVMe/TCP initiator for
product-ready evidence.
## Regression
go test ./core/frontend/nvme/ -count=1 → ok 60.9s
Full suite green including these files (already verified locally
before commit).
## Sign-prep checklist progress (QA §4)
#1 L1-A ConcurrentQueueStress [x] commit
|
||
|
|
b0ccd2753b |
T2 Batch 11c sign-prep L1-A + L2-A: stress + scripted smoke tests
Sign-prep for T2B-NVMe-product-ready promotion (QA §4 checklist
items #1-3). Three new test files validating the V2-strict session
concurrency model under sustained load + a YAML-scripted subprocess
smoke for scenario reviewability.
## L1-A: ConcurrentQueueStress (t2_a_concurrent_queue_stress_test.go)
8 IO queues × 50 sequential Writes per queue = 400 Writes total.
Each Write is 32 KiB split into 8 × 4 KiB H2CData chunks (kernel
mkfs pattern). 90s hard deadline guards against deadlock
regressions.
Invariants:
- backend.calls == 400
- backend.bytes == 400 × 32 KiB
- no per-queue transport / status errors
- concurrent queues share target.ctrlMu without interference
Added helper: stressWriteTarget(t, volumeSize uint64) — spins up a
target with configurable volume size (default 1 MiB is too small
for 400 non-overlapping 32 KiB writes; test uses 64 MiB).
Runtime: 60 ms (localhost loopback).
## L1-A: LargeWriteStress (t2_a_large_write_stress_test.go)
100 sequential Writes at each of 5 sizes (512 B, 4 KiB, 8 KiB,
16 KiB, 32 KiB MDTS boundary). Per-iteration asserts:
- Exactly one R2T per cmd with DATAL == totalBytes (pins the
single-R2T-per-cmd invariant from the V2-strict revert)
- backend.calls / backend.bytes accumulate correctly
- Success status on every iteration
Added helper: writeChunkedOnClient(t, cli, slba, nlb, payload,
chunks) — issues a Write with N H2CData chunks (existing
nvmeClient.writeCmd does single-chunk only).
Runtime: 100 ms total across all 5 shapes.
## L2-A: Scripted smoke (testdata/t2-nvme-smoke.yaml +
## t2_l2_nvme_smoke_replay_test.go)
Declarative YAML scenario replayed against real blockmaster +
blockvolume subprocesses (reuses existing startL2NvmeHarness).
8 steps covering mixed sizes (1 LBA, 8 LBAs, 64 LBAs) + overwrite
semantics (write seed=11 at LBA 0, then write seed=44 at LBA 0,
assert read returns seed=44).
Payload semantics:
byte[i] = (seed + i) & 0xFF (deterministic; reads verify bit-
for-bit)
Adds yaml.v3 as test-only dep (already in go.mod via other
packages). Runtime: 13.7 s (subprocess bringup dominates).
## Files added
core/frontend/nvme/t2_a_concurrent_queue_stress_test.go (~130 LOC)
core/frontend/nvme/t2_a_large_write_stress_test.go (~160 LOC)
core/frontend/nvme/t2_l2_nvme_smoke_replay_test.go (~130 LOC)
core/frontend/nvme/testdata/t2-nvme-smoke.yaml (~60 LOC)
## Regression
go test ./core/frontend/nvme/ -count=1 → ok 60.9s
(full suite including existing L2 subprocess tests + new stress)
go test ./core/frontend/nvme/ -short -count=1 → ok 1.5s
(short mode skips L2 + stress; unit-only)
## Sign-prep checklist progress (QA §4)
#1 L1-A ConcurrentQueueStress [x] this commit
#2 L1-A LargeWriteStress [x] this commit
#3 L2-A t2-nvme-smoke.yaml + replay [x] this commit
#4 L3-A m01 iterate-m01-nvme.sh [ ] QA-owned
#5 Full regression green [x]
#6 Boundary guard green [x]
#7-#11 QA, post-checklist
Not in this commit (QA-authored files that landed in the same
working tree): t2_v2port_nvme_disconnect_mid_r2t_test.go,
t2_v2port_nvme_reconnect_loop_test.go, pipeline_extended +
pipelined_writes rewrites, scripts/iterate-m01-nvme.sh — QA to
commit separately.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
|
||
|
|
f99d5718a1 |
T2 Batch 11c BUG-003 fix: plumb KATO from Connect CDW12 into controller
Per port audit + QA Discovery Bridge scope (separate cycle from BUG-001). V2 fabric.go:41 extracts KATO from Connect CDW12 at Connect time; V3's ckpt 7 session rewrite dropped this and relied solely on Set Features 0x0F. Typical Linux hosts set KATO in Connect and do NOT issue a follow-up Set Features — so ctrl.kato was effectively zero on the target side for real hosts. ## Change session.go handleAdminConnect: after allocating the controller, call ctrl.setKATO(req.capsule.D12). Unit matches V2 (uint32 round-trip, no ms↔100ms conversion). QA constraint #2 preserved: store-only, no timer armed. 6 LOC in session.go plus log-line update. ## Test client connectOptions gains a KATO uint32 field; dialAndConnectOpts plumbs it into admin Connect's CDW12. ## Tests (new, all GREEN) - TestT2V2Port_NVMe_Connect_KATO_CDW12_Persisted — Connect with KATO=12000, assert Get Features 0x0F returns 12000 - TestT2V2Port_NVMe_Connect_KATO_Zero_Accepted — KATO=0 valid, round-trips as 0 - TestT2V2Port_NVMe_Connect_KATO_OverriddenBySetFeatures — V2 precedence: Connect stores KATO, later Set Features 0x0F overwrites (last-write-wins) ## Regression go test ./core/frontend/nvme/ -count=1 → ok 32.0s Existing 11b TestT2Batch11b_SetFeatures_KeepAliveTimer_RoundTrips stays green (same storage cell). ## References sw-block/design/bugs/003_nvme_kato_connect_cdw12_ignored.md sw-block/design/v3-phase-15-t2-nvme-port-audit.md (M-category fabric.go gap) V2 source: weed/storage/blockvol/nvme/fabric.go:41, :244 ## Exit criteria (from BUG-003 §8) - [x] Connect CDW12 plumbed into ctrl.kato - [x] New test green; 11b KATO round-trip test stays green - [ ] Ledger row PCDD-NVME-FABRIC-CONNECT-KATO-001 promoted ACTIVE (QA, after m01 verification) Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> |
||
|
|
bd1f798051 |
T2 Batch 11c BUG-001 revert pragmatic evolution → V2-strict faithful port
Reverts the per-CID pendingWrites + async goroutine-spawn design from commit |
||
|
|
6d2c04802d |
T2 Batch 11c BUG-001 fix: port V2 RX/TX split into V3 session.go
Bundles Batch 11b (signed, uncommitted) + BUG-001/002/004 co-fix per
Discovery Bridge approved 2026-04-22. Scope delta vs. port plan §5.3:
session-loop rewrite ~250-300 LOC was classified as Linux-compat polish
at 80 LOC; actual need is a full mechanism port (see port audit).
BUG-001 (primary) — mkfs.ext4 hang on m01 / queue-internal CapsuleCmd
pipelining. Linux kernel ships multiple Write cmds on one IO queue
before any R2T is consumed; V3's serial session loop read cmd-N+1 bytes
while collecting H2CData-N and errored "expected H2CData, got 0x4".
Design:
- serve() splits Phase 1 (sync ICReq/ICResp) from Phase 2 (rxLoop +
txLoop goroutines with respCh between).
- rxLoop is sole reader post-IC. Routes by PDU type:
CapsuleCmd -> parseCapsule + dispatchFromRx
H2CData -> routeH2CData, dispatches bytes to pendingWrite by
CCCID; closes done when buffer full
- txLoop is sole writer post-IC. Drains respCh; handles CapsuleResp,
C2HData+CapsuleResp (Read/Identify), and R2T.
- IO Write path: dispatchIOWrite registers a pendingWrite, enqueues
R2T, spawns handler goroutine that waits on done then calls backend.
- Admin/Fabric handlers run synchronously in rxLoop (unchanged from
V2 shape) but enqueue responses through respCh instead of touching
s.w directly.
Deviation from strict V2 port (documented in session.go top comment):
V2's inline collectR2TData -> recvH2CData + pendingCapsules works for
real Linux kernels (they send H2CData immediately after R2T) but
deadlocks against QA's spec-strict tests where host sends N cmds and
expects N R2Ts before any H2CData. V3 moves H2CData collection out of
rxLoop into per-CID pendingWrites map so R2T emission is async. ~60 LOC
delta vs. strict V2 port. QA sign referred to the RX/TX split concurrency
shape, which this preserves verbatim. The spec-correctness advantage
(async R2T) is a pragmatic evolution, not a reinvention of the per-CID
state machine QA flagged.
BUG-002 — fcDisconnect handler. V3 previously returned Invalid Opcode on
`nvme disconnect`. Now handleDisconnect enqueues a success CapsuleResp
and returns errDisconnect sentinel; serve() maps the sentinel to nil.
BUG-004 — SQHD wrap at queueSize + flowCtlOff. Connect now parses
CDW11 low-16 (SQSIZE zero-based +1) and bit 18 (CATTR bit 2). advanceSQHD
wraps at queueSize; writeResponse reports 0xFFFF when flowCtlOff.
Handler signature migration: handleAdminIdentify / handleSetFeatures /
handleGetFeatures / handleKeepAlive / handleAsyncEventRequest /
handlePropertyGet / handlePropertySet now take *Request and route
through enqueueResponse. AER non-blocking park (QA #1) preserved —
handler returns nil without enqueueing when slot is free.
BUG-003 (KATO from Connect CDW12) and RF-1 (bufpool.go) explicitly
OUT of this commit per Discovery Bridge scope.
Tests:
- TestT2V2Port_NVMe_IO_Pipelined2WritesSameQueue (canonical) RED -> GREEN
- TestT2V2Port_NVMe_IO_PipelinedNWritesSameQueue (N=2,4,8,16,32) RED -> GREEN
- TestT2V2Port_NVMe_IO_ConnectionCloseDrainsInflight RED -> GREEN
- All 7 prior debug tests green
- 11a/11b A-tier + adversarial tests green
- Full nvme regression: ok 31.6s (no perf regression)
References:
sw-block/design/bugs/001_nvme_mkfs_r2t_hang_m01.md (BUG-001)
sw-block/design/bugs/002_nvme_fabric_disconnect_missing.md (BUG-002)
sw-block/design/bugs/004_nvme_sqhd_no_wrap.md (BUG-004)
sw-block/design/v3-phase-15-t2-nvme-port-audit.md (scope justification)
feedback_porting_discipline.md (lesson citation)
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
|
||
|
|
a73909ec21 |
T2 Batch 11a: NVMe admin dispatch + Identify + queue routing + CNTLID
Per v3-phase-15-t2-batch-11-port-plan.md §7 11a scope (LOCKED
2026-04-22). Port-model port of V2 identify.go + queue model +
controller-id registry. Unlocks Go-harness admin Identify path
+ existing IO path; Linux nvme connect still gated on 11b
Property/Features/KeepAlive/AER work.
core/frontend/nvme/protocol.go
Added admin opcode constants: adminGetLogPage, adminIdentify,
adminAbort, adminSetFeatures, adminGetFeatures, adminAsyncEvent,
adminKeepAlive. Fabric types: fcPropertySet, fcPropertyGet,
fcDisconnect. CNS codes for Identify. identifySize constant.
VS version constant (nvmeVersion13 only — declared and used;
unused nvmeVersion14 removed per port-model discipline).
core/frontend/nvme/target.go
New adminController struct + Target-level CNTLID registry:
allocAdminController(subNQN, hostNQN, volumeID) *adminController
lookupAdminController(id) *adminController
releaseAdminController(id)
CNTLIDs allocated monotonically from 1 (0 reserved); released
on admin-session close.
core/frontend/nvme/session.go
Session now carries qid / qidSet / ctrl / target references.
newSession signature extended to take *Target.
handleCapsuleCmd refactored per port plan §3.4 R5:
- Fabric commands bypass the qid gate (they establish it)
- Post-Connect: route by s.qid via adminDispatch / ioDispatch
- Admin queue accepts admin opcodes only (Invalid Opcode for IO)
- IO queue accepts IO opcodes only (Invalid Opcode for admin)
handleFabric split into handleAdminConnect + handleIOConnect:
- QID decoded from CDW10[31:16]
- Admin Connect: CNTLID must be 0xFFFF or 0x0000 (request new);
allocate + register + reply with CNTLID in DW0[15:0]
- IO Connect: cite existing CNTLID; validate exists + SubNQN
matches; pin ctrl pointer. HostNQN NOT cross-checked (V2
parity + Linux spec-compat) — T8 owns auth.
- Double-Connect on same session rejected (qidSet gate)
close() releases admin CNTLID from Target registry. IO sessions
outliving admin hold their pinned ctrl pointer; new IO Connects
citing a released CNTLID fail registry lookup with
ConnectInvalidHost.
core/frontend/nvme/identify.go (NEW — port-model port of V2)
Four CNS builders per NVMe 1.3 §5.15.2:
- Identify Controller (4 KiB)
- Identify Namespace (4 KiB)
- Active NS List
- NS Descriptor List (NGUID designator NIDT=0x02)
11 deep-read corrections applied (port plan §3.5 D1-D11):
D1 Serial derived from VolumeID via sha256 (R1 symmetry with
Batch 10.5 follow-up #2 VPD 0x80); no "SWF00001" stub
D2 CMIC / ANACAP / ANAGRPMAX / NANAGRPID / NS ANAGRPID = 0
(ANA log is 11c-conditional)
D3 ONCS (WriteZeros + DSM) = 0 (not implemented)
D4 NSFEAT (thin-prov/Trim) = 0
D5 DLFEAT (deallocate) = 0
D6 AERL = 0 (one pending-AER slot; finding #2)
D7 OFCS (Disconnect) = 0 (not in Batch 11 scope)
D8 SubNQN NUL-terminated (not space-padded) at offset 768
D9 LBAF[0] LBADS = 9 for 512B (bits.TrailingZeros32)
D10 IOCCSZ = (64 + MaxH2CDataLength) / 16 = 2052
D11 VS = NVMe 1.3; MNAN = 1
NGUID derivation (R1 / port plan §3.3 N1):
NGUID[16] = sha256(SubsysNQN + "\x00" + VolumeID)[:16]
EUI-64[8] = NGUID[:8]
Deterministic + per-volume unique + per-subsystem unique.
QA A-tier pins determinism in a separate file.
core/frontend/nvme/client_support_test.go
Rewrote nvmeClient to open admin (QID=0) + IO (QID=1) TCP
connection pair. Admin Connect allocates CNTLID, IO Connect
cites it. writeCmd/readCmd route through ioConn (back-compat
with ckpt 7 tests). adminIdentify(cns, nsid) added. Existing
L1 and L2-harness tests now exercise real multi-queue Connect.
core/frontend/nvme/identify_test.go (NEW)
20 sw-owned tests:
- D1-D11 field pins on Identify Controller (10 tests)
- Identify Namespace fields (4 tests: size, NSFEAT+DLFEAT,
ANAGRPID, LBAF, NGUID/EUI)
- Active NS List + NS Descriptor List (2 tests)
- Queue routing enforcement (2 tests: admin-rejects-IO,
IO-rejects-admin)
- CNTLID lifecycle (2 tests: unknown rejected with
ConnectInvalidHost 0x82; preset rejected with
ConnectInvalidParameters 0x80)
- End-to-end (1 test: admin Identify all 4 CNS + IO Write/Read)
core/frontend/iscsi/t2_v2port_scsi_inquiry_test.go (QA-authored)
QA closed the Batch 10.5 follow-up #2 N1 symmetry pin via
TestT2V2Port_SCSI_InquiryVPD80_SerialDerivationDeterministic
(4 sub-tests: same-VolumeID determinism, different-VolumeID
collision, hex-shape, operator-override bypass).
core/frontend/nvme/t2_v2port_support_test.go (QA-authored, NEW)
Skeleton shared utilities for Batch 11 A-tier tests per
v3-phase-15-t2-batch-11-test-skeleton.md. Pre-authored to
slot in when 11a lands; compiles today.
Tests green (no regressions):
core/frontend/nvme: 51 tests (was 28 pre-11a; +23 including
QA skeleton support helpers)
core/frontend/iscsi: 106 tests (was 104; +2 QA VPD 0x80
symmetric pin)
All other packages: unchanged.
Full regression: frontend 17.6s / iscsi 31.2s / nvme 31.2s
Stop-rule audit:
- In-allowlist per decision §5.2: Identify (all 4 CNS) ✓
- QA finding #1 (11a includes A10 + A10.5) ✓
- QA finding #3 (ANA fields zero in 11a/11b) ✓
- §6 #4 advertised≡implemented: OACS/OAES/ONCS/CMIC/ANACAP
/KAS/OFCS all zero aligned with un-ported admin commands ✓
- §6 #7 no V2 adapter.go / write_retry.go / bufpool.go ported ✓
- No core/authority / core/adapter imports in nvme package ✓
- No AssignmentInfo / authority-minting literals ✓
- Stale R/W semantics unchanged (IO path unmodified) ✓
- N1 symmetry: Serial derives per VolumeID (ckpt 10.5 lesson) ✓
Sign tier per port plan §7: T2B-NVMe-provisional remains.
11a acceptance met (Go-harness Identify + IO round-trip green).
Linux nvme connect still gated on 11b (Property+Features+KATO).
Pre-commit self-review applied 2 fixes:
I1: Removed unused nvmeVersion14 constant (dead code)
I2: Removed sw-added HostNQN cross-check in handleIOConnect
(V2 doesn't do it; Linux-compat safer)
Known items flagged for 11b or later:
K1: IO sessions outliving admin use pinned ctrl pointer; new
IO Connects fail. Documented in §3.1 A10.5 note.
K2: connected + qidSet tracked separately (dispatch gate vs
re-Connect gate)
K3: NSID=0xFFFFFFFF (broadcast) mapped to NSID=1 internally
K5: adminDispatch ctx parameter unused until 11b
QA-owned A-tier tests pending (per port plan §4):
- TestT2V2Port_NVMe_IdentifyNamespaceDescriptor_Deterministic
(4 pins: R1 a-d)
- TestT2V2Port_NVMe_IdentifyAdvertisedFeatures_AreServed
(walks advertised bits; §6 stop-rule #4 enforcement)
- TestT2V2Port_NVMe_NoAuthorityOrStorageBleed_AdminSurface
(AST boundary guard extended to identify.go)
|
||
|
|
275fdaeaa1 |
T2 Batch 10.5 follow-up #2: VPD 0x80 Serial N1 symmetry
QA review (2026-04-22) caught the N1 asymmetry: Batch 10.5
fixed VPD 0x83 NAA to be per-VolumeID derived, but VPD 0x80
Serial still defaulted to the hardcoded "SWF00001" stub. Linux
udev reads both pages together for its unique fingerprint; any
site running more than one volume would have distinct NAA but
identical Serial — exactly the "unusable hardcoded stub"
failure mode that N1's own comment flagged as the reason NAA
was changed away from V2's stub.
Fix shape (QA's Option 2): derive Serial from VolumeID when
cfg.SerialNo is not explicitly configured. Operator override
path preserved — an operator who wants a specific serial (asset
tag etc.) still sets cfg.SerialNo and it's honored verbatim.
core/frontend/iscsi/scsi.go:
- New serialFromVolumeID() helper: hex(sha256(VolumeID)[:8]) →
16 lowercase ASCII chars. 64 bits of entropy, deterministic,
per-volume unique. Mirrors naaFromVolumeID shape.
- NewSCSIHandler no longer defaults serialNo to "SWF00001".
Empty cfg.SerialNo leaves h.serialNo empty so the VPD 0x80
handler can derive on demand (it needs backend.Identity()
which isn't available until post-login in the session layer).
- inquiryVPD at case 0x80: if h.serialNo is empty, derive via
serialFromVolumeID(h.backend.Identity().VolumeID); otherwise
use the operator-supplied override as-is.
- Added "encoding/hex" import.
core/frontend/iscsi/scsi_batch10_5_test.go:
- TestT2Batch10_5_InquiryVPD80_ReturnsSerial updated: assert
16-char lowercase hex shape + regression guard that serial
is NOT the old "SWF00001" stub.
- NEW TestT2Batch10_5_InquiryVPD80_RespectsOperatorOverride:
cfg.SerialNo="ASSET-TAG-007" returns verbatim, so operators
can still override the derived default.
QA Owner will pin the symmetric determinism/collision invariant
in a separate A-tier Phase 3 test — this commit is sw's Option 2
fix, not the symmetric QA test.
Tests green (no regressions):
core/frontend/iscsi: 104 tests (was 102; +2)
All other packages: unchanged.
Stop-rule audit:
- inside §5.1 allowlist (VPD 0x80 was already an approved
page; this tightens the default rather than adding surface)
- advertised ≡ implemented discipline holds (Serial still
advertised; now meaningful)
- no stale W/R semantic change
- no core/authority / core/adapter bleed
|
||
|
|
1254e7cb0e |
T2 Batch 10.5 follow-up: LBPME overclaim + allocLen truncation +
standard INQUIRY V2-tuned shape
Three review findings closed (PM + architect, 2026-04-22):
Finding 1 — PM High / architect Medium: LBPME overclaim.
READ_CAPACITY(16) was advertising LBPME=1 (logical block
provisioning management enabled) while port plan §3.2 skip
list keeps UNMAP + VPD 0xB2 OUT of Batch 10.5. Aligned with
the principle from VPD 0x00 ("advertised ≡ implemented"): set
LBPME=0 until UNMAP + VPD 0xB2 are in scope. Comment updated
to explain the prior "V2 parity" justification was wrong — V2
parity on the SHAPE holds, but V2 sets LBPME=1 because V2
also implements the backing ops; T2 doesn't.
Finding 2 — architect Medium: readCapacity16 allocLen bug.
`if allocLen < 32 { allocLen = 32 }` forced up to the natural
response size, so the subsequent truncation branch never
fired. Initiator requesting a short response got the full
32 bytes — a protocol violation per SPC-5 §6.6 ("initiator
allocation length is authoritative"). Removed the force-up.
For allocLen < 32 the response now truncates correctly.
Finding 3 — PM Medium: standard INQUIRY under-ported.
V3 was returning a 36-byte minimal response; V2 tunes 96
bytes with Additional Length=91 and CmdQue=1 (command
queuing supported). Ported V2's shape:
byte 4 = 91
byte 7 = 0x02 (CmdQue=1)
bytes 8-31: vendor / product, V2-matched
bytes 32-35: rev "0001"
Skipped V2's TPGS bit (ALUA is skip-list). The previous
36-byte response worked for iscsiadm attach but forced the
kernel SCSI layer to assume minimum SPC capabilities — V2
tuning removes that.
core/frontend/iscsi/scsi.go:
inquiry(): 36 → 96 byte response, Additional Length=91,
CmdQue=1, allocLen default 96
readCapacity16(): drop force-up of allocLen; LBPME=0
core/frontend/iscsi/scsi_batch10_5_test.go:
Updated TestT2Batch10_5_ReadCapacity16_ReturnsLastLBAAndBlockSize:
now asserts LBPME == 0 (was: != 0)
NEW TestT2Batch10_5_ReadCapacity16_ShortAllocLen_Truncates:
{0,1,7,8,12,20,31} all truncate correctly; 100 caps at 32
NEW TestT2Batch10_5_Inquiry_StandardResponse_V2TunedShape:
pins 96-byte shape, Additional Length=91, CmdQue=1, TPGS=0
NEW TestT2Batch10_5_Inquiry_ShortAllocLen_Truncates:
SPC-5 §6.6 truncation rule for standard INQUIRY
Tests green (no regressions):
core/frontend/iscsi: 99 tests (was 96; +3 new regressions;
one existing assertion flipped
LBPME==0 from LBPME==1)
All other packages: unchanged.
Stop-rule audit after follow-up:
- advertised ≡ implemented discipline now holds end-to-end
- no new dispatch cases (fixes are field-level / length-level)
- skip list §3.2 unchanged (UNMAP, WRITE_SAME, PERSISTENT_RESERVE,
ALUA, VPD 0xB0/0xB2 still rejected)
- no stale W/R semantic change
- no core/authority / core/adapter bleed
Remaining for Batch 10.5 sign (QA Owner action):
- QA Owner A-tier Phase 3 tests per port plan §4:
* TestT2V2Port_SCSI_InquiryVPD00_AdvertisesOnlyImplemented
* TestT2V2Port_SCSI_InquiryVPD83_NAADerivationDeterministic
Sign-off tier unchanged: T2A-iSCSI-provisional. Batch 10.5
product-ready gate still requires the QA A-tier tests + m01
OS sanity pass.
|
||
|
|
48f667f768 |
T2 Batch 10.5: iSCSI SCSI OS probe surface — port-model port from V2
Per v3-phase-15-t2-port-model-decision.md §5.1 approved allowlist.
Port plan: v3-phase-15-t2-batch-10-5-port-plan.md (locked 2026-04-22).
First port-model batch after the Oct 21 model switch. Mechanism-
complete port of the V2 SCSI surface Linux kernel / iscsiadm
probes during attach + filesystem use. Unblocks m01 L2-OS sanity
without leaving the ckpt 9/10 stop-rule envelope.
core/frontend/iscsi/scsi.go (EXTEND, not rewrite):
Dispatch (12 new HandleCommand cases):
MODE_SELECT(6/10) → no-op Good (ckpt 10.5 §3.1.a pair-port)
START_STOP_UNIT → no-op Good (§3.1.a)
MODE_SENSE(6/10) → routed to modeSense6/modeSense10
SYNC_CACHE(10/16) → no-op Good (§3.3 N2; memback non-durable; T3 owns real flush)
READ(16)/WRITE(16) → 64-bit LBA + 32-bit transferLen; dispatches to doRead/doWrite
SERVICE_ACTION_IN(16) SA=0x10 → readCapacity16
INQUIRY VPD (EVPD=1): dispatcher replaces prior blanket reject.
0x00 (Supported pages) → advertises EXACTLY {0x00, 0x80, 0x83}
— matches the implemented set per §3.3 N3; kernel won't
get an advertised page then fail to read it.
0x80 (Unit serial number) → h.serialNo, 8-byte padded
0x83 (Device ID, non-ALUA branch) → one NAA-6 designator
derived from sha256(VolumeID)[:8] with high nibble pinned
to 0x6 (§3.3 N1 + naaFromVolumeID helper). Deterministic,
per-volume unique — avoids multipath / udev conflating
different volumes, which was V2's pre-ALUA stub bug.
0xB0 / 0xB2 / any other → IllegalRequest InvalidFieldInCDB
(explicitly NOT ported per port plan §3.2 skip list).
Mode pages (V2 Windows-tuned values preserved):
buildModePages(0x08) → modePage08: Caching, WCE=1 + RCD=0
buildModePages(0x0A) → modePage0A: Control default
buildModePages(0x3F) → both
Unknown page → empty pages (V2 parity).
READ_CAPACITY(16) 32-byte response: 64-bit last-LBA + block
size + LBPME=1 (V2 parity). 16-byte variants of Read/Write
use binary.BigEndian.Uint64 for LBA (bytes 2-9) + Uint32 for
transferLen (bytes 10-13). Both dispatch to existing
doRead/doWrite — same bounds check + mapBackendError path.
Opcode constants grew: ModeSelect6/10, ModeSense6/10,
StartStopUnit, SyncCache10/16, Read16, Write16,
ServiceActionIn16, plus SaiReadCapacity16 service action.
core/frontend/iscsi/session.go:
cdbExpectedWriteBytes now covers WRITE(16) alongside WRITE(10).
Preserves the ckpt-10-hardening EDTL/CDB pre-flight check for
the new 16-byte variant.
Tests (sw-owned, port plan §4):
core/frontend/iscsi/scsi_modesense_test.go (NEW, 10 tests)
MODE_SENSE(6) pages 0x08 / 0x0A / 0x3F / unknown / truncation
MODE_SENSE(10) page 0x08 (10-byte header)
MODE_SELECT(6/10) no-op Good
START_STOP_UNIT no-op Good
core/frontend/iscsi/scsi_synccache_test.go (NEW, 2 tests)
SYNC_CACHE(10/16) no-op Good + backend NOT invoked
core/frontend/iscsi/scsi_batch10_5_test.go (NEW, 10 tests)
VPD 0x00 advertised list == {0x00, 0x80, 0x83} exactly
VPD 0x80 serial prefix
VPD 0x83 NAA-6 shape (designator header + high nibble 0x6)
VPD 0xB0 / 0xB2 / unknown → IllegalRequest
READ_CAPACITY(16) last-LBA + block size + LBPME
WRITE(16) → READ(16) round-trip
WRITE(16) / READ(16) LBA-out-of-range rejection
READ_CAPACITY(10) regression (dispatch changes didn't break it)
Tests green (no regressions):
core/frontend/iscsi: 96 tests (was 74; +22 Batch 10.5)
NVMe / T1 / memback / testback / host/volume: unchanged
Full regression 17.7s + 31.4s + 31.3s
Stop-rule audit vs decision doc §5.1 allowlist:
- In-allowlist: MODE_SENSE(6/10), SYNC_CACHE(10/16), VPD
0x00/0x80/0x83, READ_CAPACITY(16), READ(16), WRITE(16) ✓
- Pair-port extension per §3.1.a: MODE_SELECT(6/10),
START_STOP_UNIT (trivial no-op stubs paired with MODE_SENSE) ✓
- Not-ported per §3.2: UNMAP, WRITE_SAME, PERSISTENT_RESERVE,
ALUA, MAINTENANCE_IN, VPD 0xB0/0xB2, IsHealthy-gated TUR ✓
- No stale W/R semantic change
- No V2 storage / authority / retry coupling introduced
- `core/frontend/iscsi` still does not import `core/authority`
or `core/adapter` (AST guard remains green)
V2 Depth Debt appendix (for eventual closure report):
- SYNC_CACHE no-op: T3 handoff — when durable backend lands,
call frontend.Backend.Sync() equivalent (interface extension
needed)
- VPD 0xB0 / 0xB2 rejected: T3 (Block Limits) / T3+ (Logical
Block Provisioning) depending on durable backend feature set
QA Owner A-tier Phase 3 tests (separate, QA-authored file):
- TestT2V2Port_SCSI_InquiryVPD00_AdvertisesOnlyImplemented
(strict advertised-list match, §3.3 N3 guard)
- TestT2V2Port_SCSI_InquiryVPD83_NAADerivationDeterministic
(same-VolumeID determinism + different-VolumeID collision guard,
§3.3 N1 guard)
To be authored by QA Owner in
core/frontend/iscsi/t2_v2port_scsi_inquiry_test.go per plan §4.
|
||
|
|
239f8e52bc |
T2 ckpt 10 follow-up: EDTL/CDB pre-flight + strict R2T TTT
Architect review findings 2026-04-21 (ckpt 10 Medium): #1 EDTL trusted before CDB validation (memory amplification) collectWriteData allocated make([]byte, edtl) and issued R2T for the full EDTL before SCSIHandler ran the CDB's transfer- length check. A hostile peer could advertise a huge EDTL on a tiny WRITE(10) CDB to force an outsized buffer + R2T + Data-Out collection before rejection. Fix in session.handleSCSICmd: compute the CDB-authoritative expected byte count (cdbExpectedWriteBytes for WRITE(10)) BEFORE entering collectWriteData. Mismatched EDTL returns CHECK CONDITION + SenseIllegalRequest + ASCInvalidFieldInCDB without any allocation or R2T. Unrecognized write opcodes fall through to the handler's own validation path. #2 R2T-solicited Data-Out accepted TTT=0xFFFFFFFF collectWriteData had `|| pdu.TTT != 0xFFFFFFFF` exception that silently admitted the unsolicited marker after the target had issued an explicit R2T with TTT=1. Weakened the InitialR2T=Yes "solicited-only" discipline. Fix in collectWriteData: remove the 0xFFFFFFFF exception. Data-Out MUST echo the R2T's TTT exactly. Comment updated to explain why. Low: narrowed the read-side comment on sendDataInWithStatus / handleSCSICmd to reflect the actual T2 ckpt 10 scope (single Data-In PDU with S-bit; read splitting deferred until an OS initiator exposes the need). core/frontend/iscsi/t2_ckpt10_hardening_test.go (NEW, sw regression) TestT2Route_ISCSI_LargeWrite_EDTLCDBMismatch_RejectsWithoutAllocating: Builds a SCSI-Cmd with WRITE(10) transferLen=1 (512 B) but EDTL=128 MiB. Asserts: - Target reply opcode != R2T (no R2T issued) - Target reply opcode == SCSI-Response with CHECK CONDITION - Sense key == IllegalRequest; ASC == InvalidFieldInCDB - Round-trip fits within 2s (no 128 MiB allocation attempt) - Backend.Write invocation count == 0 (pre-flight reject never reaches the handler) Uses a custom countingBackend wrapping RecordingBackend to pin the "backend never invoked" invariant. TestT2Route_ISCSI_LargeWrite_WrongTTT_OnDataOut_Rejected: 4-block write; 1 block immediate, 3 blocks solicited. Reads the R2T, then sends Data-Out with TTT=0xFFFFFFFF (the unsolicited marker) instead of echoing the R2T's TTT. Asserts: - Next read from the client side surfaces an error (target closed the session) - Backend WriteCount == 0 Pins the stop-rule: no silent weakening of the negotiated solicited-only discipline. Tests green (no regressions): core/frontend/iscsi: 74 tests (was 72; +2 hardening regressions) All other packages: unchanged. Stop-rule audit: fixes stay inside ckpt 9/10 allowlist. No new auth/digest/storage/authority paths, no stale W/R semantics weakened. Not addressed in this commit (documentation drift, QA-owned): - The QA audit file header on t2_v2port_qa_test.go still claims V3 "does not implement R2T" which became stale after ckpt 10. sw cannot modify a QA-owned file without Discovery Bridge — flagged to QA Owner for header update. |
||
|
|
5115cfc554 |
T2 checkpoint 10: iSCSI multi-PDU R2T — large-write path
Per T2 assignment §4.3 ckpt 9/10 allowlist: "Multi-PDU R2T /
large write support" — port smallest required R2T path, keep
writes routed through frontend.Backend.Write.
Why now, ahead of actual iscsiadm failure on m01: the R2T path
is mechanical and well-understood. Writes > FirstBurstLength
(default 64 KiB) are the common large-write case iscsiadm will
drive. Porting now removes an m01 blocker without expanding
scope beyond the allowlist. Stop-rule audit below confirms no
overreach.
core/frontend/iscsi/session.go
handleSCSICmd now handles three write shapes:
- No write (FlagW off or EDTL=0): metadata / read path
unchanged; dataOut = req.DataSegment (typically empty).
- Immediate-only write (EDTL <= len(immediate data)): fast
path, no R2T.
- Solicited write (EDTL > len(immediate)): target emits ONE
R2T covering the remainder; collects Data-Out PDU(s)
with strict DataSN + BufferOffset ordering; dispatches
the assembled payload as ONE Backend.Write call.
New collectWriteData() enforces V2's correctness invariants:
- DataSN sequential (no out-of-order)
- BufferOffset matches cumulative received
- Data-Out TTT matches R2T TTT (or 0xFFFFFFFF unsolicited
is rejected since we negotiate InitialR2T=Yes)
- F-bit only valid when received == EDTL
- Overflow past EDTL rejected with clear error
Stop-rule observance (§4.3): stale-lineage semantics UNCHANGED.
A stale backend's write error surfaces AFTER R2T assembly
completes, as CHECK CONDITION — never as silent ACK because
the R2T sequence ran cleanly. This is pinned by
TestT2Route_ISCSI_LargeWrite_OnStaleBackend_RejectsAfterR2T.
T2 scope: single R2T for all remaining bytes (no MaxBurst
chunking). V2 supports multi-R2T per MaxBurstLength — we'll
port that ONLY if iscsiadm on m01 actually exposes the need.
core/frontend/iscsi/client_support_test.go
scsiCmdFull() is the new extended form: EDTL = len(immediate)
+ len(solicited). When the target emits R2T, the client feeds
the solicited bytes via one Data-Out PDU matching the R2T's
offset/length. Simpler legacy scsiCmd() is now a thin wrapper
that passes nil for solicited (preserves ckpt 4 call sites).
core/frontend/iscsi/t2_large_write_test.go (NEW, sw regression)
3 tests:
- TestT2Route_ISCSI_LargeWrite_R2TPath_Component:
16-block (8 KiB) write with only 4 blocks (2 KiB) immediate.
Target emits R2T; client feeds the other 12 blocks via
Data-Out. Asserts: exactly 1 Backend.Write, offset 0,
bytes exactly match a deterministic (i % 251) payload.
READ(10) round-trip verifies data landed at correct LBA.
- TestT2Route_ISCSI_LargeWrite_OnStaleBackend_RejectsAfterR2T:
stale backend + large write. R2T sequence still runs
(protocol correctness) but SCSI-Response is CHECK
CONDITION. Pins the stop-rule: R2T completion is NOT
commit authorization.
- TestT2Route_ISCSI_ImmediateOnlyWrite_StillWorks:
regression guard — 1-block immediate-only writes bypass
R2T as before. WriteCount=1, status Good.
Tests green (no regressions):
core/frontend/iscsi: 68 tests (was 65; +3 ckpt 10)
All other packages: unchanged.
Stop-rule audit (§4.3):
- Inside allowlist: multi-PDU R2T for writes ✓
- Did NOT port: V2 dataio.go multi-PDU Data-In splitting
(read-side chunking is separate from R2T; not an allowlist
item; not needed until an OS initiator exposes it)
- Did NOT weaken stale W/R semantics
- Did NOT introduce V2 authority / storage / WAL / retry paths
- Did NOT introduce MaxBurst chunking (smallest-required)
Sign-off tier: T2A-iSCSI-provisional unchanged. Ckpt 10 is
preparatory; product-ready promotion still gated on L2-OS
critical cells (i2/i3) on m01.
|
||
|
|
33821f7a9f |
T2 ckpt 9 follow-up: Discovery no longer gated on backend readiness
Architect residual-risk note (round-9 review): iSCSI Target
opened the frontend.Backend at accept time, before login. Any
connection — including Discovery — blocked on Provider.Open's
ErrNotReady wait, so `iscsiadm -m discovery` against a
not-yet-Healthy volume would hang instead of returning
SendTargets. Called out as a future m01 compat risk, not a
reject, but small enough to close now.
Fix:
- Target.handleConn no longer opens the backend. It hands
Provider + VolumeID + HandlerConfig to newSession and
lets the session decide.
- Session.serve does login FIRST. After login:
Discovery session → skip backend open entirely;
serve Text/Logout/NOP-Out only.
Normal session → call Provider.Open; a failure (e.g.
ErrNotReady) closes the session
cleanly after login rather than
blocking at accept.
- Target shutdown watcher now cancels the session ctx in
addition to closing the conn — required so a Provider.Open
that only wakes on ctx.Done can unblock during
Target.Close (avoids shutdown deadlock in the
never-ready regression test).
core/frontend/iscsi/session.go
Session now carries provider + volumeID + hcfg + backend.
serve(): loginPhase → (SessionType==Normal ? Provider.Open
+ build SCSIHandler : skip) → fullFeatureLoop. close()
also closes the opened backend.
core/frontend/iscsi/target.go
handleConn hands provider/volumeID/hcfg to newSession;
shutdown watcher cancels ctx so blocked Open unblocks.
core/frontend/iscsi/discovery_without_backend_test.go (NEW)
Two regression tests:
- TestT2Route_ISCSI_DiscoveryDoesNotDependOnBackendReady:
target bound to a neverReadyProvider (Open blocks
forever until ctx done); Discovery session completes
login + SendTargets + assertion within 5s. Asserts
Provider.Open was called ZERO times during Discovery.
- TestT2Route_ISCSI_NormalSessionClosesWhenProviderNotReady:
Normal-session login completes within 2s even though
Open blocks indefinitely — proves login isn't gated
on backend readiness.
Tests green (no regressions):
core/frontend/iscsi: 56 tests (was 54; +2 residual-risk regs)
All other packages: unchanged.
Stop-rule audit: fix is mechanism-level, stays inside the ckpt 9
allowlist (no new auth / digest / storage / authority paths).
Signs-off tier unchanged (T2A-iSCSI-provisional).
|
||
|
|
0d81c9bafc |
T2 checkpoint 9: iSCSI parameter negotiation + digest=None + SendTargets discovery
V2 mechanism port per assignment §4.3 ckpt 9 allowlist. Three
allowed mechanisms ported; nothing outside the allowlist is
introduced. The port discipline (mechanism-only, no V2 authority/
storage/auth) is preserved.
Why now: enables `iscsiadm -m discovery -t sendtargets` and a
real `iscsiadm -m node --login` to interoperate with the T2
target. L2-OS work on m01 (ckpt 11+) needs both; doing the port
once here keeps the ckpt-driven scope tight per the rule "port
the smallest required mechanism, not the directory".
Ports landed (all from weed/storage/blockvol/iscsi/):
core/frontend/iscsi/params.go (NEW)
Text key=value parser/encoder + numeric/boolean negotiation
helpers (RFC 7143 §6 + §13). CHAP helpers from V2 NOT ported
— auth is T8.
core/frontend/iscsi/login.go (REWROTE the minimal stub)
Full LoginNegotiator state machine: SecurityNeg → LoginOp →
FullFeature with parameter exchange. NegotiableConfig captures
the per-target profile (MaxRecv, MaxBurst, FirstBurst, R2T,
ImmediateData, etc.) with DefaultNegotiableConfig() matching
V2 sane defaults for Linux open-iscsi compat.
Identity capture (InitiatorName/SessionType/TargetName);
Normal sessions resolve TargetName via TargetResolver;
Discovery sessions skip the resolver check per spec.
Digest negotiation answers "None" for HeaderDigest /
DataDigest (T2 explicitly does not implement digest verify;
closure report won't claim digest security).
core/frontend/iscsi/discovery.go (NEW)
HandleTextRequest implements SendTargets. Multi-value
TargetName/TargetAddress encoding (the discovery exception to
Params duplicate-key rule). TargetLister interface for the
session to pull a live target list at request time.
core/frontend/iscsi/session.go (MOD)
loginPhase replaced its 1-shot "buildLoginResponse" with the
real negotiator loop (multi-round support). dispatch handles
OpTextReq via HandleTextRequest. Discovery sessions reject
SCSI commands (RFC 7143 §6.2). Session struct now carries
NegotiableConfig + TargetResolver + TargetLister via newSession.
core/frontend/iscsi/target.go (MOD)
TargetConfig: added IQN (now load-bearing — the resolver
requires it for Normal-session login), PortalAddr (operator
override for SendTargets advertised address), Negotiation.
Target satisfies TargetResolver (HasTarget(name)==name==IQN)
and TargetLister (single-target list).
core/frontend/iscsi/client_support_test.go (MOD)
Test client now sends InitiatorName/SessionType/TargetName +
digest negotiation params on login (the negotiator now
enforces V2-compatible required fields). loginOptions struct
lets tests opt into Discovery sessions or non-default identity.
NEW tests (sw-owned regression):
params_test.go 10 tests:
- encode/parse roundtrip preserves order
- parse rejects malformed / empty key / duplicate key
- parse skips trailing nul
- Set replaces existing key in place
- NegotiateNumber min(offered, ours) + clamp + non-numeric reject
- NegotiateBool AND semantics + invalid value
- BoolStr Yes/No
login_test.go 7 tests:
- DirectLoginOpToFullFeature: V2 "skip security" path used by
our test client; identity captured, digests echoed None,
TargetPortalGroupTag present (RFC 7143 §13.9).
- MultiRound_SecurityThenLoginOp: 3-round flow that iscsiadm
uses by default.
- DiscoverySession_NoTargetCheck: Discovery skips resolver.
- RejectMissingInitiatorName: status 0x02 detail 0x07.
- RejectUnknownTargetName: status 0x02 detail 0x03 (NotFound).
- OperationalNegotiation: MaxBurst min, FirstBurst min,
InitialR2T OR semantics.
- UnknownKey_NotUnderstood per RFC.
discovery_test.go 5 tests:
- EncodeDiscoveryTargets: 1 target, empty, omits empty Address.
- HandleTextRequest: SendTargets All / by-name / no key.
- TestT2Route_ISCSI_SendTargetsDiscovery: real in-process
Discovery session over wire — login as Discovery, send
SendTargets=All, verify TargetName + TargetAddress
(loopback + portal-group tag) come back. iscsiadm-shaped
end-to-end on the protocol layer (no OS initiator yet).
Tests green (no regressions):
core/frontend/iscsi: 54 tests (was 31; +23 ckpt 9)
core/frontend/nvme: unchanged (26)
All other packages: unchanged.
Sign-off impact: T2A-iSCSI-provisional unchanged. Ckpt 9 is
preparation for L2-OS work; product-ready promotion remains
gated on L2-OS critical cells (i2/i3) running on m01.
Stop rule observed (§4.3): no port outside the allowlist;
no stale-path semantics weakening; no V2 authority/storage
introduction.
|
||
|
|
e00d725cb5 |
T2 ckpt 8 follow-up: enforce --nvme-ns + --nvme-subsysnqn on the wire
Two architect-review findings (round-7) closed:
Finding 1: --nvme-ns was a dead flag.
cmd/blockvolume accepted --nvme-ns N but built TargetConfig with
zero-value Handler, so the IOHandler always defaulted to NSID=1.
An operator running --nvme-ns 7 got a target that still rejected
every command targeting NSID=7.
Fix (cmd/blockvolume/main.go):
Handler: nvme.HandlerConfig{NSID: uint32(f.nvmeNS)}
threaded through TargetConfig so the configured value reaches
the per-session handler.
Finding 2: --nvme-subsysnqn was advertised but not enforced.
Target.SubsysNQN was metadata-only; the wire-level Fabric Connect
accepted any host's SubNQN. A host could connect with an
arbitrary subsystem name and still get IO service — multi-target
routing and operator intent ambiguous.
Fix (core/frontend/nvme/session.go + target.go + errors.go):
- Session.expectedSubNQN field, plumbed via newSession().
- Target.handleConn passes t.cfg.SubsysNQN into newSession.
- handleFabric rejects mismatched SubNQN with
SCT=Command Specific (1) + SC=ConnectInvalidParameters (0x80)
per NVMe-oF spec §3.3.1. New SC constants in errors.go:
SCConnectInvalidParameters / SCConnectControllerBusy /
SCConnectInvalidHost.
- Empty Session.expectedSubNQN preserves "no enforcement"
contract for in-process L1 tests that don't pin a subsystem
identity. cmd/blockvolume always sets SubsysNQN (already
required at startup), so production is always enforced.
core/frontend/nvme/identity_enforcement_test.go (NEW, sw regression)
4 tests pin both fixes:
- TestT2NVMe_HandlerHonorsConfiguredNSID:
handler-level — IOHandler with NSID=7 rejects NSID=1
commands with Generic/InvalidField, backend not invoked.
- TestT2Process_NVMe_TargetHandlerNSIDConfigPropagates:
wire-level — Target with HandlerConfig.NSID=7 rejects
client Write at NSID=1; status decode confirms wire bits
SCT=0 SC=0x02. Backend not invoked.
- TestT2Process_NVMe_ConnectWithWrongSubNQN_Rejected:
low-level capsule write with wrong SubNQN; assert
wire status SCT=1 SC=0x80 (ConnectInvalidParameters).
- TestT2NVMe_EmptySubsysNQN_AcceptsAnyConnect:
regression for the in-process L1 path — empty target
SubsysNQN admits any Connect (preserves L1 test setup).
Tests green (no regressions):
core/frontend/nvme: 26 tests (was 22; +4 enforcement regressions)
All other packages: unchanged.
Sign-off impact: T2B-NVMe-provisional unchanged (still QA + sw lead);
follow-up tightens identity wiring per architect feedback before
T2-closed L2-OS work begins.
|
||
|
|
ee12558f58 |
T2 checkpoint 8: cmd/blockvolume --nvme-* wiring + NVMe L2-harness green
cmd/blockvolume/main.go
New flags symmetric with iSCSI:
--nvme-listen <addr> (loopback-only bind enforced;
empty disables)
--nvme-subsysnqn <nqn> (required when --nvme-listen set)
--nvme-ns <id> (default 1)
When --nvme-listen is set:
- implicitly auto-enables --t1-readiness with same stderr
notice ("blockvolume: nvme enabled: t1-readiness auto-enabled")
→ kept symmetric with iSCSI per QA checkpoint-7 note;
closure report doesn't have to explain asymmetry.
- constructs memback.NewProvider wrapping the volume's
AdapterProjectionView (same readiness bridge as iSCSI;
sketch §10 "Readiness bridge shared, not duplicated").
- emits nvme-listening JSON ready line with nvme_addr + subsys_nqn.
Refactored enforceIscsiLoopbackBind → enforceFrontendLoopbackBind
(parameterized on kind="iscsi"|"nvme") so both protocols use
one guard. Identical loopback-only safety policy.
core/frontend/nvme/t2_l2_nvme_harness_test.go (QA-owned, test-spec §6)
// T2 L2 EVIDENCE CLASS: L2-harness
T2.L2.n1 TestT2Process_NVMe_AttachWriteRead (13.6s):
real blockmaster + blockvolume subprocesses with
--nvme-listen on a reserved loopback port; Go NVMe/TCP
initiator does ICReq → fabric Connect → Write 512B at LBA
0 → Read at same location, bytes match over real wire
(capsule + R2T + H2CData + C2HData round trip).
T2.L2.n4 TestT2Process_NVMe_ReopenAfterMove_ServesNewLineage (17.2s):
same harness; pre-move Connect+Write+disconnect, then primary
volume restarts with new data/ctrl addrs (same status+nvme
addrs). Master mints IntentRefreshEndpoint → EV advances.
Fresh Connect to the same NVMe addr gets a backend at the
new lineage and Write+Read round-trip succeed. Explicit
NON-CLAIM: pre-move bytes not expected to persist.
NOT included per checkpoint-5 scope (C5.3 applied to NVMe):
T2.L2.n2 / n3 (stale Write / Read after move). L2-OS REQUIRED
critical cells; harness can't substitute for kernel ANA
Transition handling. Tracked for L2-OS on m01.
Tests green (no regressions):
core/frontend/nvme: 22 tests (errors 7 + boundary 1 + io 9 +
L1 route 3 + L2-harness 2)
core/frontend/iscsi: 31 unchanged
All other packages: unchanged.
Sign-off tier: T2B-NVMe-provisional
Acceptance:
- L0 6/6 green (n1-n6)
- L1 3/3 green (n1-n3 component route)
- L2-harness 2/2 green (n1 + n4)
- cmd/blockvolume --nvme-* product-host wiring landed
- loopback default + NQN required match T2 safe defaults
- i2 stale Write / i3 stale Read deferred to L2-OS
Sign-off: QA Owner + sw lead (§8B.9 provisional tier)
Downstream unlock: none; T2A-iSCSI-product-ready and
T2B-NVMe-product-ready remain L2-OS work
(m01 enablement).
|
||
|
|
af31cf7785 |
T2 checkpoint 7: NVMe/TCP capsule + fabric Connect + session + L1 route green
core/frontend/nvme/protocol.go (NEW)
Wire types ported from V2: CommonHeader (8B), ICReq/ICResp
(120B body), CapsuleCommand (64B specific header), CapsuleResponse
(16B / NVMe CQE), C2HDataHeader, R2THeader, H2CDataHeader (16B
each), ConnectData (1024B). MakeStatusField helper packs SCT+SC
+DNR into CQE status word per NVMe base spec §4.6.1. Byte-for-
byte the V2 wire shape so a future merge / shared client is
trivial.
core/frontend/nvme/wire.go (NEW)
Reader/Writer for NVMe/TCP PDU streams, ported from V2 with
the bounds-validation invariants intact (HeaderLength,
DataOffset, DataLength sanity — defends against malformed
PDUs from a hostile peer).
core/frontend/nvme/session.go (NEW)
T2-minimal NVMe controller: one Session per TCP connection.
Sequence:
1. ICReq -> ICResp (TCP transport handshake, accept whatever
PDUFormatVersion the host sent)
2. Fabric Connect (CapsuleCmd OpCode=0x7F FCType=0x01)
accepted for any HostNQN/SubNQN — auth is T8.
3. IO dispatch:
Read : CapsuleCmd -> C2HData (with Last flag) -> CapsuleResp
Write : CapsuleCmd -> R2T -> wait for H2CData -> CapsuleResp
Flush : CapsuleCmd -> CapsuleResp Success
4. Errors from frontend.Backend map via the IOHandler:
ErrStalePrimary -> ANA Transition (SCT=3 SC=3) DNR=1
ErrBackendClosed -> ANA Inaccessible (SCT=3 SC=2) DNR=1
Invalid input -> SCT=0 + caller SC
Production extras (Identify / Get Log Page / Set Features /
Async Event Reports / Keep Alive / digests) intentionally
out of scope; land with L2-OS enablement.
core/frontend/nvme/target.go (NEW)
TCP listener + accept loop. Symmetric with iscsi/target.go:
Provider.Open per session, IOHandler bound to that backend,
graceful drain on Close.
core/frontend/nvme/client_support_test.go (sw test-support)
Minimal Go NVMe/TCP initiator: dialAndConnect (ICReq +
fabric Connect), readCmd (Read + C2HData receive),
writeCmd (Write + R2T + H2CData), recvCapsuleResp.
expectStatusANATransition decodes the wire SCT/SC tuple
to assert (3, 3) regardless of DNR bit.
core/frontend/nvme/t2_route_nvme_test.go (QA-owned, test-spec §5)
T2.L1.n1 TestT2Route_NVMe_AttachWriteRead_Component:
real wire round-trip (TCP + capsule + R2T/H2CData/C2HData);
backend sees one Write at exact offset/data; Read returns
same bytes.
T2.L1.n2 TestT2Route_NVMe_EndpointVersionMove_RejectsOldWrite:
swap to StaleRejectingBackend; fresh Connect's Write returns
SCT=3 SC=3 (ANA Transition).
T2.L1.n3 TestT2Route_NVMe_EndpointVersionMove_RejectsOldRead:
populate known "secret" bytes, swap to stale, fresh Read
returns ANA Transition AND zero leak of the known bytes
to initiator.
Tests green (no regressions):
core/frontend/nvme: 20 tests (errors 7 + boundary 1 + io 9 + L1 route 3)
core/frontend/iscsi: 31 unchanged
All other packages: unchanged.
Sign-off tier: T2B-NVMe checkpoint 7 (L1 component route green).
T2B-NVMe-provisional pending L2-harness (checkpoint 8).
|
||
|
|
28e9636edb |
T2 checkpoint 6: NVMe/TCP minimal slice — L0 green + boundary guard
Checkpoint 6 mirrors iSCSI checkpoints 1+2 for the NVMe/TCP
protocol. L1/L2 for NVMe come in later checkpoints.
cmd/blockvolume/main.go
Small follow-up on T2A-iSCSI-provisional sign-off note:
emit a stderr line "iscsi enabled: t1-readiness auto-enabled"
when --iscsi-listen implicitly flips the readiness bridge on.
Keeps operators from misreading the auto-enable as silent.
core/frontend/nvme/errors.go (NEW)
NVMe status vocabulary for T2:
SCT types (Generic, CommandSpecific, MediaDataInteg, PathRelated,
VendorSpecific)
Generic SCs: Success, InvalidOpcode, InvalidField, InternalError,
LBAOutOfRange, CapacityExceeded, NamespaceNotReady.
PathRelated SCs: ANA PersistLoss / Inaccessible / Transition.
StatusError type carrying (SCT, SC, Reason) with Error() and
EncodeStatusField() that packs SCT/SC into the 16-bit CQE
status field (SC<<1 | SCT<<9 per NVMe base spec §4.6.1).
Canonical constructors:
NewStaleLineage() -> SCT=3 (PathRelated) + SC=0x03 (ANA Transition)
— semantic match for authority-move
transition; Linux nvme driver treats this
as a path-retry condition.
NewBackendClosed() -> SCT=3 + SC=0x02 (ANA Inaccessible)
— distinct from stale-lineage so logs
disambiguate the two fail modes.
NewInvalidField(sc, reason) -> SCT=0 + caller SC.
Symmetric with iscsi/errors.go's ALUA 0x04/0x0A vs 0x04/0x00
distinction (see earlier checkpoint 2 note).
core/frontend/nvme/io.go (NEW)
IOHandler dispatches NVMe IO Read/Write/Flush to a
frontend.Backend. Opcode set intentionally minimal for L0 scope;
Identify / SetFeatures / fabric admin land with capsule framing
in a later checkpoint.
IOCommand is the normalized form (Opcode, NSID, SLBA, NLB, Data).
IOResult.AsError() returns nil on Success or a *StatusError.
mapBackendError: ErrStalePrimary -> ANA Transition;
ErrBackendClosed -> ANA Inaccessible;
other -> Internal Error (fail-closed).
LBA-range + NSID + short-data validation BEFORE backend call
(fail closed). NLB=0 is invalid in our one-based form (zero-based
on wire, one-based in IOCommand for readability).
core/frontend/nvme/io_test.go (QA-owned, test-spec §4 n1..n4)
T2.L0.n1 CommandReadWrite_UsesFrontendBackend: Read + Write
route through RecordingBackend, single invocation, exact
offset + data.
T2.L0.n2 StaleWrite_ReturnsProtocolFailure: non-Success,
SCT=3 SC=3 (ANA Transition).
T2.L0.n3 StaleRead_ReturnsProtocolFailure: non-Success,
zero data bytes (MUST NOT leak stale bytes), ANA Transition.
T2.L0.n4 InvalidInput_FailsClosed: table-driven — LBA past
end, LBA overflow, short data, NLB=0, unknown NSID. Each
fails at handler, backend never invoked.
Plus sw-added regressions:
BackendClosed_DistinctFromStale pins the ANA Transition vs
ANA Inaccessible distinction.
UnknownOpcode_ReturnsInvalidOpcode (fail-closed on 0x7f).
Flush_SuccessInT2Scope (no-op).
IOResult.AsError_NilOnSuccess + SupportsErrorsAs.
core/frontend/nvme/boundary_guard_test.go (QA-owned, test-spec n5+n6)
T2.L0.n5 + n6 AST guard: full-parse + alias-resolution (same
shape as iSCSI's boundary guard). Extends PCDD-STUFFING-001
coverage to core/frontend/nvme. No core/authority, no
core/adapter, no authority-minting composite literal, no
dot-import bypass.
Tests green (no regressions):
core/frontend/nvme: 17 tests (errors 7 + boundary 1 + io 9)
core/frontend/iscsi: unchanged (31)
All other packages: unchanged.
Sign-off tier: T2B-NVMe checkpoint 6 (L0 foundation). L1 + L2
arrive in checkpoints 7-8; T2B-NVMe-provisional pending L2-harness
(checkpoint 8).
|
||
|
|
15e049d79a |
T2 checkpoint 5: cmd/blockvolume --iscsi-* wiring + L2-harness green
cmd/blockvolume/main.go
New flags per assignment §3.2:
--iscsi-listen <addr> (empty disables; loopback-only bind
enforced at startup per C5.4
"Defaults must be safe")
--iscsi-iqn <iqn> (required when --iscsi-listen set)
--iscsi-lun <id> (default 0)
When --iscsi-listen is set:
- implicitly auto-enables --t1-readiness (iSCSI needs a
Healthy adapter projection to open a memback backend)
- enforces loopback bind (mirrors StatusServer's guard;
non-loopback or empty-host addrs rejected with clear
error). T2 iSCSI is unauthenticated — real-NIC binds
land with T8 security.
- constructs memback.NewProvider wrapping the volume host's
AdapterProjectionView, then iscsi.NewTarget on that
provider. Per-op lineage fence + supersede fence still
apply at SCSI command granularity.
- emits iscsi-listening JSON ready line with iscsi_addr
and iqn (same pattern as status-listening).
core/frontend/iscsi/t2_l2_iscsi_harness_test.go (QA-owned, test-spec §6)
// T2 L2 EVIDENCE CLASS: L2-harness
T2.L2.i1 TestT2Process_ISCSI_AttachWriteRead (13.5s):
real blockmaster + blockvolume subprocesses with
--iscsi-listen on a reserved loopback port; Go initiator
logs in, WRITE(10) 512 bytes at LBA 0, READ(10) at same
location returns identical bytes over real TCP+PDU framing.
T2.L2.i4 TestT2Process_ISCSI_ReopenAfterMove_ServesNewLineage (17.2s):
same harness; pre-move session writes then logs out; primary
volume restarts with new data/ctrl addrs (same status+iscsi
addrs). Master mints IntentRefreshEndpoint → EndpointVersion
advances. Fresh login on the same iSCSI addr serves the new
lineage (post-move WRITE + READ round-trip succeed under
the new Identity). Explicit NON-CLAIM: pre-move bytes not
expected to persist (memback is Identity-scoped; G8
territory).
NOT included per checkpoint-5 scope (C5.3): stale WRITE / READ
after move. Those are L2-OS REQUIRED critical cells; running
them at L2-harness would be a spec violation (§G3 initiator-
evidence rule + test-spec §6 L2-OS requirement). Tracked for
L2-OS on m01.
Tests green (no regressions):
core/frontend/iscsi: 31 tests (prior 29 + L2.i1 + L2.i4 L2-harness)
core/frontend, memback, testback, host/volume: unchanged.
Sign-off tier: T2A-iSCSI-provisional
(QA Owner + sw lead; per §8B.9).
L2-OS → product-ready → architect+PM sign is a later checkpoint.
NVMe/TCP slice (checkpoint 6) may now proceed in parallel.
|
||
|
|
32f378f1f7 |
T2 checkpoint 4: iSCSI login + session + target + L1 route green
core/frontend/iscsi/login.go
Minimal T2-scope login negotiator — accepts any Login-Request
with Transit=true + NSG=FullFeature and responds with Success.
No text-parameter negotiation, no CHAP, no digest. Sufficient
for L1 in-process component route; OS-initiator compat
(MaxRecv, digests, CHAP) is L2-OS scope.
core/frontend/iscsi/session.go
One goroutine per TCP connection. Serial rx/tx (no txLoop
split): login phase → full-feature dispatch. SCSI-Cmd PDUs
carry immediate data for WRITE (ImmediateData=true); READ
responses ride in a single Data-In with the S-bit set so the
status conveys with the data. CHECK CONDITION responses put
fixed-format sense data in the SCSI-Response data segment.
Logout + NOP-Out handled; other opcodes rejected.
core/frontend/iscsi/target.go
TCP listener + accept loop. On each accept, calls
frontend.Provider.Open to get the session's backend, then
builds an SCSIHandler bound to that backend. Close drains
active sessions.
core/frontend/iscsi/client_support_test.go (sw test-support)
Tiny Go initiator used by the L1 route tests: dialAndLogin,
scsiCmd (WRITE/READ/metadata), logout. Covers exactly what
L1 needs — not a general initiator.
core/frontend/iscsi/t2_route_iscsi_test.go (QA-owned, test-spec §5)
T2.L1.i1 TestT2Route_ISCSI_AttachWriteRead_Component:
in-process target + RecordingBackend — WRITE(10) routes
payload to backend exactly once; READ(10) returns the same
bytes over real TCP+PDU framing.
T2.L1.i2 TestT2Route_ISCSI_EndpointVersionMove_RejectsOldWrite:
swap provider to StaleRejectingBackend mid-flight; re-login
session's WRITE returns CHECK CONDITION, never success.
T2.L1.i3 TestT2Route_ISCSI_EndpointVersionMove_RejectsOldRead:
populate backend with known "secret" bytes, swap to stale,
re-login + READ — stale path returns CHECK CONDITION AND
bytes do NOT leak to initiator.
Tests green:
core/frontend/iscsi: 29 tests (errors 4 + guard 1 + scsi 11 +
pdu 10 + L1 route 3)
core/frontend, memback, testback, host/volume: unchanged.
Remaining for T2-closed: cmd/blockvolume --iscsi-* wiring, L2-harness,
NVMe/TCP symmetric slice, L2-OS enablement on m01.
|
||
|
|
96d80e339e |
T2 checkpoint 3: iSCSI PDU framing ported from V2
core/frontend/iscsi/pdu.go
Port of weed/storage/blockvol/iscsi/pdu.go byte-for-byte on
the wire format. Constants (opcodes, flags, login stages,
MaxDataSegmentLength, AHS / data-segment padding rules) are
preserved. SCSI status byte constants that V2 duplicated into
pdu.go are NOT repeated here — they live in errors.go / scsi.go
for this port so there's a single source of truth.
Also renamed the two SCSI Response PDU helpers that collided
with our SCSI-layer terminology:
SCSIStatus() -> SCSIStatusByte()
SetSCSIStatus -> SetSCSIStatusByte
(SCSIStatus[Byte] here is the byte 3 field of an OpSCSIResp
PDU, not the handler-layer enum in scsi.go.)
core/frontend/iscsi/pdu_test.go (sw-owned)
Regression coverage for the wire layer:
- BHS-only roundtrip (opcode, immediate, LUN, ITT, CmdSN, CDB)
- Data segment roundtrip with 4-byte padding (5-byte payload
round-trips through 8-byte on-wire length)
- AHS roundtrip (multiple-of-4 contract)
- AHS non-multiple-of-4 rejected at WritePDU
- Truncated BHS -> ErrPDUTruncated
- Truncated data segment -> ErrPDUTruncated
- Oversized (>8 MiB) DSL -> rejected
- EOF on empty reader -> io.EOF (not wrapped)
- Login stage CSG/NSG + transit flag roundtrip
- OpcodeName covers all defined opcodes + unknown fallback
Session + target + login wiring still pending — next checkpoint
will compose PDU + SCSI handler into an in-process iSCSI target
for L1 route tests.
Tests green (no regressions):
core/frontend/iscsi: 26 tests (errors 4 + boundary 1 + scsi 11 +
pdu 10)
All other packages: unchanged.
|
||
|
|
903417846b |
T2 checkpoint 2: iSCSI SCSI handler + L0.i1/i2/i3/i4 green
core/frontend/iscsi/scsi.go
SCSIHandler adapting frontend.Backend to SCSI CDB dispatch.
Minimal opcode set for T2 L0: TEST_UNIT_READY, REQUEST_SENSE,
INQUIRY (standard, non-VPD), READ_CAPACITY(10), READ(10),
WRITE(10), REPORT_LUNS. Every READ/WRITE routes through
frontend.Backend.Read / .Write — the per-op lineage fence
fires exactly once per SCSI command.
mapBackendError maps frontend error values to SCSI status/sense:
ErrStalePrimary -> CHECK CONDITION + NOT READY +
ASC 0x04/ASCQ 0x0A (ALUA asymmetric access
state transition — matches lineage-move
semantics, distinct from generic not-ready)
ErrBackendClosed -> CHECK CONDITION + NOT READY +
ASC 0x04/ASCQ 0x00 (cause not reportable)
Distinct ASCQ so operators can tell stale-lineage and
closed/faulted apart in logs.
LBA-range and short-dataOut validation happens BEFORE the
backend call (fail closed). Zero-length transfer is a valid
no-op and does not touch the backend.
core/frontend/iscsi/errors.go
ASCStaleLineage/ASCQStaleLineage now pinned to SPC-5's
"asymmetric access state transition" pair (0x04/0x0A) for the
reason above. Single source of truth for the stale-lineage
wire mapping.
core/frontend/iscsi/scsi_test.go (QA-owned, test-spec §4)
T2.L0.i1 TestT2ISCSI_CommandReadWrite_UsesFrontendBackend:
WRITE(10) then READ(10) route through recording backend;
exact offset, exact data, single invocation each.
T2.L0.i2 TestT2ISCSI_StaleWrite_ReturnsCheckCondition:
stale WRITE -> non-Good, CHECK CONDITION, NotReady,
stale-lineage ASC; never silently ACKs success.
T2.L0.i3 TestT2ISCSI_StaleRead_ReturnsCheckCondition:
stale READ -> non-Good, zero data bytes, CHECK CONDITION;
never leaks stale bytes to initiator.
T2.L0.i4 TestT2ISCSI_InvalidInput_FailsClosed:
table-driven — LBA past end, LBA overflow window, short
dataOut. Each fails at the handler, backend never invoked.
Zero-length transfer verified as valid no-op.
Plus sw-added regressions:
- TestT2ISCSI_BackendClosed_MapsToNotReady pins the
stale-vs-closed ASCQ distinction so future refactors can't
collapse the two fail modes.
- TestT2ISCSI_MetadataCommands_SuccessForT2Subset covers
TUR/INQUIRY/READ CAPACITY/REPORT LUNS/REQUEST SENSE happy
path (initiator handshake won't blow up once PDU framing
lands).
- TestT2ISCSI_UnknownOpcode_ReturnsIllegalRequest ensures
unknown CDBs fail-closed and never reach the backend.
Scope: this checkpoint delivers handler-LEVEL coverage of the
four L0 T2.i* tests. Session-LEVEL API (Login/Session, wire
PDUs, TCP target) lands with PDU framing in the next checkpoint
— at which point L1 component tests (in-process target +
Provider) can run against real Go initiator code.
Tests green (no regressions):
core/frontend: T1 suite unchanged (18s incl. L2)
core/frontend/iscsi: 16 tests (errors 4 + guard 1 + scsi 11)
core/frontend/memback: 6
core/frontend/testback: 4
core/host/volume: prior volume suite
|
||
|
|
5d8d9d2502 |
T2 checkpoint 1: sw review ACCEPT, shared test doubles, iSCSI skeleton
Review: T2 test spec ACCEPT per §8B.3 — no blockers; notes routed
to QA Owner (L2-OS env = m01; shared bridge = no generalization
needed; V2 port audit produced during porting).
This checkpoint lands the T2 foundation without any wire-protocol
code yet:
core/frontend/testback/ (NEW, sw-owned)
Shared test doubles for both iSCSI and NVMe suites:
- StaticProvider: returns a preconfigured frontend.Backend on every Open
- RecordingBackend: captures every Read/Write call (offset, data)
- StaleRejectingBackend: ErrStalePrimary on all I/O
4 unit tests pinning fake behavior so assertions don't silently drift.
core/frontend/iscsi/ (NEW, start of package)
- errors.go: SCSI status + sense constants, SCSIError type,
NewCheckConditionStaleLineage / NewCheckConditionIllegalRequest
constructors (single source for the stale-lineage mapping).
- errors_test.go: 4 L0 tests on the error shape.
- boundary_guard_test.go: T2.L0.i5 + i6 combined AST guard —
no core/authority import, no core/adapter import (T2 tightens
beyond T1 per sketch §3), no composite-literal minting, no
dot-import. Extends PCDD-STUFFING-001 coverage to iscsi pkg.
Not yet landed (planned, next sessions per review plan):
- PDU framing + login + session + target
- SCSI READ/WRITE dispatch to frontend.Backend
- L0.i1 CommandReadWrite + L0.i2 StaleWrite + L0.i3 StaleRead + L0.i4 InvalidInput
- L1 in-process route tests
- cmd/blockvolume --iscsi-* wiring + L2-harness
- NVMe/TCP symmetric slice
- L2-OS enablement on m01
Tests green:
core/frontend: 18s (T1 regression intact)
core/frontend/iscsi: errors 4 + boundary guard 1 = 5
core/frontend/memback: regression intact
core/frontend/testback: 4
|