mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-05 02:27:26 +01:00
11429ea3fb5fede26ece128c3ea17ff6ac2bc855
46
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
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
|
||
|
|
f5c557074d |
T1 product closure: readiness bridge + supersede fence + L2 authority move
Addresses three architect review rounds on T1 frontend contract:
Round 1 (L0/L1 only) → Round 2 (real adapter path + product loop):
- AdapterProjectionView reads engine.ReplicaProjection.Mode
(engine.ModeHealthy is the real readiness source, not
manufactured AssignmentInfo receipt)
- HealthyPathExecutor drives engine through Probe + Fence +
PublishHealthy so Mode actually reaches ModeHealthy
- cmd/blockvolume: --t1-readiness + --status-addr flags;
volume.StatusServer exposes frontend.Projection over HTTP
- memback negative offset: returns ErrInvalidOffset, no panic
- Boundary guard: full AST parse + alias resolution
Round 3 (cross-replica supersede + real authority move in L2):
- SupersedeProbe seam on AdapterProjectionView; Host.IsSuperseded
compares lastOther (replicaId, epoch, ev) vs self-lineage →
Healthy=false when another replica holds newer authority
- L2 now drives a product-route authority move: r1 restarts
with new data/ctrl addrs → master mints IntentRefreshEndpoint
→ EndpointVersion advances → old backend ErrStalePrimary →
fresh Open captures new lineage
- StatusServer restricted to loopback (bind + client check)
Round 4 (proof coverage + robustness):
- Real Host.recordOtherLine → IsSuperseded → View integration
test (no more stubProbe-only coverage for supersede claim)
- L2 closure claim sharpened: PROVES IntentRefreshEndpoint
stale reject; DOES NOT PROVE cross-replica primary change
(deferred to T6/G8)
- Reserve loopback port via :0 instead of hardcoded 7165
- Boundary guard: forbid dot-import of core/adapter and
core/authority (bare-literal bypass closed)
Tests (all green):
core/frontend L0: 7 + negative-offset regression + 3 meta
core/frontend L1: 1 (real adapter + AdapterProjectionView)
core/frontend L2: 1 (product route + authority move + stale
reject + new open, 17-21s)
core/host/volume: 4 AdapterProjectionView + 3 supersede
integration + 5 StatusServer loopback
Closure: INV-FRONTEND-001 / INV-FRONTEND-002 Unit+Component+
Integration; PCDD-STUFFING-001 Unit with dot-import guard.
Cross-replica primary-change facet explicitly remains
Unit/Component only (routed to G8/T6 for L2 promotion).
|
||
|
|
91371e5737 |
T1 frontend contract: core/frontend + memback + L0/L1 tests
Implements the frontend contract per T1 sketch §5-9: Identity,
Backend, Provider, ProjectionView types; ErrStalePrimary /
ErrNotReady / ErrBackendClosed sentinels; memback contract-smoke
backend that re-validates full lineage on every Read/Write.
Tests per QA test-spec:
L0 x7 (provider open healthy + not-ready, backend read/write,
stale read, stale write table-driven, close, boundary guard)
L1 x1 (Publisher + VolumeBridge publication route, Epoch-bump
move, old backend rejects, new backend serves post-move)
Two sw review notes for QA Owner:
- Spec samples use engine.ReplicaProjection{VolumeID, ReplicaID,
Healthy}. Actual engine type lacks those fields; per sketch §5
the frontend defines its own Projection struct. Documented in
file headers.
- Spec's T1.L1.1 asserts ReplicaID change across the move.
Cross-replica authorship requires TopologyController, not
StaticDirective. This L1 proves Epoch-drift fence (the fence's
actual invariant). ReplicaID-change coverage routed to L2
over the real product route.
L2 test (T1.L2.1) not written: BLOCKED-BY-T0 per test-spec §6 —
the T0 noop executor cannot produce a frontend-serving projection
until the T1-owned readiness bridge lands in cmd/blockvolume.
|
||
|
|
f26d03b47a | README: mark project under construction in title | ||
|
|
55793d49bc |
T0 closure: blockmaster/blockvolume hosting + D1-D5 tests
Product binaries (cmd/blockmaster, cmd/blockvolume) and core/host wiring for volume-scoped assignment delivery, durable authority with Windows rename retry, and the T0 closure test set (D1 L2 subprocess, D2 G1 adversarial, D3 concurrent write-reload regression, D4 hosting-smoke scenario + Go-native replay, D5 --topology flag). Diagnostic surfaces: ObservationStore.SupersededCount (PCDD-DELAYED-HB-001 evidence, not authority input) and SetNowForTest clock seam on Store/Host, guarded by grep test ensuring the identifier stays out of production files. |
||
|
|
c699d358b0 |
P14 cleanup: CodeRabbit nits on the S5-S8 PR
Three review follow-ups from PR #10 CodeRabbit feedback. All style/robustness; no correctness changes. 1. core/authority/authority.go — drop dead-scaffolding locals (prevForRollback / hadPrev) around the durable-write path. State mutation is deliberately sequenced after store.Put, so there is nothing to roll back on Put failure. Replace the phantom locals with a comment stating the invariant. 2. cmd/sparrow/s7_restart_smoke_test.go — use exec.CommandContext with a 60s test-level deadline for both the go build and the two subprocess runs, so a hung child dies when go test times out instead of lingering. 3. cmd/sparrow/s7_bootstrap_test.go — replace `dir + string(os.PathSeparator) + ...` with filepath.Join for cross-platform correctness. Not addressed (explicitly CodeRabbit-flagged "recommended not essential"): double-reload at boot (bootstrap.go). Would require a new Publisher WithPreloaded option; skipped to keep this commit tight and not reopen S5 surfaces. go test ./core/authority ./cmd/sparrow -count=1 green. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> |
||
|
|
5a902c15f4 |
P14 S8: IntentRefreshEndpoint L1 route test (evidence-matrix Claim 6)
Closes the S8 evidence-matrix gap for Claim 6 (controller-driven bind / reassign / refresh over accepted topology). Prior state had Bind / Reassign with dedicated L1 routes but refresh was only exercised at L0 via controller_test.go, covered implicitly by placement/rebalance/failover. This adds the explicit route. Scenario: heartbeats report slot DataAddr/CtrlAddr changing for the current authority while publisher still holds old addrs → decideVolume emits IntentRefreshEndpoint → publisher bumps EndpointVersion on the same Epoch → bridge delivers refreshed AssignmentInfo to the consumer → next rebuild confirms via the full contract (including addr match) and clears desired. Test file: core/authority/convergence_route_test.go - TestConvergenceRoute_RefreshEndpoint_ConfirmsAndClearsDesired - buildV1HeartbeatsWithAddrs helper (per-replica addr override for heartbeat construction) Publisher's directive is the real TopologyController (not a static ask list) so the route goes through decideVolume. go test ./core/authority -count=1 green (4.8s). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> |
||
|
|
0562aeb878 |
P14 S7: real-route restart closure (L1 component + L2 subprocess smoke)
Proves the S4-S6 control loop composes under restart and real-route pressure: durable authority reload -> observation replay -> controller recompute -> VolumeBridge delivery -> VolumeReplicaAdapter. Restart sequence pinned (sketch §5, adapter-BEFORE-bridge per round-3): lock -> store -> pub(reload) -> ctrl(reloaded reader) -> host(same reader) -> adapter -> VolumeBridge -> pub.Run + host.Start. Desired state is recomputed, not persisted (sketch §6). No DesiredStore, no StuckStore, no bootstrap-mint shortcut. Stale pre-restart observation rejected via existing basisMatchesLine, not a new bootstrap predicate. L1 (core/authority/restart_route_test.go, 8 tests + 4 stale sub-cases): row 1 reloaded authority via bridge to adapter; row 2 recompute (hard precondition + same-observation replay); row 3 stale observation (4 sub-cases via snapshottingReader host-reader freeze — test simulation shape per sketch §9, not a heartbeat-wire claim); row 4a old slot NOT revived from durable (S5 one-record-per-volume contract); row 4b live-route monotonic guard rejects bridge-delivered old slot from in-memory publisher; row 5 unsupported evidence via ConflictingPrimaryClaim; row 6 fence path bounded (Fence command reaches executor via real route; withheld callback does not produce spurious Healthy); row 7 per-volume isolation on restart. L2 component (cmd/sparrow/s7_bootstrap_test.go): rows 8/9/10a via in-process Bootstrap two-run, asserting directly on ReloadedRecords, ReloadSkips, VolumeAuthorityLine. No backward mint across restart. L2 subprocess (cmd/sparrow/s7_restart_smoke_test.go): row 10b via real sparrow binary spawn twice against the same store dir. Asserts exit 0 on both runs, lock released between runs, second-run structured stdout reports the durable line the first run wrote, backwardMint=false. cmd/sparrow additions: - --s7-restart-smoke flag (test-only, undocumented in --help) - runS7RestartSmoke entry with pinned JSON pass-line schema - parseFlags rules: requires --authority-store, mutually exclusive with --s5-bootstrap Helpers: restartRoute / simulateRestart (single pinned construction seam; no direct adapter.OnAssignment anywhere; uses VolumeBridge, not hand-rolled Bridge goroutines); restartExecutor (fence-mode configurable pre-loop); snapshottingReader.forceSet for stale-basis simulation. Engine/adapter/transport: no changes. Row 4 honesty split (round-5c): durable restart discards old-slot state by S5 design, so "old-slot rejected on restart" is proved by ABSENCE; the monotonic-guard proof belongs to a pre-restart live-route test where in-memory per-replica keys legitimately exist. Row 6 explicitly defers the full timeout- expiry quantitative bound to the adapter's own tests (sketch §10.1 Path B forbids S7 from reconfiguring the fence path). Residual: Windows TempDir teardown can race with lock-file release; logged as residual per sketch §8.5 scope — durable-store write/reload errors remain hard failures. go test ./core/authority ./cmd/sparrow ./core/adapter -count=1 green. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> |
||
|
|
a837a67ec6 |
P14 S6: convergence institution (bounded wait + stuck evidence)
Turns controller desired assignments into a bounded-fate closure: confirmed, retried (passively), superseded, or surfaced as stuck evidence — without minting new authority. - DesiredAssignment: +ProposedBasis/DesiredAt/LastRetryAt/Stuck. - TopologyControllerConfig: +RetryWindow (default 5s). - convergence.go: ConvergenceStuckEvidence (distinct map from UnsupportedEvidence), supersedeDesiredLocked (case 1 only: publisher epoch > ProposedBasis AND different target — case 2 dropped because it misclassified every in-flight Reassign), evaluateStuckLocked (passive; does NOT re-emit). - controller.go: unified processSupportedVolumeLocked; confirm routes through clearDesiredLocked so late post-Stuck confirmations drop stuck evidence; supported-recovery clears prior UnsupportedEvidence. L0 (convergence_test.go): 15 targeted proofs — confirmation (both-sources, stale-observation guard), stuck (after window, no Reassign churn, clears on late confirm), supersede (publisher moved elsewhere, normal-lag is NOT supersede, decision-table differs), pending/unsupported clearing, per-volume isolation, supported-recovery evidence cleanup. L1 (convergence_route_test.go): 3 component-route proofs through ObservationHost -> TopologyController -> Publisher -> VolumeBridge -> Consumer: observation-fed failover confirms, publish-but-not-observed reaches Stuck with no duplicate bridge delivery, supersede drops stale desired. No engine/adapter/transport changes. S2 non-forgeability and S5 store-write guards still pass. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> |
||
|
|
47eb1f6f8d |
P14 S5: durable authority institution + live sparrow bootstrap
Introduces the P14 S5 durable-authority layer: Publisher state
survives control-plane restart via an atomic-rename file-per-
volume store, guarded by a cross-platform OS-level single-owner
lock, with startup wiring in cmd/sparrow that acquires the lock
and reloads durable truth before live publication begins.
Load-bearing boundaries held (sketch §3):
* durable authority store may preserve and reload truth, but
it may NEVER mint truth. Publisher is the sole minter of
Epoch / EndpointVersion; the store persists values already
minted and reloads them verbatim at boot.
* AST boundary guards (from S5 sketch §12) enforced at test
scope: no non-authority code constructs a DurableRecord with
non-zero Epoch/EndpointVersion, no non-authority code calls
store.Put.
Core store and interface (core/authority/):
* authority_store.go — DurableRecord shape (per-volume current
line; no per-slot history, no append log, no wall-clock
freshness field); AuthorityStore interface with Load /
LoadWithSkips / Put / Close; SHA-256-checksummed JSON
envelope; per-record ErrCorruptRecord; index-level failure
distinguished from per-record skip.
* authority_store_file.go — file-per-volume FileAuthorityStore
with fsync + atomic rename on write; stale-tempfile cleanup
on Load; INJECTIVE filename encoding (every non-[a-zA-Z0-9-]
byte including '_' escapes as "_XX" — closes the earlier
"_002f" vs "/" aliasing gap).
* authority_bootstrap.go — AcquireStoreLock returning a
StoreLock whose OS-level file lock is dropped on handle
close, cross-platform crash-safe.
* authority_bootstrap_unix.go (build !windows) — syscall.Flock
with LOCK_EX|LOCK_NB.
* authority_bootstrap_windows.go (build windows) —
syscall.CreateFile with dwShareMode=0 exclusive share;
ERROR_SHARING_VIOLATION / ERROR_ACCESS_DENIED map to
ErrStoreLockHeld. Purely stdlib; no x/sys dependency.
Publisher integration (core/authority/authority.go):
* WithStore(store) functional option on NewPublisher. Nil /
omitted keeps existing in-memory behavior.
* Synchronous reload at construction: verifies records,
populates p.state, seeds p.writeSeqByVolume from max stored
WriteSeq. Per-record corrupt skips surface via LoadErrors()
(per-volume fail-closed; process continues).
* Synchronous write-through in apply(): DurableRecord built
under pub.mu, store.Put invoked before in-memory commit. On
Put failure the in-memory state is NOT mutated, subscribers
are NOT notified, and the caller gets a wrapped error — on-
disk and in-memory stay lock-step.
* Index-level load failure panics at construction (honors the
sketch §10 fail-the-whole-boot rule); the Bootstrap helper
converts this to a clean error return via a pre-check.
Live sparrow entry point (cmd/sparrow/):
* bootstrap.go — Bootstrap(storeDir, directive) helper that
performs the full startup sequence (lock → store → index
pre-check → NewPublisher with reload → log outcomes). Also
exposes BootstrapFromStore seam so tests can inject a mock
store to exercise the pre-check cleanup branch portably.
* s5_bootstrap.go — runS5Bootstrap mode invoked via
"sparrow --authority-store <dir> --s5-bootstrap". Acquires
lock, reloads, runs Publisher briefly, emits report, exits
cleanly. This is the one real non-test caller of the
durable route. The default demo path stays in-memory by
design (the Bind/Reassign smoke sequence is not restart-
clean, and forcing it to be would smuggle durability-aware
branches into SMOKE test code).
* main.go — --authority-store and --s5-bootstrap flags
rejected at parseFlags unless paired; --s5-bootstrap
dispatches to runS5Bootstrap. Default modes unchanged.
Proof (core/authority/ + cmd/sparrow/):
* authority_store_test.go — round-trip, latest-wins per-volume,
corrupt-record per-volume fail-closed, atomic-write-no-torn
(orphan tempfile cleanup), process lock exclusivity +
idempotent release + survives stale lockfile on disk,
unreadable-index boot fails closed, wall-clock-NOT-consulted
on reload, AST boundary guards (store never mints, only
core/authority calls store.Put), filename encoding
injectivity + no-filesystem-unsafe-output, envelope shape.
* authority_restart_test.go — reload reproduces current line,
stale pre-failover record rejected, Publisher advances from
reloaded truth (not zero), Controller sees reloaded line at
boot, Put-failure rolls in-memory back, empty-store reload
yields fresh state, store-backed Publisher runs normal
Bridge route.
* cmd/sparrow/bootstrap_test.go — live Bootstrap tests: fresh
dir acquires lock + reloads, existing-record reloads into
Publisher state, corrupt record logged at startup (not
stranded in LoadErrors), lock contention refuses second
bootstrap, empty dir errors, Close idempotent,
ParseFlags_AuthorityStoreRequiresS5Bootstrap flag validation,
RepeatedRunsAreRestartClean (two runS5Bootstrap invocations
on same dir with seeded record between — architect round-7
regression), PreCheckFailure_ReleasesLockAndClosesStore
(mock-injected index failure → lock released, store closed,
error returned — architect round-8/9 regression).
* observation_test.go — E2E SystemFedSnapshotReachesController
poll-loop fixed: was racing on first non-empty submission
(initial pending) instead of waiting for supported; now
polls until supported-v1 with 3 slots is observed.
No changes to engine, adapter, transport, ops, storage.
Authority package: 112 tests. cmd/sparrow: 19 tests. Full module:
12 packages pass.
Design docs in sw-block/design/ external repo:
* v3-phase-14-s5-assignment.md
* v3-phase-14-s5-durable-authority-institution.md
* v3-phase-14-s5-sketch.md
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
|
||
|
|
60c5ff5db4 |
P14 S4: observation institution + multi-volume topology controller
Lands two related pieces that make late-Phase-14 observation-to-
authority truth system-owned:
1. Multi-volume TopologyController (accepted P14 topology set:
per-volume three-slot on distinct servers). This was the
"consumer baseline" staged earlier as full-topology
scaffolding and is committed here as the foundation S4 feeds.
2. Observation institution: heartbeat / inventory -> stable
ClusterSnapshot producer, per the S4 assignment
(sw-block/design/v3-phase-14-s4-assignment.md and
v3-phase-14-s4-sketch.md).
Load-bearing boundary held across both pieces:
* observation institution may withhold supportability, but it
may NOT mint authority (sketch §3)
* Publisher stays the sole minter of Epoch/EndpointVersion
* adapter.OnAssignment stays the one and only consumer ingress
* no new engine event, command, or projection field
Observation-side deliverables (core/authority/):
* observation_types.go — Observation, ServerFact, SlotFact,
LocalRoleClaim, FreshnessConfig, Supportability enum
(pending / supported / unsupported kept VISIBLY distinct per
architect execution note), AcceptedTopology, six reason
constants.
* observation_store.go — push-ingest latest-wins per ServerID,
derived ServerFreshness (never-observed / bootstrapping /
missing / fresh / expired), immutable storeSnapshot for
builder input, configurable GC.
* observation_wire.go — V2 heartbeat wire shape port
(block_heartbeat / block_heartbeat_proto /
block_heartbeat_loop analogues) as mechanism only.
HeartbeatToObservation is a pure field-shape copy.
* unsupported_evidence.go — per-volume VolumeUnsupportedEvidence
(latest-wins per VolumeID), separate VolumePendingStatus,
SupportabilityReport with Pending + Unsupported as distinct
maps, BuildResult.
* snapshot_builder.go — pure BuildSnapshot(store, topology,
reader) -> BuildResult. Reads publisher's current per-volume
line via the read-only AuthorityBasisReader and stamps it in
VolumeTopologySnapshot.Authority for supported volumes, so
the controller's stale-resistance check can match on
subsequent feeds. Observation never mints authority.
* observation_host.go — owns store lifecycle, push-ingest
entry points, reactive rebuild (build-on-change + coalescing
wake), GC sweep honoring configured retain window,
ControllerSink atomic submission (snapshot + report
together so supportability transitions propagate even when
supported volumes drop to zero).
Controller-side intake (core/authority/controller.go):
* SubmitClusterSnapshot kept as the test-scaffolding entry.
* NEW SubmitObservedState(snap, report) — the observation-fed
intake. Mirrors SubmitClusterSnapshot's convergence
discipline line-for-line (stale-basis preserves desired,
no-emit clears desired, same-ask dedupe prevents authority
churn) and adds pending/unsupported transition handling.
Under this intake, the controller hears every supportability
transition, including "zero supported volumes now", which
clears stale desired state.
V2 muscles ported (mechanism only):
* block_heartbeat / block_heartbeat_proto field layout
(observation_wire.go)
* block_heartbeat_loop shape concept (host owns the loop)
Explicitly NOT ported (per assignment denylist):
* weed/storage/blockvol/promotion.go
* old HandleAssignment / promote / demote ownership
* master_block_plan / master_block_failover / master_block_registry /
master_block_assignment_queue (reference only for S5/S6)
* any V2 path where heartbeat timing or local status becomes
failover truth
Proof matrix (observation_test.go — 35 tests covering all sketch
§16 rows + architect-round regressions):
Authoring:
- PartialInventory_PendingThenUnsupported
- MissingServerObservation_NeverOrdinaryIneligible
- EndToEnd_SystemFedSnapshotReachesController
- ConflictingPrimaryClaim_Unsupported
- ConflictingPrimaryClaim_NoWinnerEverChosen
- ExpiredFact_SemanticallyIneligible
- ExpiredDoesNotReachController
- BadVolumeDoesNotBlockHealthyVolume_Isolation
- VolumeUnsupportedEvidence_IsolatedPerVolume
- DuplicateServerTopology_UnsupportedAndEvidenceRecorded
- DuplicateServerTopology_NotControllerInput
Host-level:
- IngestMutation_TriggersSnapshotRebuild
- FreshnessWindowHonored_NotTickMultiples
- GCRetainWindow_Honored
Boundary (AST-based, sketch §16a):
- NeverMintsAuthority_BoundaryGuard
- SupportabilityDoesNotReadClusterSnapshotOutput
Architect round-2 regressions:
- BuilderStampsAuthorityFromReader
- SupportabilityCollapsePropagatesToController
- SupportabilityCollapseClearsControllerDesired
- UnknownObservedVolume_ProducesUnsupportedEvidence
Architect round-3 regressions:
- IdenticalSupportedSnapshots_NoDuplicateAsks
- VolumeRecovers_ClearsStaleDesired
No changes to engine, adapter, transport, ops, storage, or
sparrow. 91 authority tests pass. Full module: 12 packages pass.
Design docs in sw-block/design/ external repo:
* v3-phase-14-s4-assignment.md
* v3-phase-14-s4-observation-institution.md
* v3-phase-14-s4-sketch.md
* v3-phase-14-s4-closure-gaps.md (architect-round boundary notes)
* v3-phase-14-full-topology-design.md
* v3-phase-14-placement-rebalance-policy.md
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
|
||
|
|
0fc367f3a3 |
P14 S3: bounded policy owner + system-owned failover (two-slot topology)
Introduces the first accepted S3 slice: one explicit policy owner
behind the S2 Directive seam, with cross-slot failover proven
end-to-end through the existing authority publication route. The
accepted topology set for this slice is one volume, two replica
slots on distinct servers, one current primary, one failover
candidate.
Load-bearing boundaries preserved from S2:
* policy emits AssignmentAsk, never AssignmentInfo
* authority.Publisher remains the sole minter of Epoch /
EndpointVersion (enforced by the repo-wide AST
non-forgeability test)
* engine and adapter remain consumers; adapter.OnAssignment
stays the one and only consumer ingress
* Remove / retirement deferred
S2 boundary change absorbed via the reassign-semantic note
(sw-block/design/v3-phase-14-s3-reassign-semantic.md):
* IntentReassign is now a per-volume authority advance, not a
per-slot Epoch bump. Target ReplicaID may differ from the
currently-published replica. New Epoch is minted from the
max across (VolumeID, *) + 1. EV resets to 1 on the target.
Still requires SOME prior publish for the volume; first-time
establishment remains IntentBind.
* Per-slot EV monotonicity unchanged for IntentRefreshEndpoint.
Implementation (core/authority/):
* policy.go — PolicyOwner (Directive impl), AssignmentAsk input
model (AuthorityBasis, SlotObservation, PolicySnapshot),
PolicyConfig, AuthorityBasisReader (LastAuthorityBasis +
VolumeAuthorityLine), decision table (Bind /
RefreshEndpoint / Reassign), unsupported-topology evidence
with structured offending-basis artifact.
* authority.go — widened IntentReassign; new
VolumeAuthorityLine method on Publisher; new VolumeBridge
helper for system-owned retarget without test choreography;
new maxPublishedEpochForVolume helper.
Four ordered guards on every snapshot in PolicyOwner.Next:
1. distinct-servers invariant (empty ServerID or matching
non-empty ServerID -> unsupported evidence)
2. snapshot-side authority-in-topology (snap.Authority outside
the two slots -> unsupported evidence)
3. publisher-side out-of-topology authority (publisher's
current per-volume line on a replica not in the two slots
-> unsupported evidence carrying the offending Basis)
4. per-volume stale-resistance (snap.Authority must match the
current per-volume authority line on VolumeID, ReplicaID,
Epoch, EndpointVersion)
Closure proofs (core/authority/policy_test.go — 26 new tests):
Authoring (§13.1 of sketch):
- TestPolicy_NoAuth_OneAcceptable_EmitsBind
- TestPolicy_NoAuth_BothAcceptable_EmitsBindForPreferred
- TestPolicy_NoAuth_NeitherAcceptable_NoAsk
- TestPolicy_CurrentHealthy_Unchanged_NoAsk
- TestPolicy_CurrentHealthy_DataAddrChanged_EmitsRefresh
- TestPolicy_CurrentHealthy_CtrlAddrChanged_EmitsRefresh
- TestPolicy_CurrentUnacceptable_OtherAcceptable_EmitsReassign
- TestPolicy_CurrentUnacceptable_OtherUnacceptable_NoAsk
- TestPolicy_AuthOutsideTopology_NoAskPlusUnsupportedEvidence
- TestPolicy_UnsupportedTopology_AlwaysEmitsEvidence
- TestPolicy_OnlyThreeIntentsProduced
Stale-resistance (§13.2 + architect round 2 + round 3):
- TestPolicy_StaleDecision_DroppedWhenAuthorityAdvances
- TestPolicy_StaleRefresh_DroppedWhenNewerEndpointVersion
- TestPolicy_NewerSnapshotOverwritesOlder_OnlyLatestValidEmits
- TestPolicy_StaleSnapshotAfterCrossSlotFailover_Dropped
Topology honesty (architect round 3 + round 4):
- TestPolicy_EmptyServerID_NoAskPlusUnsupportedEvidence
- TestPolicy_BothSlotsSameServer_NoAskPlusUnsupportedEvidence
- TestPolicy_OutOfTopologyPublisherAuthority_NoAskPlusUnsupportedEvidence
(structured Basis assertions — evidence carries the
offending publisher line, not just a reason string)
Boundary:
- TestPolicy_NoDirectAssignmentInfoConstruction
- TestPolicy_DoesNotAddAdapterIngress
Reassign semantic regressions:
- TestReassign_CrossSlotMintsEpochPlusOne
- TestReassign_NoPriorVolumePublish_StillRejects
- TestReassign_PerSlotOpsOnOldSlotDoNotAdvanceVolumeLine
- TestReassign_PerSlotEndpointVersionMonotonicityPreserved
End-to-end closure (VolumeBridge-based, no test choreography):
- TestPolicyToAdapter_E2E_Bind
- TestPolicyToAdapter_E2E_Failover
- TestPolicyToAdapter_E2E_EndpointRefresh
- TestVolumeBridge_FollowsFailoverWithoutTestChoreography
- TestVolumeBridge_PostFailoverOldSlotRefreshRejectedByAdapter
(adapter rejects stale-identity input delivered through
VolumeBridge after cross-slot move)
- TestPolicyToAdapter_E2E_Failover_PublicationHonestyDuringTransition
(ack-gated window: adapter is non-Healthy at Epoch=2 until
FenceCompleted; observed deterministically via fence-hold
hook on the test executor)
No changes to engine, adapter, transport, ops, storage, or
sparrow. The S3 package is additive.
Authority package tests: 56 pass (30 from S1+S2; 26 new from S3).
Full module: 12 packages pass.
Design docs (in sw-block/design/ external repo):
* v3-phase-14-s3-audit.md
* v3-phase-14-s3-sketch.md
* v3-phase-14-s3-design.md
* v3-phase-14-s3-closure.md
* v3-phase-14-s3-reassign-semantic.md (boundary note)
* v3-phase-14-s3-closure-gaps.md (round 3 boundary note)
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
|
||
|
|
63ea717a75 |
P14 S2 fix²: close-safe delivery, catch-up ordering, pointer-form bypass
Addresses five architect findings across two review rounds, all on
the authority package introduced in
|
||
|
|
3d53563ca9 |
P14 S2 fix: per-subscription cancel, lossless-latest delivery, AST non-forgeability
Addresses three architect findings on the first S2 drop:
1. High: Unsubscribe(vid, rid) was key-wide — one Bridge exiting
silently closed channels for all other peers on the same
(VolumeID, ReplicaID). Replaced with per-subscription cancel:
Subscribe now returns (ch, cancel func). Each cancel closes only
its own subscription. Publisher owns a nextSubID counter and
tracks subscriptions as []*subscription per key. Cancel is
idempotent and safe against concurrent Run-exit teardown via a
"whoever finds it closes it" protocol.
Regression test: TestPublisher_IndependentUnsubscribe_OtherPeersUnaffected.
2. High: silent drop on full subscriber buffer could leave the
adapter on stale authority truth until an unrelated later ask
happened — unacceptable for an authority route. Per-subscription
channels are capacity 1 with overwrite-latest semantics: on full,
the publisher drains the stale pending value and retries send,
so the subscriber always reads the LATEST authoritative state
next. Intermediate states may be coalesced (correct for authority
truth; the engine cares about current identity, not interstitial
history).
Regression test: TestPublisher_DeliveryConvergesToLatestOnSlowConsumer.
3. Medium: the non-forgeability structural test was a regex-based
grep over core/ only, and caught only composite-literal Epoch
assignments. Rewritten as an AST-based walker that (a) covers
the whole repo (cmd/ and future production packages included,
not just core/) and (b) catches both composite-literal mints
with non-zero Epoch/EndpointVersion AND local variable
declarations of type AssignmentInfo — the classic bypass shape
for deferred mutation: `var x AssignmentInfo; x.Epoch = input`.
The stronger check surfaced three pre-existing hidden operator
paths in cmd/sparrow/main.go that minted AssignmentInfo with
hard-coded epochs 1/2/3 directly. All three demo sites are now
routed through a shared authority.Publisher: healthy demo issues
IntentBind, catch_up and rebuild demos issue IntentReassign.
No sparrow demo code constructs AssignmentInfo directly anymore.
Other:
* Run now closes every live subscription channel on exit, so
Bridges observe end-of-stream cleanly. Tested by
TestPublisher_RunClosesLiveSubscriptionsOnExit.
* Publisher.apply() releases the publisher lock before fan-out,
preventing a slow consumer from stalling the authoring loop.
Docs updated:
* docs/p14-s2-design.md — Publication API now documents
per-subscription cancel, removes the stale Unsubscribe(vid,rid)
verb, adds the "lossless for current fact" delivery semantic.
* docs/p14-s2-closure.md — test list updated (20 tests), Changed
section records the sparrow migration.
No changes to engine, adapter, transport, ops, storage.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
|
||
|
|
5c663b8c83 |
P14 S2: bounded authority publication route for assignment truth
Introduces the core/authority/ package — the system-owned publication
route where Epoch and EndpointVersion are authored, not relayed. The
publisher is the only production code that constructs an
adapter.AssignmentInfo with a non-zero Epoch.
Contract boundaries (load-bearing):
* S2 owns publication of authority truth.
* S2 does NOT own failover policy.
* Engine and adapter remain consumers, not producers.
Design:
* Publisher.Run consumes AssignmentAsk values from an injected
Directive and fans out AssignmentInfo to subscribers keyed by
(VolumeID, ReplicaID) — not by ReplicaID alone, which would
multiplex different volumes that share a replica name.
* AssignmentAsk carries no Epoch and no EndpointVersion. The
publisher mints both from the intent enum (Bind | RefreshEndpoint
| Reassign). Retirement (Remove) is deliberately deferred.
* No public verb accepts a preformed AssignmentInfo. The former
PublishAssignment relay verb was removed from the design before
code — the publisher is a minter, not a pass-through.
* Directive is the seam where P14 S3's failover policy will later
plug in without reaching into the publisher. S2 ships only
StaticDirective.
* Bridge forwards publisher output to adapter.OnAssignment — the
adapter remains the one and only consumer entry point; no second
mutation ingress was added.
Tests (core/authority/authority_test.go):
* Intent semantics: Bind mints epoch=1 ev=1; RefreshEndpoint keeps
epoch and bumps ev (no-op on unchanged addrs); Reassign bumps
epoch and resets ev=1; each invalid precondition is rejected.
* Fan-out keyed by (VolumeID, ReplicaID): two subs on the same key
both receive; a sub on a different volume for the same replica
name does NOT receive — regression for the narrow-key bug.
* Late-subscriber catch-up via LastPublished.
* Run loop drives Directive until ctx cancel; rejected asks are
logged and loop continues.
* Bridge forwards to AssignmentConsumer.
* Closure target integration test: Publisher -> Bridge -> real
VolumeReplicaAdapter reaches Mode == ModeHealthy without any
harness.assign call.
* Non-forgeability structural test walks core/ and fails if any
production file outside an explicit allowlist (authority /
calibration / conformance / schema) constructs an AssignmentInfo
with a non-zero Epoch.
Docs:
* docs/p14-s2-audit.md — scoped audit of existing producers /
publishers / consumers / hidden-operator-path smells / V2 port
candidates.
* docs/p14-s2-design.md — bounded design: load-bearing boundaries,
closure target, package layout, AssignmentAsk shape, authoring
rules table, publication API, Bridge model, V2 port plan,
explicit non-goals and acceptance criteria.
* docs/p14-s2-closure.md — what S2 closed, what stayed out, S2/S3
boundary table, verification recipe.
No changes to engine, adapter, transport, ops, storage, or sparrow
wiring. The authority route is additive.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
|
||
|
|
dec084485b |
P14 S1: proactive R>=H fence with ack-gated healthy publication
Adds an explicit FenceAtEpoch command + FenceCompleted/FenceFailed
event pair on the caught-up recovery branch. A replica with R >= H
under a newer identity epoch is no longer declared healthy until the
replica's lineage gate has been bumped to match Identity.Epoch via a
FenceCompleted — closing the window where stale old-epoch traffic
could still land on the replica while the projection already reads
healthy.
Contract surface:
* Caught-up path emits ONLY FenceAtEpoch — no catch-up / no rebuild.
Fence is a command+event pair, not a session lifecycle.
* PublishHealthy held until FenceCompleted advances FencedEpoch.
Publication and DeriveProjection both gate on this so the
operator-visible mode reflects the ack-gated contract, not
just the command stream.
* FenceFailed is fail-closed: FencedEpoch is NOT advanced; retry
is probe-driven (next successful probe re-runs decide() and
re-emits FenceAtEpoch).
* Session completion (catch-up / rebuild) implicitly fences,
because mutating traffic at the current epoch already bumped
the replica's gate.
* Stale FenceCompleted (epoch < Identity.Epoch, or same epoch
with older endpointVersion) is rejected without mutating state.
* FencedEpoch is engine-internal; NOT exposed in ReplicaProjection.
Adapter-side fence dispatch:
* fenceInFlight keyed by fence LINEAGE
(replicaID, epoch, endpointVersion), NOT by replicaID alone.
This prevents a newer-epoch fence from being starved by an
older in-flight fence — both occupy distinct slots, the old
one is dropped by the engine as stale when its callback lands,
and the newer one drives publication to healthy without
waiting for an unrelated later probe.
Proof tests:
* engine: TestFence_CaughtUpPath_UsesNoDataRecovery
* engine: TestFence_HealthyOnlyAfterFenceComplete
* engine: TestFence_FailureLeavesFencedEpochUnchanged
* engine: TestFence_StaleOldEpochRejectedAfterFenceOnCaughtUp
* adapter: TestFullRoute_CaughtUp_NotHealthyUntilFenceComplete
* adapter: TestFence_NewerEpochNotStarvedByOlderInFlightFence
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
|
||
|
|
2f07922234 |
P8-P12: local data process, lineage protocol, data-sync, recovery-execution, single-node surface, replicated durable slice
* storage: local data process — admission, flusher, and experimental extent-direct backend
Names the local data process (read / write / flush / checkpoint /
recover on one node) as a bounded institution with an explicit
crash model and carry-forward boundaries. Adds WAL admission
backpressure, a background flusher that drains WAL entries into
the extent, and an experimental metadata-only backend alongside
the regular WAL+extent backend. Both backends implement the same
LogicalStorage interface and pass the shared contract test suite.
Admission controller ports the battle-tested watermark algorithm
from the in-production engine: 0.7 soft / 0.9 hard, counting
semaphore for concurrent writers, deadline governing the whole
Acquire call, flusher wakeup via a dedicated urgent-notify seam.
Defaults intentionally absent at the admission layer — callers
set them explicitly, same contract as the source.
Flusher processes the entire dirty-map snapshot per cycle; the
on-disk checkpoint is bumped to the highest LSN verified-and-
flushed. Compare-and-delete cleanup preserves concurrent writes
that bumped an LBA's LSN after the snapshot was taken.
The experimental backend (core/storage/smartwal) writes data to
the extent first and appends only a small metadata record to a
ring. Reads bypass the ring entirely. A group committer batches
concurrent fsyncs.
Adopting the extent-direct backend as the default would be a
separate decision; this change only makes it available behind the
same interface.
Docs: docs/local-data-process.md names the institution, its crash
windows per backend, and the explicit carry-forward list.
* protocol: close recovery around explicit lineage at every layer
Every recovery start now carries (epoch, endpointVersion, sessionID,
targetLSN) — a single tuple that travels from engine decision through
adapter command, transport wire, replica ingress, and back via ack.
Each layer rejects messages whose lineage doesn't match the contract
it currently believes is active, so stale work cannot leak between
layers.
Engine: probe / catch-up / rebuild commands carry epoch +
endpointVersion. ProbeFailed and RecoveryFactsObserved are now
treated as lineage-bearing observations and dropped if stale.
Same-observation reorder fix is preserved and extended so reversed
probe/facts arrival still converges. Zero-valued epoch /
endpointVersion are rejected at event ingestion with a clear trace
key, not silently at the wire.
Adapter: each Start* command mints a fresh process-wide sessionID
and feeds it synchronously through the executor and engine, so
every outbound mutation can carry it.
Transport: invalidated sessions are canceled — the active session
holds its conn, and InvalidateSession closes the conn directly so a
goroutine parked in ReadMsg unblocks immediately. Recovery conns
have explicit deadlines on every write/read. Mutating wire frames
(ShipEntry, RebuildBlock, RebuildDone, BarrierReq) carry the full
lineage tuple. Replica ingress rejects stale lineage and closes the
connection without partial application.
Rebuild: blocks now apply with the engine's frozen targetLSN
instead of a placeholder, so a future LSN-aware ApplyEntry guard
won't silently drop rebuild data. The primary returns success only
after reading BarrierResp from the replica with the actually
achieved frontier — never on EOF, timeout, or a non-terminal phase
ack.
Tests: adversarial coverage at every layer — stale transport-epoch
events at the engine, stale callback drops at the adapter, mid-
session invalidation interrupting a blocked ack read at the
transport, stale wire-lineage rejection at the replica, and a
calibration handoff/stale-probe scenario.
README adds a roadmap table naming what each upcoming phase closes
and what it does not, so the project's bounded-closure model is
visible to readers.
* transport: institutionalize the data-sync layer
Names the bounded data-sync institution: catch-up byte movement,
rebuild byte movement, barrier exchange, achieved-frontier report,
and the lineage gate that fails closed on stale or overlapping
traffic. The institution does not own recovery classification,
session lifecycle policy, failover decisions, or operator
publication — those belong to later phases.
Splits transport into per-responsibility files so the boundaries
are visible on the page:
executor.go — session lifecycle + probe (observation only)
catchup_sender.go — primary-side catch-up byte movement
rebuild_sender.go — primary-side rebuild byte movement
barrier.go — typed BarrierResponse and helpers
replica.go — per-message-type handlers, lineage gate
Catch-up and rebuild each keep their own ship loop. The two
protocols look similar today but have different terminators (barrier
vs RebuildDone) and shouldn't share a hidden implementation that
would mask their divergence later.
BarrierResponse replaces the bare 8-byte uint64 wire reply with a
typed struct {AchievedLSN uint64}. The replica reports what Sync()
actually returned; the primary returns that value verbatim. Short
or unexpected payloads now fail closed instead of silently
fabricating a frontier.
Replica handler dispatch extracted into named per-message methods
(handleShipEntry, handleProbeReq, handleRebuildBlock,
handleRebuildDone, handleBarrierReq), each fronted by the same
acceptMutationLineage gate.
Five new fail-closed tests prove the institution's negative space:
- overlapping sessions: higher lineage bumps active state, older
session's in-flight frames are rejected
- primary mid-rebuild crash: subsequent higher-lineage session
converges, achieved frontier reflects the new session
- replica disconnects before BarrierResp: primary surfaces failure
with no fabricated AchievedLSN
- stale Ship after newer Rebuild: cross-message-type lineage
rejection
- probe during rebuild: probe is observation, does not disturb
activeLineage
Plus a typed-barrier roundtrip + short-payload-fails-closed test.
docs/data-sync-institution.md names what this layer owns, what it
does not, and the explicit carry-forward to later phases.
* chore: remove committed artifact .commitmsg
* engine, adapter, transport: close recovery-execution lifecycle
Admits one bounded recovery-execution institution around
engine-issued recovery commands: engine command → prepared →
real started or bounded timeout → cancel/invalidate/fail/complete
→ terminal close truth. Every stale or delayed callback fails
closed under lineage without reviving dead semantic truth.
Scaffolding (admitted earlier in this working session):
- SessionPrepared event splits "we accepted the contract" from
"runtime actually began execution". A dial failure or
invalidate-before-start no longer looks identical to a real
running session.
- OnSessionStart callback + SetOnSessionStart on CommandExecutor
tie SessionStarted to real execution start, not command
issuance. Transport emits it via signalSessionStart after
attachConn succeeds, with a registry recheck so an invalidate
between attach and signal drops the callback.
- startTimeout watchdog in the adapter arms on Start* only, fires
only if engine-state still matches (sessionID == q.sessionID
AND Phase == PhaseStarting), clears on real start or terminal
close. An old timer racing a newer session records fire_noop,
not a spurious failure.
Closure (this pass):
Engine trace detail enriched so ignored transitions name the
current phase ("current phase=failed") and session ID mismatch
traces distinguish older-session vs newer-session vs no-active-
session via phaseMismatchDetail(). Operators debugging a stale
callback can tell at a glance why it was rejected.
Adapter watchdog now records structured lifecycle events via
WatchdogLog(): arm, clear_started, clear_closed, supersede, fire,
fire_noop. Not an operator surface — execution evidence for tests
and diagnostic dumps.
New tests covering the required proof set:
engine/apply_test.go:
- TestV3_Terminal_DelayedFailureAfterCompletionIgnored
- TestV3_Terminal_DuplicateCompletedIgnored
- TestV3_Terminal_DuplicateFailedIgnored
- TestV3_Terminal_InvalidPhaseTransitionsLeaveStateUnchanged
adapter/watchdog_test.go (new):
- TestWatchdog_ClearedByRealStart
- TestWatchdog_ClearedByImmediateClose
- TestWatchdog_OldTimerCannotFailNewSession
- TestWatchdog_InvalidateBeforeStart_NoFalseStartNoFalseSuccess
transport/transport_test.go:
- TestTransport_Lifecycle_LateCompletionAfterInvalidateDropped
docs/recovery-execution-institution.md updated with per-scenario
proof table, separate watchdog contract table, and an explicit
"What is NOT proven here" section naming carry-forward for
multi-replica coordination, policy-driven invalidation, operator
surfaces.
Non-identity invalidation remains out of scope: the engine still
emits InvalidateSession only from identity-truth handlers
(assignment, removal). A SessionInvalidated reducer exists without
an emitter as forward-compatibility for the topology phase.
* ops: bounded single-node product surface
Makes the existing inspection endpoints read as one coherent
single-node product surface: self-describing, bounded, and
tested against its honesty rules.
Added two endpoints so the surface is product-shaped rather than
four scattered reads:
GET / surface map — scope + endpoints + read-only note
GET /diagnose bounded summary over projection + trace tail +
watchdog counters; full fidelity stays at the
dedicated endpoints
Every field exposed by /diagnose is derivable from the existing
State.Snapshot() — projection, trace, watchdog log. The surface is
a mirror over accepted lower truth, never a new authority path.
No HTTP mutation surface. Any mutation verb on any path still
returns 501. The surface-index test rejects cluster-shaped
vocabulary ("cluster", "failover", "promotion", "topology
authority", "rf3") in the self-description — an early draft of
the root endpoint's note used "Cluster-shaped control" and the
test caught it; the note was reworded positively.
Proof (core/ops/surface_test.go):
- TestSurfaceIndex_SelfDescribing: GET / lists exactly the paths
the mux wires, each with a non-empty Owns description.
- TestSurfaceIndex_WordingIsSingleNode: the surface declares
itself single-node and contains no cluster-shaped vocabulary.
- TestDiagnose_EmptyStateIsHonest: an empty-state /diagnose
returns zero/empty values, never fabricated fields.
- TestDiagnose_OnlyReadsLowerTruth: the /diagnose field set is
restricted to fields derivable from Snapshot(); any future
addition that isn't sourced from lower truth trips this test.
- TestSurfaceMutations_IncludesRootAndDiagnose: every mutation
verb on / and /diagnose returns 501.
New docs/single-node-surface.md names what the surface owns, what
it does not, and the explicit carry-forward: replicated status to
P12, topology/failover control to P14, operator governance surface
to P15.
README gets a "Single-node product surface" section linking to
the new doc. docs/bootstrap-validation.md updated to reference
/ and /diagnose, and to drop the "Phase 05" label — the doc is
now positioned as the CLI/endpoint reference, with the
product-shape view living in single-node-surface.md.
Also rolls in a small docs/recovery-execution-institution.md note
clarifying that the adapter watchdog's engine-state pre-check is
advisory; the engine phase guards remain the authoritative last
gate. This keeps a dual-layer guard visible to future maintainers
so they don't collapse the two into one convenience check.
* adapter: bounded replicated durable slice — handoff mechanism + fencing proof
Proves the first product capability beyond single-node operation:
given an external reassignment (epoch+1), the engine clears any
in-flight session, invalidates stale lineage, re-probes the
replica, decides catch-up or rebuild, and converges — while the
old primary's stale execution is rejected at every layer by the
lineage gate.
No new engine or transport mechanism was required. The lower
institutions (lineage gate, session lifecycle, data sync) compose
into a working handoff. P12's deliverable is the product-level
proof that this composition works.
Added adapter.OnRemoval(replicaID, reason) so the old primary's
demotion is expressible from outside the package.
Four multi-adapter handoff tests — two real adapters + two real
transport executors sharing one replica listener, no mocks:
TestHandoff_OldPrimaryToNewPrimary_Converges
A (epoch=1) reaches healthy; B (epoch=2) probes, recovers,
converges. Replica data matches B.
TestHandoff_StaleOldPrimaryTraffic_Rejected
After B's epoch=2 traffic establishes lineage on the replica,
stale epoch=1 frames are rejected at the data plane.
TestHandoff_RejoinAfterNewPrimary_DataConsistent
Every LBA the new primary wrote is byte-identical on the
replica after handoff.
TestHandoff_OldPrimaryDemoted_NoResurrection
After ReplicaRemoved, late callbacks from the old executor
cannot resurrect a healthy projection.
Durability claim (explicitly bounded): all writes the new primary
successfully barrier-ack'd are durable on the replica. Writes
in-flight on the old primary at reassignment that weren't ack'd
may be lost. The new primary's truth is authoritative.
Known limitation documented: if the new primary finds the replica
already caught up (R >= H), no mutating traffic establishes the
new epoch on the replica. Stale old-epoch traffic with a higher
sessionID could land. Low practical risk; deferred to P14 as a
proactive-fence concern.
docs/replicated-slice.md names what P12 proves (one bounded
failover/rejoin mechanism), what it doesn't (who decides primary,
when to fail over), and the carry-forward to P13/P14/P15.
* P8-P12: reconcile working tree with accepted phase closures
Reconciles the working tree so all accepted P10, P11, and P12
closures are present and consistent — no regressions, no stubs,
no doc/code mismatches.
P10 watchdog observability restored:
- armStartWatchdog/clearStartWatchdog record structured events
(arm, clear_started, clear_closed, supersede, fire, fire_noop)
into the adapter's watchdogLog field
- WatchdogLog() returns real data, not a nil stub
- clearStartWatchdog takes a WatchdogKind reason parameter so
clear-by-start is distinguishable from clear-by-close
- watchdog_test.go assertions are full strength — no skip-if-nil
guards
P10 engine trace detail restored:
- phaseMismatchDetail() helper distinguishes older-session,
newer-session, and no-active-session cases
- all session lifecycle handlers use enriched traces:
"current phase=failed" instead of "not in active phase"
- four terminal-lifecycle proof tests restored:
DelayedFailureAfterCompletion, DuplicateCompleted,
DuplicateFailed, InvalidPhaseTransitionsLeaveStateUnchanged
P11 single-node product surface restored:
- GET / (self-describing surface map) and GET /diagnose (bounded
summary) re-added to handlers.go and server.go
- surface_test.go recreated with all five honesty proofs
- server_test.go mux and mutation paths include / and /diagnose
- README endpoint list names all six read-only endpoints
- README "Single-node product surface" and "Replicated durable
slice" sections restored with doc links
- bootstrap-validation.md endpoint table and example curl block
include / and /diagnose; header repositioned as CLI/endpoint
reference with link to single-node-surface.md
P12 fixes preserved:
- replicated-slice.md route statement narrowed to distinguish
recovery-needed handoff (fenced) from R>=H (NOT fenced)
- TestHandoff_OldPrimaryDemoted_NoResurrection strengthened:
uses SetStepDelay to keep session active during removal, then
injects late OnSessionStart + OnSessionClose(success) — both
rejected
- "stops receiving assignments" wording corrected to "receives
explicit ReplicaRemoved"
- adapter.OnRemoval() public API added
- transport.BlockExecutor.SetStepDelay() exposed for test control
|
||
|
|
74c4f88cca |
docs: add engine surface taxonomy
## What this adds `docs/surface.md` is a taxonomy reference for the semantic core. It names every event, command, truth domain, and operator enum the engine currently exposes, so reviewers and contributors can see the full surface without re-reading the code. ## Counts (verified against current sources) | Dimension | Count | |---|---| | Events | 12 | | Commands | 6 | | Truth domains | 5 | | Operator `Mode` | 4 | | `RecoveryDecision` | 4 | | `SessionKind` | 3 | | `SessionPhase` | 5 | | `ProbeStatus` | 4 | | `ContactKind` | 5 | ## Why no single state diagram The doc explicitly argues against drawing a unified diagram and names what replaces it: - the reducer itself as the transition specification - invariants (C8 / C9 / C10 / C12 + the same-observation batch rule) - conformance YAML cases - per-run trace output Plus a list of per-dimension sub-diagrams that DO fit on one page for local review. ## Linked from README Single line under "Repo Layout" pointing to the new doc. |
||
|
|
7ed813a3b7 |
transport: fix doRebuild race — wait for replica barrier ack
## The bug `doRebuild` returned `AchievedLSN = targetLSN` immediately after writing `MsgRebuildDone`, then closed the connection. The replica's handler runs on a separate goroutine and might not have processed the rebuild blocks yet when `OnSessionClose` fires — tests that read replica state after close saw unapplied blocks. `TestTransport_Rebuild_DoesNotCorruptLBA0` flaked at ~40% locally. ## The fix Structural, not a sleep. The replica's `MsgRebuildDone` handler now replies with `MsgBarrierResp` carrying the actual synced frontier, sent **after** `Sync()` returns. The primary's `doRebuild` reads that ack before returning, mirroring the existing `doCatchUp` barrier contract. The `time.Sleep(50ms)` previously needed in `TestTransport_Rebuild_StreamsAndAdvancesFrontier` is no longer required and has been removed — the structural ack guarantees durability when `closeCh` fires. `AchievedLSN` reported to `OnSessionClose` is now the replica's real frontier rather than the primary's intent — a more truthful durability boundary. ## Verification - `TestTransport_Rebuild_DoesNotCorruptLBA0` 5/5 runs pass (was ~3/5 before) - Full transport suite green under `-count=5` - Full repo suite green |
||
|
|
7f9232af28 |
storage: persistence backend with crash-safe acked writes
Adds a single-node persistence layer behind a `LogicalStorage` seam that admits multiple implementations. The semantic engine, adapter, and calibration are unchanged — storage is execution machinery, not authority. ## Interface `core/storage/logical_storage.go` defines `LogicalStorage`. Both `BlockStore` (in-memory, existing) and the new `WALStore` satisfy it (compile-time assertions). Methods cover Write/Read/Sync/Recover, Boundaries (R/S/H), frontier control (AdvanceFrontier / AdvanceWALTail / ApplyEntry / AllBlocks), and lifecycle (Close). ## WALStore — default crash-safe backend `core/storage/walstore.go` plus supporting files (`wal_entry.go`, `wal_writer.go`, `superblock.go`, `dirty_map.go`, `recovery.go`, `group_commit.go`). - Single preallocated file: superblock + circular WAL + extent - Per-record CRC32 + EntrySize trailer detects torn writes - Group committer batches concurrent Sync callers into one fsync - Defensive past-head scan on Recover picks up writes that landed after the last superblock update - Idempotent recovery ## smartwal subpackage — experimental alternative `core/storage/smartwal/` (record / ring / superblock / store / recovery / tests / README). - 32-byte metadata records in a slot-based ring - Data goes directly to extent; reads always hit extent (no dirty map needed for the read path) - Last-writer-wins per LBA on recovery; CRC verified against extent block - Distinct magic byte from WALStore so files cannot be confused - Subpackage layout signals opt-in / experimental status; default remains WALStore ## Crash consistency for acked writes `TestWALStore_AckedWritesSurviveSimulatedCrash` and `TestSmartWAL_AckedWritesSurviveSimulatedCrash` both bypass `Close()` by dropping the file handle directly — no implicit fsync, no housekeeping. After reopen + Recover, every block whose Write was followed by a successful Sync is recoverable; pre-Sync writes may or may not be present but never corrupt acked data. ## sparrow `--persist-demo` Reproducible single-node demo: Write 4 blocks, Sync, Close, reopen, Recover, Read back. Removes prior demo file in the target dir before Round 1 so repeated invocations / CI runs work cleanly. Text and `--json` output. Exit codes documented in `docs/bootstrap-validation.md`. ## Contract test infrastructure `core/storage/contract_test.go` runs 11 contract assertions against each registered implementation via a factory table. Adding a third implementation is one entry in the table. ## Documentation `docs/persistence.md` describes the WAL+extent design, crash- consistency guarantees, what's NOT covered, file layout, on-disk record format, and the **Execution-layer scope decision**: `LogicalStorage` is the accepted persistence seam; `DataCommunicator` / `RecoveryExecutor` / `ProgressFeed` are deliberately deferred peer institutions. **Backing-store options** section documents the path to raw block device, O_DIRECT, FUA, and SPDK with concrete perf budgets — all preserve the seam. ## Required adjustments to existing code `BlockStore.Sync` changed from `() uint64` to `() (uint64, error)` so in-memory and on-disk implementations share one signature. Callers that ignored the return updated to discard explicitly. Replica barrier handler now propagates real fsync errors. ## Tests | Package | Count | |---|---| | `core/storage` | 26 (11 contract × 2 backends + 4 WALStore-specific) | | `core/storage/smartwal` | 16 (11 contract + 5 SmartWAL-specific) | | `cmd/sparrow` | 14 (added repeatability check for the demo) | Full repo green except a pre-existing flake on `TestTransport_Rebuild_DoesNotCorruptLBA0` (unrelated; addressed on a separate branch). |
||
|
|
aff28bc936 |
calibration: first scenario pass (C1-C5)
Adds the first calibration pass: five scenario families (C1-C5) that drive the accepted route and record expected-versus-observed evidence as machine-readable artifacts. ## Scenarios | ID | Family | What it proves | |---|---|---| | `CAL-C1-healthy-repeat` | C1 | Repeated probes on a caught-up replica do not trigger spurious recovery | | `CAL-C2-short-gap-catchup` | C2 | Short retained gap chooses catch-up; closes to healthy; data integrity preserved | | `CAL-C3-long-gap-rebuild` | C3 | Long gap beyond retained window chooses rebuild; closes to healthy; data integrity preserved | | `CAL-C4-terminal-close-only` | C4 | Healthy publication appears in the trace ONLY after `event: SessionClosedCompleted` (ordered check, not presence-only) | | `CAL-C5-order-stable` | C5 | Five same-replica delivery perturbations produce identical Decision, FinalMode, recoverySignature, and CloseEventCount | ## What changed - `core/calibration/` — new package - `result.go`, `harness.go`, `scenarios.go`, `report.go`, `scenarios_test.go` - `cmd/sparrow/calibrate.go` — wires `--calibrate` and `--calibrate --json` - `docs/calibration/scenario-map.md` and `divergence-log.md` — evidence templates seeded with the first-pass results - `README.md` and `docs/bootstrap-validation.md` — `--calibrate` advertised ## Evidence dimensions C5 compares across runs 1. `Decision` (derived from command path) 2. `FinalMode` 3. `recoverySignature` = (NCatchUp count, NRebuild count) 4. `CloseEventCount` (count of `SessionClosedCompleted` events in trace) 5. `DataIntegrityOK` Each has a distinct sentinel in the JSON artifact when it drifts. ## Tests - 14 calibration tests (5 per-scenario + 8 compare + 1 meta-test for the recovery-signature check) - Stable under `-count=10` stress - Full repo green |
||
|
|
bdc4845014 |
phase 05: bootstrap/inspection/validation surfaces on the sparrow
Extends the accepted sparrow (Phase 04) with narrow dev/test flags and a read-only HTTP inspection surface so outside readers and testers can start, inspect, and validate the runnable slice without deep design-doc archaeology. No new standalone operator CLI — `weed shell` remains the eventual production interface; this work is a standalone-repo sparrow improvement, not a competing CLI. ## What changed - `cmd/sparrow/main.go` — flag handling; `startHTTPOps` binds synchronously and surfaces errors honestly - `cmd/sparrow/scope.go` — authoritative `ScopeStatement` + `Version` - `core/ops/` — new package: `state.go`, `server.go`, `handlers.go` - `docs/bootstrap-validation.md` — operator-facing surface reference - `README.md` — Operations section ## Sparrow flags (all opt-in, default unchanged) | Flag | Effect | |---|---| | `--json` | machine-readable JSON summary | | `--runs N` | repeat the full demo N times | | `--http ADDR` | read-only HTTP ops server, stays up after demos | | `--help` | authoritative supported/unsupported scope | | `--version` | version string | ## Exit codes | Code | Meaning | |---|---| | 0 | all-pass | | 1 | any fail (validation use) | | 2 | usage / flag error | | 3 | runtime setup failure (currently: `--http` bind failed) | ## HTTP ops surface (behind `--http`) | Method | Path | Returns | |---|---|---| | GET | `/status` | version, uptime, scope, current demo | | GET | `/projection` | latest `ReplicaProjection` as JSON | | GET | `/trace` | latest adapter trace as JSON array | | POST/PUT/PATCH/DELETE | any path | 501 + structured "not supported" body | ## Anti-pattern guards held - ops package never calls `engine.Apply` directly - ops reads state only through `adapter.Projection()` / `.Trace()` - no ops handler chooses recovery semantics or redefines `targetLSN` - `ScopeStatement` shown by `--help` and `/status` is the same constant - no new standalone operator CLI binary ## Honest bind `startHTTPOps` calls `net.Listen` synchronously and returns an error if the port cannot be bound. `--http` never falsely claims "listening" when it is not. The bound address shown to the user is the actual listener address (useful for `--http :0` random-port). ## Tests | Package | Count | |---|---| | `cmd/sparrow` | 12 (flag parsing, scope content, repeatable runs, HTTP bind happy path, HTTP bind port-conflict failure, end-to-end exit-code 3 on bind failure) | | `core/ops` | 26 (handlers, 501 on every verb × path, state) | Pre-existing flake `TestTransport_Rebuild_DoesNotCorruptLBA0` is unrelated; `fix/rebuild-race` branch addresses it separately. |
||
|
|
2b6ce9b202 |
fix: same-observation events enter engine as atomic batch
OnProbeResult routes ProbeSucceeded + RecoveryFactsObserved from the same probe through applyBatchAndExecute, so both enter the engine under one lock hold — no unrelated event can interleave between them. Shared bookkeeping lives in applyEventLocked; both the batch and single-event paths go through it, so the trace / projection / command accumulators can't drift again. ApplyLog returned from OnProbeResult is now complete (EventKind, full Trace including session events, post-session Projection). An ingress rule is pinned in code: multi-fact observations MUST route through applyBatchAndExecute, and any new multi-fact ingress needs its own contention test. Tests: - TestBatch_UsesBatchPath: EventKind prefix, both event markers in Trace, Projection reflects post-apply state - TestBatch_LogIncludesSessionEvents: SessionPrepared/Started markers present in returned log.Trace - TestBatch_AtomicUnderContention: 4 goroutines fire competing events while main fires 2000 probes; scans trace event markers to prove ProbeSucceeded is always immediately followed by RecoveryFactsObserved. Vacuity guard requires real contention. |
||
|
|
60103e5f7b |
Block semantic engine + runnable block sparrow (#1)
* V3 mini engine: Phase 01 + 02 + 03 initial implementation Phase 01 — Semantic Core (engine/): - 5 truth domains, 11 events, 6 commands, deterministic Apply() - Stale rejection, terminal truth, wrong-replica guard - 17 conformance tests Phase 02 — Reference Runtime (schema/ + runtime/ + conformance/): - YAML case loader with strict validation - Replay runner with expectation checker - 7 cases, 7 determinism proofs, 5 loader tests Phase 03 — Adapter (adapter/): - Single route: observation -> engine -> command -> executor - CommandExecutor with SetOnSessionClose callback - Command dispatch outside lock, session ID owned by adapter - 8 constraint tests (C8/C9/C10/C12 + callback + full route) 44 tests total, all passing. * Phase 04: runnable block sparrow with real TCP transport First public runnable slice of seaweed-block. Demonstrates three recovery paths end-to-end through a deterministic semantic engine: 1. Healthy: replica caught up (R >= H), no recovery needed 2. Catch-up: short gap (R >= S, R < H), ship blocks via TCP 3. Rebuild: long gap (R < S), full base copy via TCP Package structure (renamed v3mini/ -> core/): core/engine - deterministic Apply(state, event) reducer core/adapter - single-route adapter with async callback wiring core/schema - YAML conformance case loading (strict fields) core/runtime - replay runner for conformance oracle core/conformance - 7 YAML cases + determinism + loader tests core/storage - in-memory block store with LSN tracking core/transport - TCP protocol, replica listener, block executor cmd/sparrow - runnable demo binary 51 tests, all passing. Sparrow runs via: go run ./cmd/sparrow Key design rules enforced: - Engine decides, executor executes (C12) - Same facts produce same decision (C8) - Timer only triggers probe, never recovery (C9) - No transport state in engine (C10, recursive reflect guard) - Terminal truth only from SessionClosedCompleted - Executor honors engine-issued targetLSN exactly - Session close callback wired from executor to adapter to engine - Command dispatch outside adapter mutex (no deadlock risk) - Rebuild uses AdvanceFrontier (no LBA 0 corruption) - Catch-up reports barrier-confirmed achievedLSN, not intent * fix: address CodeRabbit/Gemini review findings 1. Max payload limit in ReadMsg (16MB cap, prevents memory exhaustion) 2. Session ID race fix: capture IDs under lock in buildSessionEvents, pass via map to executeCommand — no re-locking needed 3. Barrier response error handling in replica listener 4. Demo 1 uses waitForMode polling instead of fixed sleep 5. ApplyEntry validates data size matches blockSize 6. Rebuild test timing: small delay for replica Sync after MsgRebuildDone |
||
|
|
723719b3df | Initial commit |